<commit_before>
// Define the main API
var divIDE = {
  ctxTarget: undefined,

  showMenu: function (event){
    divIDE.clearMenu();
    divIDE.ctxTarget = $(event.target);
    var panelType = divIDE.ctxTarget.attr('panelType');
    if (panelType == undefined){
      divIDE.ctxTarget = divIDE.ctxTarget.closest('[paneltype]');
      panelType =  divIDE.ctxTarget.attr('panelType');
    }
    var panelMenu = divIDE.panelTypes[panelType].showMenu;
    if (panelMenu == undefined){
      divIDE.showMenuType(panelType);
    } else {
      divIDE.panelTypes[panelType].showMenu(panelType, event);
    }
  },

  showMenuType: function(panelType){
      event.stopPropagation();
      event.preventDefault();
      var ctxMenu = $("#" + panelType + "CtxMenu")[0];
      ctxMenu.style.display = "block";
      ctxMenu.style.left = (event.pageX - 10)+"px";
      ctxMenu.style.top = (event.pageY - 60)+"px";
  },

  clearMenu: function (elem){
//     divIDE.ctxTarget = undefined;
    var ctxMenus = $(".ctxMenu");
    for (var i=0; i < ctxMenus.length; i++){
        ctxMenus[i].style.display = "none";
        ctxMenus[i].style.left = "";
        ctxMenus[i].style.top = "";
    }
  },
  panelTypes: {
  },

  registerPanel: function (panel) {
    divIDE.panelTypes[panel.name] = panel;
    var topMenus = panel.topMenuItems;
    if (topMenus != undefined){
      divIDE.addTopMenuItems(panel);
    }
    var ctxMenus = panel.contextMenuItems;
    if (ctxMenus != undefined){
      divIDE.addContextMenuItems(panel);
    }
    var panelHTML = panel.panelHTML;
    if (panelHTML != undefined){
      divIDE.addPanelTemplate(panel);
    }
    var ready = panel.ready;
    if (ready != undefined){
      panel.ready();
    }
  },
  // helper function for recursion
  _addSubMenus: function (menus, idprepend){
    if (idprepend == undefined){
      var idprepend = '';
    }
    var html = '';
    for (key in menus){
      var attrs = '';
      for (attrkey in menus[key]){
        if (attrkey == 'subMenus'){
          continue
        }
        attrs += " " + attrkey + '="' + menus[key][attrkey] + '" ';
      }

      var litext = '
';
      var ultext = '
';

      html += litext + '\
        ' + key + '';
      if (menus[key].subMenus != undefined){
        html += ultext;

        html += divIDE._addSubMenus(menus[key].subMenus);
        html += '\

'
      }
      html += '\

';
    }
    return html;
  },

  addTopMenuItems: function(panel){
    var parent = $('#topMenu').children();
    var html = '';

    // Add up them htmls
    html += divIDE._addSubMenus(panel.topMenuItems, 'topMenu');
    parent.append(html);
  },

  addContextMenuItems: function (panel) {
    var parent = $('#CtxMenus')
    var html = '\

\

'

    // Add up them menus
    html += divIDE._addSubMenus(panel.contextMenuItems);

    // Add closing div and ul text to go with context menus
    html += '\

 \

'
    parent.append(html);
  },

  panelTemplateId: function(panel) {
    return panel.name + 'Template';
  },

  panelTemplateClass: 'divIDEPanelTemplate',

  addPanelTemplate: function (panel) {
    var parentElem = $('#panelTemplates');

    //make a div with an id that we can predict
    var div = document.createElement('div');
    $(div).addClass(divIDE.panelTemplateClass);
    $(div).attr('id', divIDE.panelTemplateId(panel));
    $(div).html(panel.panelHTML(parentElem));
    parentElem[0].appendChild(div);
  },

  // TODO: This needs work for exporting
  containerContents: function (elem){
    var contents = [];
    var children = $(elem).children('div');
    for (var i = 0; i < children.length; i++){
      var child = $(children[i]);
      contents.push({
         divType: $(elem).attr('panelType'),
         classes: child.attr('class'),
         id: child.attr('id'),
         style: child.attr('style'),
         data: {
             contents: divIDE.containerContents(child),
             width: child.css('max-width'),
             height: child.css('max-height'),
             flex: child.css('flex')
         }
      });
    }
    return contents;
  },

  // Setting up the common functions, general utility
  // Downloading a file: http://stackoverflow.com/questions/3665115/create-a-file-in-memory-for-user-to-download-not-through-server
  download: function(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
  },

  // Looks like importing is trickier: https://www.html5rocks.com/en/tutorials/file/dndfiles/
  // Importing/reading a single file: http://stackoverflow.com/questions/3582671/how-to-open-a-local-disk-file-with-javascript
  upload: function(e, callback) {
    var file = e.target.files[0];
    if (!file) {
      return;
    }
    var reader = new FileReader();
    reader.onload = function (e) {
        callback(reader.result);
    }
    // This function is asynchronous, which means we have no idea when it will happen.
    // As such, after it's finished, we need to have a callback to do something with the
    // results. Hence the above callback function.
    reader.readAsText(file);
  }
}

// Main panel definition
var main = {
  name: "mainDivIDE",
  contextMenuItems: {
    "Add Panel": {
      id: 'mainAddPanel',
      onclick: 'layout.addPanel()',
    },
    "Align": {
      id: 'mainAlign',
      subMenus: {
        "Vertical": {
          id: "mainAlignVertical",
          onclick: 'layout.alignVertical()'
        },
        "Horizontal": {
          id: "mainAlignHorizontal",
          onclick: 'layout.alignHorizontal()'
        }
      }
    }
  },
  topMenuItems: {
    File: {
      subMenus: {
        Open: {
          id: 'tmFileOpen'
        },
        Recent: {
          id: 'tmFileRecent',
          subMenus: {
            item1: {
              id: 'item1'
            },
            item2: {
              id: 'item2'
            }
          }
        }
      },
      id: "tmFile"
    }
  },
  showMenu: function(panelType, event) {
    if ($('#tmLayoutEdit').data('clicks')){
      divIDE.showMenuType(panelType);
    }
  },

  ready: function () {
    var mainDivIDE = $("#mainDivIDE")[0];
    mainDivIDE.addEventListener("contextmenu", divIDE.showMenu, false);
    mainDivIDE.addEventListener("click", divIDE.clearMenu, false);
    $(mainDivIDE).addClass('borderStyle rowItems divIDELayout');
    $(mainDivIDE).attr('panelType', 'mainDivIDE')

  }
}

// Layout panel definition
layout = {
  name: "DivIDELayout",
  panelHTML: function(parentElement) {
    var html = "\

 \

\
          Width:	 \
          <input type='number' min=0 max=2048 class='layoutWidth' value='1' onchange='layout.boxWidthChange(this)'> \
          </input> 	 \
           <select class='unit' onchange='layout.boxWidthChange(this)'> \
                <option value='flex'>flex</option> \
                <option value='px'>px</option> \
               </select> \
          	 \

 \

\
          Height:	 \
          <input type='number' min=0 max=2048 class='layoutWidth' value='1' onchange='layout.boxHeightChange(this)'> \
          </input> 	 \
           <select class='unit' onchange='layout.boxHeightChange(this)'> \
                <option value='flex'>flex</option> \
                <option value='px'>px</option> \
               </select> \
          	 \

 \

";
    return html
  },

  contextMenuItems: {
    "Add Panel": {
      id: 'mainAddPanel',
      onclick: 'layout.addPanel()',
    },
    "Remove Panel": {
      id: 'mainRemovePanel',
      onclick: 'layout.removePanel()',
    },
    "Align": {
      id: 'mainAlign',
      subMenus: {
        "Vertical": {
          id: "mainAlignVertical",
          onclick: 'layout.alignVertical()'
        },
        "Horizontal": {
          id: "mainAlignHorizontal",
          onclick: 'layout.alignHorizontal()'
        }
      }
    }
  },
  topMenuItems : {
    Layout: {
      subMenus: {
        Edit: {
          id: 'tmLayoutEdit',
          onclick: 'layout.layoutEdit(this)'
        },
        Save: {
          id: 'tmLayoutSave',
          onclick: 'layout.exportLayout()'
        },
        Load: {
          id: 'tmLayoutLoad',
          onclick: "$('#tmLayoutLoadFile').click()",
        }
      },
      id: "tmLayout"
    }
  },

  data: {
      callbackFunctions: [],
      dataLinks: {},
  },

  getPanelData: function(elem) {
    var trs = $(elem).find('tr');
    var data = {};
    for (var i=0; i < trs.length; i++){
      var val = $(trs[i]).find('input').val();
      var unit = $(trs[i]).find('select').val();
      var key = '';
      if ($(trs[i]).text().toLowerCase().includes('width')){
        key = 'width';
      } else if ($(trs[i]).text().toLowerCase().includes('height')) {
        key = 'heigth';
      }
      data[key] = {size: val, unit: unit};

    }
    return data;
  },

  onDataLinksChanged: function(element){
      // TODO implement
  },

  layoutEdit: function(elem) {
    var clicks = $(elem).data('clicks');
    if (clicks) {
      $('.' + this.name).addClass("borderStyle");
      $('#mainDivIDE').addClass("borderStyle");
      $('.' + this.name).removeClass("editBorderStyle");
      $('#mainDivIDE').removeClass("editBorderStyle");
      $(elem).text('Edit');
      $('.layoutToolBar').hide();
    } else {
      $('.' + this.name).removeClass("borderStyle");
      $('#mainDivIDE').removeClass("borderStyle");
      $('.' + this.name).addClass("editBorderStyle");
      $('#mainDivIDE').addClass("editBorderStyle");
      $(elem).html(' → Edit');
      $('.layoutToolBar').show();
    }
    $(elem).data("clicks", !clicks);
  },

  // Other functions related to this panels
  boxSizeChange: function (melem, wh){
      var elem = $(melem).closest('div');
      var tr = $(melem).closest('tr');
      var unit = $(tr).find('select')[0].value;
      var size = $(tr).find('input')[0].value;
      if (unit == 'flex'){
          elem.css('flex', size);
          elem.css('max-' + wh, '');
          inputs = elem.find('input');
          for (var i = 0; i < inputs.length; i++){
              var u = $(inputs[i]).closest('tr').find('select')[0].value;
              if (u == 'flex'){
                  inputs[i].value = size;
              }
          }
      } else if (unit == 'px') {
          elem.css('flex', '');
          elem.css('max-'+ wh, size + unit);
      }
  },

  boxWidthChange: function (melem){
      this.boxSizeChange(melem, 'width');
  },
  boxHeightChange: function (melem){
      this.boxSizeChange(melem, 'height');
  },

  removePanel: function (){
      parentElem = divIDE.ctxTarget;
      if (parentElem.id != 'main'){
          parentElem.remove();
      }
  },

  addPanel: function (){
    parentElem = $(divIDE.ctxTarget);
    var classes = this.name;
    if ($('#tmLayoutEdit').data('clicks')){
      classes += ' editBorderStyle'
    } else {
      classes += ' BorderStyle';
    }

    var elId = $(parentElem).attr('id') + '.' + this.name + '.' + $(parentElem).children().length;

    // Grab the template layout element
    var template = $('#' + divIDE.panelTemplateId(this));

    parentElem.append($(template).html());

    var div = parentElem.children()[parentElem.children().length - 1];
    $(div).attr('id', elId);
    $(div).attr('panelType', this.name);
    $(div).addClass(classes);

  },

  // JUST SO YOU DON"T GET CONFUSED, THE REAL ACTION HAPPENS WHEN YOU SPECIFY THE PANEL TYPE FOR THE LAYOUT
  setPanelType: function(Element){
    var cFINISH = 'TODO'
  },

//

  alignVertical: function (melem){
      elem = divIDE.ctxTarget;
      elem.removeClass("rowItems")
      elem.addClass("columnItems")
  },

  alignHorizontal: function (melem){
      elem = divIDE.ctxTarget;
      elem.removeClass("columnItems")
      elem.addClass("rowItems")
  },

  // Loading and Saving
  exportLayout: function(){
    // Build the json structure defining the layout
    var main = $('#mainDivIDE');
    var layout = {
        divMain: {
            divType: this.name, //has to be a layout panel
            classes: main.attr('class'),
            id: main.attr('id'),
            panelType: main.attr('panelType'),
            data: {
                contents: divIDE.containerContents(main)
            }
        }
    }
    divIDE.download('layout.json', JSON.stringify(layout));
  },

  loadLayout: function(e){
      var layoutObj;
      function callback(result) {
          layoutObj = JSON.parse(result);

          importLayout(layoutObj);
      }
      divIDE.upload(e, callback);
  },

  importLayout: function(layoutObj){
      // TODO: FINISH THIS
      console.log(layoutObj);
  },

  // Ready function

  ready: function(){
    $('#tmLayoutLoad').parent().append('<input type="file" id="tmLayoutLoadFile" style="display: none;" "/>');
    $('#tmLayoutLoadFile').change(function (e) {
      var layoutObj;
      function callback(result) {
        layoutObj = JSON.parse(result);
        layout.importLayout(layoutObj);
      }
      divIDE.upload(e, callback);
    });

  }
}

// Initialization
// Setting up the main structure

// Panels need to be registered BEFORE foundation is imported
divIDE.registerPanel(main);
divIDE.registerPanel(layout);

<commit_msg>Cleaning up and commenting the .js file<commit_after>
// Define the main API
var divIDE = {
  // Support for right-click context menus
  ctxTarget: undefined,

  showMenu: function (event){
    divIDE.clearMenu();
    divIDE.ctxTarget = $(event.target);
    var panelType = divIDE.ctxTarget.attr('panelType');
    if (panelType == undefined){
      divIDE.ctxTarget = divIDE.ctxTarget.closest('[paneltype]');
      panelType =  divIDE.ctxTarget.attr('panelType');
    }
    var panelMenu = divIDE.panelTypes[panelType].showMenu;
    if (panelMenu == undefined){
      divIDE.showMenuType(panelType);
    } else {
      divIDE.panelTypes[panelType].showMenu(panelType, event);
    }
  },

  showMenuType: function(panelType){
      event.stopPropagation();
      event.preventDefault();
      var ctxMenu = $("#" + panelType + "CtxMenu")[0];
      ctxMenu.style.display = "block";
      ctxMenu.style.left = (event.pageX - 10)+"px";
      ctxMenu.style.top = (event.pageY - 60)+"px";
  },

  clearMenu: function (elem){
//     divIDE.ctxTarget = undefined;
    var ctxMenus = $(".ctxMenu");
    for (var i=0; i < ctxMenus.length; i++){
        ctxMenus[i].style.display = "none";
        ctxMenus[i].style.left = "";
        ctxMenus[i].style.top = "";
    }
  },

  // Container for storing registered panels
  panelTypes: {
  },

  // Support for registering a new panel
  registerPanel: function (panel) {
    divIDE.panelTypes[panel.name] = panel;
    var topMenus = panel.topMenuItems;
    if (topMenus != undefined){
      divIDE.addTopMenuItems(panel);
    }
    var ctxMenus = panel.contextMenuItems;
    if (ctxMenus != undefined){
      divIDE.addContextMenuItems(panel);
    }
    var panelHTML = panel.panelHTML;
    if (panelHTML != undefined){
      divIDE.addPanelTemplate(panel);
    }
    var ready = panel.ready;
    if (ready != undefined){
      panel.ready();
    }
  },
  // Functions related to adding top and context menus
  // helper function for recursion
  _addSubMenus: function (menus, idprepend){
    if (idprepend == undefined){
      var idprepend = '';
    }
    var html = '';
    for (key in menus){
      var attrs = '';
      for (attrkey in menus[key]){
        if (attrkey == 'subMenus'){
          continue
        }
        attrs += " " + attrkey + '="' + menus[key][attrkey] + '" ';
      }

      var litext = '
';
      var ultext = '
';

      html += litext + '\
        ' + key + '';
      if (menus[key].subMenus != undefined){
        html += ultext;

        html += divIDE._addSubMenus(menus[key].subMenus);
        html += '\

'
      }
      html += '\

';
    }
    return html;
  },

  addTopMenuItems: function(panel){
    var parent = $('#topMenu').children();
    var html = '';

    // Add up them htmls
    html += divIDE._addSubMenus(panel.topMenuItems, 'topMenu');
    parent.append(html);
  },

  addContextMenuItems: function (panel) {
    var parent = $('#CtxMenus')
    var html = '\

\

'

    // Add up them menus
    html += divIDE._addSubMenus(panel.contextMenuItems);

    // Add closing div and ul text to go with context menus
    html += '\

 \

'
    parent.append(html);
  },

  // Helper function that gives the ID of the template div given a panel name
  panelTemplateId: function(panel) {
    return panel.name + 'Template';
  },

  // Class assigned to panel templates. This is mostly used to display:none
  panelTemplateClass: 'divIDEPanelTemplate',

  // Actual function that adds a template. The reason we need to add
  // A template of a panel into the html is so that foundation can work
  // it's magic when the document is read.
  addPanelTemplate: function (panel) {
    var parentElem = $('#panelTemplates');

    //make a div with an id that we can predict
    var div = document.createElement('div');
    $(div).addClass(divIDE.panelTemplateClass);
    $(div).attr('id', divIDE.panelTemplateId(panel));
    $(div).html(panel.panelHTML(parentElem));
    parentElem[0].appendChild(div);
  },

  // TODO: This needs work for exporting, maybe should go in the definition of a layout panel
  containerContents: function (elem){
    var contents = [];
    var children = $(elem).children('div');
    for (var i = 0; i < children.length; i++){
      var child = $(children[i]);
      contents.push({
         divType: $(elem).attr('panelType'),
         classes: child.attr('class'),
         id: child.attr('id'),
         style: child.attr('style'),
         data: {
             contents: divIDE.containerContents(child),
             width: child.css('max-width'),
             height: child.css('max-height'),
             flex: child.css('flex')
         }
      });
    }
    return contents;
  },

  // Setting up the common functions, general utility
  // Downloading a file: http://stackoverflow.com/questions/3665115/create-a-file-in-memory-for-user-to-download-not-through-server
  download: function(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
  },

  // Looks like importing is trickier: https://www.html5rocks.com/en/tutorials/file/dndfiles/
  // Importing/reading a single file: http://stackoverflow.com/questions/3582671/how-to-open-a-local-disk-file-with-javascript
  upload: function(e, callback) {
    var file = e.target.files[0];
    if (!file) {
      return;
    }
    var reader = new FileReader();
    reader.onload = function (e) {
        callback(reader.result);
    }
    // This function is asynchronous, which means we have no idea when it will happen.
    // As such, after it's finished, we need to have a callback to do something with the
    // results. Hence the above callback function.
    reader.readAsText(file);
  }
}

// Main panel definition
var main = {
  name: "mainDivIDE",
  contextMenuItems: {
    "Add Panel": {
      id: 'mainAddPanel',
      onclick: 'layout.addPanel()',
    },
    "Align": {
      id: 'mainAlign',
      subMenus: {
        "Vertical": {
          id: "mainAlignVertical",
          onclick: 'layout.alignVertical()'
        },
        "Horizontal": {
          id: "mainAlignHorizontal",
          onclick: 'layout.alignHorizontal()'
        }
      }
    }
  },
  topMenuItems: {
    File: {
      subMenus: {
        Open: {
          id: 'tmFileOpen'
        },
        Recent: {
          id: 'tmFileRecent',
          subMenus: {
            item1: {
              id: 'item1'
            },
            item2: {
              id: 'item2'
            }
          }
        }
      },
      id: "tmFile"
    }
  },
  showMenu: function(panelType, event) {
    if ($('#tmLayoutEdit').data('clicks')){
      divIDE.showMenuType(panelType);
    }
  },

  ready: function () {
    var mainDivIDE = $("#mainDivIDE")[0];
    mainDivIDE.addEventListener("contextmenu", divIDE.showMenu, false);
    mainDivIDE.addEventListener("click", divIDE.clearMenu, false);
    $(mainDivIDE).addClass('borderStyle rowItems divIDELayout');
    $(mainDivIDE).attr('panelType', 'mainDivIDE')

  }
}

// Layout panel definition
layout = {
  name: "DivIDELayout",
  panelHTML: function(parentElement) {
    var html = "\

 \

\
          Width:	 \
          <input type='number' min=0 max=2048 class='layoutWidth' value='1' onchange='layout.boxWidthChange(this)'> \
          </input> 	 \
           <select class='unit' onchange='layout.boxWidthChange(this)'> \
                <option value='flex'>flex</option> \
                <option value='px'>px</option> \
               </select> \
          	 \

 \

\
          Height:	 \
          <input type='number' min=0 max=2048 class='layoutWidth' value='1' onchange='layout.boxHeightChange(this)'> \
          </input> 	 \
           <select class='unit' onchange='layout.boxHeightChange(this)'> \
                <option value='flex'>flex</option> \
                <option value='px'>px</option> \
               </select> \
          	 \

 \

";
    return html
  },

  contextMenuItems: {
    "Add Panel": {
      id: 'mainAddPanel',
      onclick: 'layout.addPanel()',
    },
    "Remove Panel": {
      id: 'mainRemovePanel',
      onclick: 'layout.removePanel()',
    },
    "Align": {
      id: 'mainAlign',
      subMenus: {
        "Vertical": {
          id: "mainAlignVertical",
          onclick: 'layout.alignVertical()'
        },
        "Horizontal": {
          id: "mainAlignHorizontal",
          onclick: 'layout.alignHorizontal()'
        }
      }
    }
  },

  topMenuItems : {
    Layout: {
      subMenus: {
        Edit: {
          id: 'tmLayoutEdit',
          onclick: 'layout.layoutEdit(this)'
        },
        Save: {
          id: 'tmLayoutSave',
          onclick: 'layout.exportLayout()'
        },
        Load: {
          id: 'tmLayoutLoad',
          onclick: "$('#tmLayoutLoadFile').click()",
        }
      },
      id: "tmLayout"
    }
  },

  data: { // TODO ? maybe lives in divIDE instead?
      callbackFunctions: [],
      dataLinks: {},
  },

  getPanelData: function(elem) {
    var trs = $(elem).find('tr');
    var data = {};
    for (var i=0; i < trs.length; i++){
      var val = $(trs[i]).find('input').val();
      var unit = $(trs[i]).find('select').val();
      var key = '';
      if ($(trs[i]).text().toLowerCase().includes('width')){
        key = 'width';
      } else if ($(trs[i]).text().toLowerCase().includes('height')) {
        key = 'heigth';
      }
      data[key] = {size: val, unit: unit};

    }
    return data;
  },

  onDataLinksChanged: function(element){
      // TODO implement
  },

  // Other functions related to this panel specifically, not part of the divIDE interface...
  layoutEdit: function(elem) {
    var clicks = $(elem).data('clicks');
    if (clicks) {
      $('.' + this.name).addClass("borderStyle");
      $('#mainDivIDE').addClass("borderStyle");
      $('.' + this.name).removeClass("editBorderStyle");
      $('#mainDivIDE').removeClass("editBorderStyle");
      $(elem).text('Edit');
      $('.layoutToolBar').hide();
    } else {
      $('.' + this.name).removeClass("borderStyle");
      $('#mainDivIDE').removeClass("borderStyle");
      $('.' + this.name).addClass("editBorderStyle");
      $('#mainDivIDE').addClass("editBorderStyle");
      $(elem).html(' → Edit');
      $('.layoutToolBar').show();
    }
    $(elem).data("clicks", !clicks);
  },

  boxSizeChange: function (melem, wh){
      var elem = $(melem).closest('div');
      var tr = $(melem).closest('tr');
      var unit = $(tr).find('select')[0].value;
      var size = $(tr).find('input')[0].value;
      if (unit == 'flex'){
          elem.css('flex', size);
          elem.css('max-' + wh, '');
          inputs = elem.find('input');
          for (var i = 0; i < inputs.length; i++){
              var u = $(inputs[i]).closest('tr').find('select')[0].value;
              if (u == 'flex'){
                  inputs[i].value = size;
              }
          }
      } else if (unit == 'px') {
          elem.css('flex', '');
          elem.css('max-'+ wh, size + unit);
      }
  },

  boxWidthChange: function (melem){
      this.boxSizeChange(melem, 'width');
  },
  boxHeightChange: function (melem){
      this.boxSizeChange(melem, 'height');
  },

  removePanel: function (){
      parentElem = divIDE.ctxTarget;
      if (parentElem.id != 'main'){
          parentElem.remove();
      }
  },

  addPanel: function (){
    parentElem = $(divIDE.ctxTarget);
    var classes = this.name;
    if ($('#tmLayoutEdit').data('clicks')){
      classes += ' editBorderStyle'
    } else {
      classes += ' BorderStyle';
    }

    var elId = $(parentElem).attr('id') + '.' + this.name + '.' + $(parentElem).children().length;

    // Grab the template layout element
    var template = $('#' + divIDE.panelTemplateId(this));

    parentElem.append($(template).html());

    var div = parentElem.children()[parentElem.children().length - 1];
    $(div).attr('id', elId);
    $(div).attr('panelType', this.name);
    $(div).addClass(classes);

  },

  // JUST SO YOU DON"T GET CONFUSED, THE REAL ACTION HAPPENS WHEN YOU SPECIFY THE PANEL TYPE FOR THE LAYOUT
  setPanelType: function(Element){
    var cFINISH = 'TODO'
  },

  alignVertical: function (melem){
      elem = divIDE.ctxTarget;
      elem.removeClass("rowItems")
      elem.addClass("columnItems")
  },

  alignHorizontal: function (melem){
      elem = divIDE.ctxTarget;
      elem.removeClass("columnItems")
      elem.addClass("rowItems")
  },

  // Loading and Saving
  exportLayout: function(){
    // Build the json structure defining the layout
    var main = $('#mainDivIDE');
    var layout = {
        divMain: {
            divType: this.name, //has to be a layout panel
            classes: main.attr('class'),
            id: main.attr('id'),
            panelType: main.attr('panelType'),
            data: {
                contents: divIDE.containerContents(main)
            }
        }
    }
    divIDE.download('layout.json', JSON.stringify(layout));
  },

  loadLayout: function(e){
      var layoutObj;
      function callback(result) {
          layoutObj = JSON.parse(result);

          importLayout(layoutObj);
      }
      divIDE.upload(e, callback);
  },

  importLayout: function(layoutObj){
      // TODO: FINISH THIS
      console.log(layoutObj);
  },

  // Ready function

  ready: function(){
    $('#tmLayoutLoad').parent().append('<input type="file" id="tmLayoutLoadFile" style="display: none;" "/>');
    $('#tmLayoutLoadFile').change(function (e) {
      var layoutObj;
      function callback(result) {
        layoutObj = JSON.parse(result);
        layout.importLayout(layoutObj);
      }
      divIDE.upload(e, callback);
    });

  }
}

// Initialization
// Setting up the main structure

// Panels need to be registered BEFORE foundation is imported
divIDE.registerPanel(main);
divIDE.registerPanel(layout);

<|endoftext|>


<commit_before>document.addEventListener('deviceready',function(){
    /* USEFUL STUFF:
     * https://developer.mozilla.org/en-US/docs/Web/API/FileError#Error_codes
     */
    var fail = function(e){
        navigator.notification.alert("oh dear, something went wrong :(",function(){},"File Persistance","OK");
        console.log("oh dear, something went wrong :(");
    };
    var filePersist = new FilePersist();
    var myExampleDirName = "exampleDir";
    var myExampleFileName = "exampleFile";

    filePersist.getDir(cordova.file.dataDirectory,function(dataDir){
        filePersist.getDir(dataDir,function(myExampleDir){
            var objToSave = {
                "string": "hello",
                "boolean": true,
                "int": 1,
                "array": ["test","test2"]
            };
            var success = function(){
                navigator.notification.alert("Object successfully saved to fileSystem",function(){},"File Persistance","OK");
                console.log("Object successfully saved to fileSystem");
                filePersist.getFileContents(myExampleDir,myExampleFileName,function(obj){
                    navigator.notification.alert("The console log is now displaying what we just saved...",function(){},"File Persistance","OK");
                    console.log("What is in "+myExampleDir.nativeURL+myExampleFileName);
                    console.log(obj);
                },fail,filePersist.options.createIfDoesNotExist);
            };
            filePersist.setFileContents(myExampleDir,myExampleFileName,objToSave,fail,success,filePersist.options.createIfDoesNotExist);
        },fail,myExampleDirName,filePersist.options.createIfDoesNotExist);
    },fail);

},false);
<commit_msg>* device ready not firing on wp8? hmmm<commit_after>document.addEventListener('deviceready',function(){
    /* USEFUL STUFF:
     * https://developer.mozilla.org/en-US/docs/Web/API/FileError#Error_codes
     */
    var fail = function(e){
        navigator.notification.alert("oh dear, something went wrong :(",function(){},"File Persistance","OK");
        console.log("oh dear, something went wrong :(");
    };
    var filePersist = new FilePersist();
    var myExampleDirName = "exampleDir";
    var myExampleFileName = "exampleFile";

//    filePersist.getDir(cordova.file.dataDirectory,function(dataDir){
//        filePersist.getDir(dataDir,function(myExampleDir){
//            var objToSave = {
//                "string": "hello",
//                "boolean": true,
//                "int": 1,
//                "array": ["test","test2"]
//            };
//            var success = function(){
//                navigator.notification.alert("Object successfully saved to fileSystem",function(){},"File Persistance","OK");
//                console.log("Object successfully saved to fileSystem");
//                filePersist.getFileContents(myExampleDir,myExampleFileName,function(obj){
//                    navigator.notification.alert("The console log is now displaying what we just saved...",function(){},"File Persistance","OK");
//                    console.log("What is in "+myExampleDir.nativeURL+myExampleFileName);
//                    console.log(obj);
//                },fail,filePersist.options.createIfDoesNotExist);
//            };
//            filePersist.setFileContents(myExampleDir,myExampleFileName,objToSave,fail,success,filePersist.options.createIfDoesNotExist);
//        },fail,myExampleDirName,filePersist.options.createIfDoesNotExist);
//    },fail);

},false);
<|endoftext|>


<commit_before>'use strict';

angular.module('$strap.directives')

.directive('bsAlert', function($parse, $timeout, $compile) {

  return {
    restrict: 'A',
    link: function postLink(scope, element, attrs) {

      var getter = $parse(attrs.bsAlert),
        setter = getter.assign,
        value = getter(scope);

      // For static alerts
      if(!attrs.bsAlert) {

        // Setup close button
        if(angular.isUndefined(attrs.closeButton) || (attrs.closeButton !== '0' && attrs.closeButton !== 'false')) {
          element.prepend('<button type="button" class="close" data-dismiss="alert">×</button>');
        }

        // Support close-after attribute
        if(angular.isDefined(attrs.closeAfter)) {
          var closeAfter = parseInt(attrs.closeAfter, 10) || 0;
          $timeout(function(){
            element.alert('close');
          }, closeAfter);
        }

      } else {

        scope.$watch(attrs.bsAlert, function(newValue, oldValue) {
          value = newValue;

          // Set alert content
          element.html((newValue.title ? '' + newValue.title + ' ' : '') + newValue.content || '');

          if(!!newValue.closed) {
            element.hide();
          }

          // Compile alert content
          //$timeout(function(){
          $compile(element.contents())(scope);
          //});

          // Add proper class
          if(newValue.type || oldValue.type) {
            oldValue.type && element.removeClass('alert-' + oldValue.type);
            newValue.type && element.addClass('alert-' + newValue.type);
          }

          var closeAfter = 0;
          if (angular.isDefined(newValue.closeAfter)) {
            closeAfter = newValue.closeAfter;
          } else if (angular.isDefined(attrs.closeAfter)) {
            closeAfter = attrs.closeAfter;
          }
          closeAfter = parseInt(closeAfter, 10) || 0;

          if(closeAfter > 0) {
            $timeout(function(){
              element.alert('close');
            }, closeAfter);
          }

          // Setup close button
          if(angular.isUndefined(attrs.closeButton) || (attrs.closeButton !== '0' && attrs.closeButton !== 'false')) {
            element.prepend('<button type="button" class="close" data-dismiss="alert">×</button>');
          }

        }, true);

      }

      element.addClass('alert').alert();

      // Support fade-in effect
      if(element.hasClass('fade')) {
        element.removeClass('in');
        setTimeout(function() {
          element.addClass('in');
        });
      }

      var parentArray = attrs.ngRepeat && attrs.ngRepeat.split(' in ').pop();

      element.on('close', function(ev) {
        var removeElement;

        if(parentArray) { // ngRepeat, remove from parent array
          ev.preventDefault();

          element.removeClass('in');

          removeElement = function() {
            element.trigger('closed');
            if(scope.$parent) {
              scope.$parent.$apply(function() {
                var path = parentArray.split('.');
                var curr = scope.$parent;

                for (var i = 0; i < path.length; ++i) {
                  if (curr) {
                    curr = curr[path[i]];
                  }
                }

                if (curr) {
                  curr.splice(scope.$index, 1);
                }
              });
            }
          };

          $.support.transition && element.hasClass('fade') ?
            element.on($.support.transition.end, removeElement) :
            removeElement();

        } else if(value) { // object, set closed property to 'true'
          ev.preventDefault();

          element.removeClass('in');

          removeElement = function() {
            element.trigger('closed');
            scope.$apply(function() {
              value.closed = true;
            });
          };

          $.support.transition && element.hasClass('fade') ?
            element.on($.support.transition.end, removeElement) :
            removeElement();

        } else { // static, regular behavior
        }

      });

    }
  };
});
<commit_msg>feat(alert): refactor support for close-after attr (fixes #120)<commit_after>'use strict';

angular.module('$strap.directives')

.directive('bsAlert', function($parse, $timeout, $compile) {

  return {
    restrict: 'A',
    link: function postLink(scope, element, attrs) {

      var getter = $parse(attrs.bsAlert),
        setter = getter.assign,
        value = getter(scope);

      var closeAlert = function closeAlertFn(delay) {
        $timeout(function(){
          element.alert('close');
        }, delay * 1);
      };

      // For static alerts
      if(!attrs.bsAlert) {

        // Setup close button
        if(angular.isUndefined(attrs.closeButton) || (attrs.closeButton !== '0' && attrs.closeButton !== 'false')) {
          element.prepend('<button type="button" class="close" data-dismiss="alert">×</button>');
        }

        // Support close-after attribute
        if(attrs.closeAfter) closeAlert(attrs.closeAfter);

      } else {

        scope.$watch(attrs.bsAlert, function(newValue, oldValue) {
          value = newValue;

          // Set alert content
          element.html((newValue.title ? '' + newValue.title + ' ' : '') + newValue.content || '');

          if(!!newValue.closed) {
            element.hide();
          }

          // Compile alert content
          //$timeout(function(){
          $compile(element.contents())(scope);
          //});

          // Add proper class
          if(newValue.type || oldValue.type) {
            oldValue.type && element.removeClass('alert-' + oldValue.type);
            newValue.type && element.addClass('alert-' + newValue.type);
          }

          // Support close-after attribute
          if(angular.isDefined(newValue.closeAfter)) closeAlert(newValue.closeAfter);
          else if(attrs.closeAfter) closeAlert(attrs.closeAfter);

          // Setup close button
          if(angular.isUndefined(attrs.closeButton) || (attrs.closeButton !== '0' && attrs.closeButton !== 'false')) {
            element.prepend('<button type="button" class="close" data-dismiss="alert">×</button>');
          }

        }, true);

      }

      element.addClass('alert').alert();

      // Support fade-in effect
      if(element.hasClass('fade')) {
        element.removeClass('in');
        setTimeout(function() {
          element.addClass('in');
        });
      }

      var parentArray = attrs.ngRepeat && attrs.ngRepeat.split(' in ').pop();

      element.on('close', function(ev) {
        var removeElement;

        if(parentArray) { // ngRepeat, remove from parent array
          ev.preventDefault();

          element.removeClass('in');

          removeElement = function() {
            element.trigger('closed');
            if(scope.$parent) {
              scope.$parent.$apply(function() {
                var path = parentArray.split('.');
                var curr = scope.$parent;

                for (var i = 0; i < path.length; ++i) {
                  if (curr) {
                    curr = curr[path[i]];
                  }
                }

                if (curr) {
                  curr.splice(scope.$index, 1);
                }
              });
            }
          };

          $.support.transition && element.hasClass('fade') ?
            element.on($.support.transition.end, removeElement) :
            removeElement();

        } else if(value) { // object, set closed property to 'true'
          ev.preventDefault();

          element.removeClass('in');

          removeElement = function() {
            element.trigger('closed');
            scope.$apply(function() {
              value.closed = true;
            });
          };

          $.support.transition && element.hasClass('fade') ?
            element.on($.support.transition.end, removeElement) :
            removeElement();

        } else { // static, regular behavior
        }

      });

    }
  };
});
<|endoftext|>


<commit_before>$(document).ready(function() {
 $tabs = $("#tabs").tabs({
  select: function(event, ui) {
   $(".thumb").remove();
   page = 1;
  },
  load: function(event, ui) {
   console.log('colorbox');
   $(".event").colorbox();
  }
 });
 page = 1;
 add_monitors();
 setup_is();

 //FUNCTIONS//
 function add_monitors(){
  $.post("skins/new/includes/getMonitors.php", function(data){
   var monitors = data.split(","); // Put monitors into array
   monitors.pop(); // Pop off last monitor (it is blank)
   var x = monitors.length; // Number of monitors
   for (var i=0;i<x;i++){
    var monitor = monitors[i];
    $tabs.tabs('add', "skins/new/includes/getEvents.php?MonitorName="+monitor, monitor);
   }
  });
 };

 function setup_is(){
  $(window).scroll(function(){
   if ($(window).scrollTop() == $(document).height() - $(window).height()){
    FetchMore();
   }
  });
 }

 function FetchMore(){
  var MonitorName = $('li.ui-state-active a span').val();
  $.post("skins/new/includes/getEvents.php?MonitorName="+MonitorName+"&page="+page, function(data){
   if (data != "") {
   }
  });
  page = page + 1;
 }
 //FUNCTIONS//
});
<commit_msg>Removed some logging, changed colorbox size and fixed var MonitorName<commit_after>$(document).ready(function() {
 $tabs = $("#tabs").tabs({
  select: function(event, ui) {
   $(".thumb").remove();
   page = 1;
  },
  load: function(event, ui) {
   $(".event").colorbox({width:"50%", height:"50%"});
  }
 });
 page = 1;
 add_monitors();
 setup_is();

 //FUNCTIONS//
 function add_monitors(){
  $.post("skins/new/includes/getMonitors.php", function(data){
   var monitors = data.split(","); // Put monitors into array
   monitors.pop(); // Pop off last monitor (it is blank)
   var x = monitors.length; // Number of monitors
   for (var i=0;i<x;i++){
    var monitor = monitors[i];
    $tabs.tabs('add', "skins/new/includes/getEvents.php?MonitorName="+monitor, monitor);
   }
  });
 };

 function setup_is(){
  $(window).scroll(function(){
   if ($(window).scrollTop() == $(document).height() - $(window).height()){
    FetchMore();
   }
  });
 }

 function FetchMore(){
  var MonitorName = $('li.ui-state-active a span').text();
  $.post("skins/new/includes/getEvents.php?MonitorName="+MonitorName+"&page="+page, function(data){
   if (data != "") {
   }
  });
  page = page + 1;
 }
 //FUNCTIONS//
});
<|endoftext|>


<commit_before>import mongoose from 'mongoose'
var Schema = mongoose.Schema

var athleticsSchema = new Schema({
  id: String,
  date: Date,
  events: [{
    title: String,
    location: String,
    building_id: String,
    start_time: Date,
    end_time: Date
  }]
})

athleticsSchema.index({ id: 'text', date: 'text', campus: 'text', 'events.location': 'text', 'events.title': 'text' })

export default mongoose.model('athletics', athleticsSchema)
<commit_msg>Remove date from text indices<commit_after>import mongoose from 'mongoose'
var Schema = mongoose.Schema

var athleticsSchema = new Schema({
  id: String,
  date: Date,
  campus: String,
  events: [{
    title: String,
    location: String,
    building_id: String,
    start_time: Date,
    end_time: Date
  }]
})

athleticsSchema.index({ id: 'text', date: 'text', campus: 'text', 'events.title': 'text' })

export default mongoose.model('athletics', athleticsSchema)
<|endoftext|>


<commit_before>var VR = (function() {
    var setCurrentScene = function(index) {
        currentScene = $scenes.eq(index).attr('id');
    }

    var enterVR = function() {
        scene.enterVR();
    }

    var turnOnAnimations = function() {
        camera.setAttribute('drag-look-controls', 'enabled', 'false');
        animate = true;
    }

    var turnOffAnimations = function() {
        camera.setAttribute('drag-look-controls', 'enabled', 'true');
        animate = false;
    }

    var enterMomentOfZen = function() {
        var newURL = APP_CONFIG.S3_BASE_URL + '/?scene=' + currentScene;
        history.replaceState(null, null, newURL);

        turnOffAnimations();
        changeVRScene();
        UI.updateSceneData();
        UI.navigateToVR();
    }

    var getNewVRSceneFromAudioPosition = function(position) {
        for (var i = 0; i < COPY['vr'].length; i++) {
            var thisRow = COPY['vr'][i];
            if (position < thisRow['end_time'] && position > 0) {
                if (thisRow['id'] === currentScene) {
                    break;
                } else {
                    currentScene = thisRow['id'];
                    $canvas.velocity('fadeOut', {
                        duration: 1000,
                        complete: EVENTS.onSceneSwitch
                    });
                    break;
                }
            }
        }
    }

    var changeVRScene = function() {
        $scene = $('#' + currentScene);
        $scenes.find('.sky, .instructions, .vr-annotation').attr('visible', 'false');
        $scene.find('.sky').attr('visible', 'true');

        // if (inVR) {
            $scene.find('.vr-annotation').attr('visible', 'true');
        // }

        camera.setAttribute('camera', 'fov', $scene.data('fov'));

        if (animate) {
            camera.emit('enter-' + currentScene);
        }
    }

    var cancelAnimation = function() {
        if (animate) {
            camera.emit('cancel-' + currentScene);
        }
    }

    var navigateToEndScene = function() {
        $scenes.find('.sky').attr('visible', 'false');
        $('.end-scene').find('a-image').attr('visible', 'true');
        endedAudioInVR = true;
    }

    return {
        'setCurrentScene': setCurrentScene,
        'enterVR': enterVR,
        'turnOnAnimations': turnOnAnimations,
        'turnOffAnimations': turnOffAnimations,
        'enterMomentOfZen': enterMomentOfZen,
        'getNewVRSceneFromAudioPosition': getNewVRSceneFromAudioPosition,
        'changeVRScene': changeVRScene,
        'cancelAnimation': cancelAnimation,
        'navigateToEndScene': navigateToEndScene
    }
})();<commit_msg>keep making sure vr annotations only show up in vr<commit_after>var VR = (function() {
    var setCurrentScene = function(index) {
        currentScene = $scenes.eq(index).attr('id');
    }

    var enterVR = function() {
        scene.enterVR();
    }

    var turnOnAnimations = function() {
        camera.setAttribute('drag-look-controls', 'enabled', 'false');
        animate = true;
    }

    var turnOffAnimations = function() {
        camera.setAttribute('drag-look-controls', 'enabled', 'true');
        animate = false;
    }

    var enterMomentOfZen = function() {
        var newURL = APP_CONFIG.S3_BASE_URL + '/?scene=' + currentScene;
        history.replaceState(null, null, newURL);

        turnOffAnimations();
        changeVRScene();
        UI.updateSceneData();
        UI.navigateToVR();
    }

    var getNewVRSceneFromAudioPosition = function(position) {
        for (var i = 0; i < COPY['vr'].length; i++) {
            var thisRow = COPY['vr'][i];
            if (position < thisRow['end_time'] && position > 0) {
                if (thisRow['id'] === currentScene) {
                    break;
                } else {
                    currentScene = thisRow['id'];
                    $canvas.velocity('fadeOut', {
                        duration: 1000,
                        complete: EVENTS.onSceneSwitch
                    });
                    break;
                }
            }
        }
    }

    var changeVRScene = function() {
        $scene = $('#' + currentScene);
        $scenes.find('.sky, .instructions, .vr-annotation').attr('visible', 'false');
        $scene.find('.sky').attr('visible', 'true');

        if (inVR) {
            $scene.find('.vr-annotation').attr('visible', 'true');
        }

        camera.setAttribute('camera', 'fov', $scene.data('fov'));

        if (animate) {
            camera.emit('enter-' + currentScene);
        }
    }

    var cancelAnimation = function() {
        if (animate) {
            camera.emit('cancel-' + currentScene);
        }
    }

    var navigateToEndScene = function() {
        $scenes.find('.sky').attr('visible', 'false');
        $('.end-scene').find('a-image').attr('visible', 'true');
        endedAudioInVR = true;
    }

    return {
        'setCurrentScene': setCurrentScene,
        'enterVR': enterVR,
        'turnOnAnimations': turnOnAnimations,
        'turnOffAnimations': turnOffAnimations,
        'enterMomentOfZen': enterMomentOfZen,
        'getNewVRSceneFromAudioPosition': getNewVRSceneFromAudioPosition,
        'changeVRScene': changeVRScene,
        'cancelAnimation': cancelAnimation,
        'navigateToEndScene': navigateToEndScene
    }
})();<|endoftext|>


<commit_before>
"use strict";

import Field from './Field';
import DragDrop from './dragDrop';
import Slug from './slug';
import Message from './message';

export default angular.module('monad.directives', [])
    .directive('moField', Field)
    .directive('moDragDrop', DragDrop)
    .directive('moSlug', Slug)
    .directive('moMessage', Message)
    .name
    ;

<commit_msg>dependency<commit_after>
"use strict";

import Field from './Field';
import DragDrop from './dragDrop';
import Slug from './slug';
import Message from './message';

export default angular.module('monad.directives', ['monad.cms'])
    .directive('moField', Field)
    .directive('moDragDrop', DragDrop)
    .directive('moSlug', Slug)
    .directive('moMessage', Message)
    .name
    ;

<|endoftext|>


<commit_before>/* global module */

module.exports = function (grunt) {

    "use strict";

    grunt.initConfig({
        pkg: grunt.file.readJSON("package.json"),
        qunit: {
            options: {
                urls: ["http://localhost:8000/test/index.html"]
            }
        },
        connect: {
            server: {
                options: {
                    port: 8000,
                    base: "."
                }
            }
        },
        jshint: {
            all: [
                "!Gruntfile.js",
                "assets/js/src/*.js",
                "!js/build/*.js",
                "test/*.js"
            ],
            options: {
                jshintrc: ".jshintrc",
                reporter: require("jshint-stylish")
            }
        },
        uglify: {
            dist: {
                files: {
                    "assets/build/scripts.min.js" : [
                        "assets/js/*.js"
                    ]
                }
            }
        },
        clean: {
            dist: [
                "assets/build/scripts.min.js"
            ]
        },
        watch: {
            js: {
                files: [
                    "<%= jshint.all %>"
                ],
                tasks: ["jshint"]
            }
        },
        php: {
            dist: {
                options: {
                    port: 8080,
                    base: 'web',
                    open: true,
                    keepalive: true
                }
            }
        },
        /*phpcs: {
            application: {
                dir: ['*.php']
            },
            options: {
                bin: 'vendor/bin/phpcs',
                standard: 'Zend'
            }
        },*/
        phplint: {
            options: {
                swapPath: '/tmp'
            },
            all: ['*.php']
        }/*,
        phpunit: {
            unit: {
                dir: 'tests/unit'
            },
            options: {
                bin: 'phpunit',
                bootstrap: 'tests/Bootstrap.php',
                colors: true,
                testdox: true
            }
        },
        /*php_analyzer: {
            application: {
                dir: 'src'
            }
        }*/
    });

    grunt.loadNpmTasks("grunt-contrib-clean");
    grunt.loadNpmTasks("grunt-contrib-qunit");
    grunt.loadNpmTasks("grunt-contrib-jshint");
    grunt.loadNpmTasks("grunt-contrib-uglify");
    grunt.loadNpmTasks("grunt-contrib-connect");
    grunt.loadNpmTasks("grunt-contrib-watch");

    grunt.loadNpmTasks('grunt-phpcs');
    grunt.loadNpmTasks('grunt-php');
    grunt.loadNpmTasks('grunt-phplint');
    grunt.loadNpmTasks('grunt-phpunit');
    grunt.loadNpmTasks('grunt-php-analyzer');

    grunt.registerTask('server', ['php']);
    grunt.registerTask("default", ["jshint", "connect", "qunit", 'phplint:all',]);
    grunt.registerTask("build", ["jshint", "connect", "qunit", "clean", "uglify"]);
    grunt.registerTask("dev", ["watch"]);
    grunt.registerTask("ci", ["default"]);
};<commit_msg>Grunt<commit_after>/*global module, require */

module.exports = function (grunt) {

    "use strict";

    grunt.initConfig({
        pkg: grunt.file.readJSON("package.json"),
        qunit: {
            options: {
                urls: ["http://localhost:8000/test/index.html"]
            }
        },
        connect: {
            server: {
                options: {
                    port: 8000,
                    base: "."
                }
            }
        },
        jshint: {
            all: [
                "Gruntfile.js",
                "assets/js/src/*.js",
                "!js/build/*.js",
                "test/*.js",
            ],
            options: {
                jshintrc: ".jshintrc",
                reporter: require("jshint-stylish")
            }
        },
        uglify: {
            dist: {
                files: {
                    "assets/build/scripts.min.js" : [
                        "assets/js/*.js"
                    ]
                }
            }
        },
        clean: {
            dist: [
                "assets/build/scripts.min.js"
            ]
        },
        watch: {
            js: {
                files: [
                    "<%= jshint.all %>"
                ],
                tasks: ["jshint"]
            }
        },
        php: {
            dist: {
                options: {
                    port: 8080,
                    base: "web",
                    open: true,
                    keepalive: true
                }
            }
        },
        phplint: {
            options: {
                swapPath: "/tmp"
            },
            all: [
                "*.php",
                "admin/*.php",
                "includes/*.php",
                "public/*.php"
            ]
        }
    });

    grunt.loadNpmTasks("grunt-contrib-clean");
    grunt.loadNpmTasks("grunt-contrib-qunit");
    grunt.loadNpmTasks("grunt-contrib-jshint");
    grunt.loadNpmTasks("grunt-contrib-uglify");
    grunt.loadNpmTasks("grunt-contrib-connect");
    grunt.loadNpmTasks("grunt-contrib-watch");

    grunt.loadNpmTasks("grunt-phpcs");
    grunt.loadNpmTasks("grunt-php");
    grunt.loadNpmTasks("grunt-phplint");
    grunt.loadNpmTasks("grunt-phpunit");
    grunt.loadNpmTasks("grunt-php-analyzer");

    grunt.registerTask("server", ["php"]);
    grunt.registerTask("default", ["jshint", "connect", "qunit", "phplint:all"]);
    grunt.registerTask("build", ["jshint", "connect", "qunit", "clean", "uglify"]);
    grunt.registerTask("dev", ["watch"]);
    grunt.registerTask("ci", ["default"]);
};<|endoftext|>


<commit_before>import collection from "lk-collection-convexpress";

import dispatchEvent from "services/dispatcher";
import * as authorize from "./authorize";
import schema from "./schema";

export default collection({
    name: "questions",
    dispatchEvent,
    authorize,
    schema
});
<commit_msg>Added findElement function to questions api<commit_after>import collection from "lk-collection-convexpress";

import findElement from "common/find-element";
import dispatchEvent from "services/dispatcher";
import * as authorize from "./authorize";
import schema from "./schema";

export default collection({
    name: "questions",
    dispatchEvent,
    authorize,
    schema,
    findElement
});
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  var fs = require('fs');
  require('es6-shim');
  var bower = require('bower');
  var path = require('path');

  var pkgFile = require('./package.json');
  var lyriaConfig = pkgFile.lyriaProject || {};

  var buildPrefix = 'builds';
  var buildVersion = pkgFile.version + '-' + grunt.template.today("yymmdd-HHMMss");
  var buildId = pkgFile.name + '-v' + buildVersion;
  var buildFolder = [buildPrefix, buildId].join('/');

  var libFiles = (fs.existsSync('./lib')) ? fs.readdirSync('./lib') : [];
  var styleFiles = (fs.existsSync('./css')) ? fs.readdirSync('./css') : [];

  var libFilesPriorities = ['almond', 'handlebars', 'fastclick', 'udefine'];

  var templateScripts = {
    development: [],
    production: []
  };
  var templateStyles = {
    development: [],
    production: []
  };

  var uglifyLibObject = {};
  var bowerStyleObject = {};

  for (var i = 0, j = libFiles.length; i < j; i++) {
    (function(iterator) {
      uglifyLibObject[path.join(buildFolder, 'lib', iterator)] = path.join('./lib', iterator);
      if (libFilesPriorities.indexOf(iterator) >= 0) {
        templateScripts.unshift('lib/' + iterator);
      } else {
        templateScripts.push('lib/' + iterator);
      }
    })(libFiles[i]);
  }

  uglifyLibObject[buildFolder + '/js/<%= pkg.name %>.js'] = '<%= concat_sourcemap.dist.dest %>';
  //templateScripts.push('js/<%= pkg.name %>.js');

  for (var k = 0, l = styleFiles.length; k < l; k++) {
    (function(iterator) {
      templateStyles.development.push('css/' + iterator);
      templateStyles.production.push('css/' + iterator);
    })(styleFiles[k]);
  }

  grunt.initConfig({
    pkg: pkgFile,
    lyriaConfig: lyriaConfig,
    buildVersion: buildVersion,
    buildFolder: buildFolder,
    concat_sourcemap: {
      options: {
        sourcesContent: true,
        sourceRoot: '/'
      },
      dist: {
        src: ['src/**/*.js'],
        dest: 'js/<%= pkg.name %>.js'
      }
    },
    copy: {
      assets: {
        files: [{
          expand: true,
          src: ['assets/**'],
          dest: '<%= buildFolder %>/',
          filter: function(filepath) {
            if ((filepath.indexOf(path.sep + 'scenes') >= 0) || (filepath.indexOf(path.sep + 'prefabs') >= 0)) {
              return false;
            } else {
              return true;
            }
          }
        }]
      },
      root: {
        files: [{
          expand: true,
          src: ['css/**/*', 'favicon.ico', '*.png'],
          dest: '<%= buildFolder %>/'
        }]
      },
      styles: {
        files: [{
          expand: true,
          src: ['css/**/*'],
          dest: '<%= buildFolder %>/'
        }]
      },
      bowerStyles: {
        files: bowerStyleObject
      }
    },
    template: {
      development: {
        src: 'template.html',
        dest: 'index.html',
        engine: 'handlebars',
        variables: {
          livereload: true,
          scripts: templateScripts.development,
          styles: templateStyles.development,
          mainModule: pkgFile.name,
          title: '<%= lyriaConfig.title %> (Development build <%= buildVersion %>)',
          description: lyriaConfig.description,
          author: lyriaConfig.author
        }
      },
      production: {
        src: 'template.html',
        dest: '<%= buildFolder %>/index.html',
        engine: 'handlebars',
        variables: {
          livereload: false,
          scripts: templateScripts.production,
          styles: templateStyles.production,
          mainModule: pkgFile.name,
          title: lyriaConfig.title,
          description: lyriaConfig.description,
          author: lyriaConfig.author
        }
      }
    },
    uglify: {
      production: {
        files: uglifyLibObject
      }
    },
    compress: {
      all: {
        options: {
          archive: '<%= buildFolder %>.zip'
        },
        files: [{
          cwd: '<%= buildFolder %>/',
          src: ['**'],
          dest: '<%= pkg.name %>/'
        }]
      }
    },
    stylus: {
      options: {
        paths: ['stylus', 'stylus/lyria'],
        urlfunc: 'embedurl',
        import: ['nib', 'asset'],
      },
      development: {
        options: {
          compress: false,
          linenos: true
        },
        files: {
          'css/<%= pkg.name %>.css': 'stylus/**/*.styl'
        }
      },
      production: {
        options: {
          compress: true
        },
        files: {
          '<%= buildFolder %>/css/<%= pkg.name %>.css': 'stylus/**/*.styl'
        }
      }
    },
    csslint: {
      lint: {
        src: ['css/mygame.css']
      }
    },
    jshint: {
      assets: {
        src: ['assets/**/*.js']
      },
      source: {
        src: ['src/**/*.js', '!src/generated/**/*.js']
      }
    },
    watch: {
      options: {
        // Start a live reload server on the default port 35729
        livereload: true,
      },
      stylus: {
        files: 'stylus/**/*.styl',
        tasks: ['stylus:development']
      },
      assetList: {
        files: 'assets/**/*',
        tasks: ['lyriaAssetList']
      },
      scenes: {
        files: 'assets/scenes/*',
        tasks: ['lyriaScene']
      },
      i18nData: {
        files: 'assets/i18n/**/*.json',
        tasks: ['lyriaData']
      },
      template: {
        files: 'template.html',
        tasks: ['bower']
      },
      concat: {
        files: 'src/**/*.js',
        tasks: ['concat_sourcemap']
      }
    },
    lyriaData: {
      options: {
        namespace: '<%= pkg.name %>'
      },
      all: {
        options: {
          name: 'i18n'
        },
        dest: 'src/generated/i18n.js',
        src: ['assets/i18n/**/*.json']
      }
    },
    lyriaAssetList: {
      options: {
        namespace: '<%= pkg.name %>'
      },
      all: {
        dest: 'src/generated/assetlist.js',
        src: ['assets/**/*', '!**/README.md'],
        filter: 'isFile'
      }
    },
    lyriaScene: {
      all: {
        options: {
          namespace: '<%= pkg.name %>'
        },
        files: [{
          dest: 'src/generated/scenelist.js',
          src: ['assets/scenes/*'],
          filter: 'isDirectory'
        }]
      }
    }
  });

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  var bowerList = function(done) {
    bower.commands.list({
      paths: true
    }).on('end', function(results) {
      var prepareBowerAsset = function(value) {
        value = path.relative(process.cwd(), value);

        // All forward slashes, please
        value = value.split('\\').join('/');

        if (!value.endsWith('.css')) {

          if (!value.endsWith('.js')) {
            value += '/' + key + '.js';
          }

          var libFile = ['lib', path.basename(value)].join('/');
          var buildLibFile = [buildFolder, libFile].join('/');
          uglifyLibObject[buildLibFile] = value;

          if (libFilesPriorities.indexOf(key) >= 0) {
            templateScripts.development.unshift(value);
            templateScripts.production.unshift(libFile);
          } else {
            templateScripts.development.push(value);
            templateScripts.production.push(libFile);
          }

        } else {
          var styleFile = ['css', path.basename(value)].join('/');
          bowerStyleObject[[buildFolder, styleFile].join('/')] = value;

          templateStyles.development.unshift(value);
          templateStyles.production.unshift(styleFile);
        }
      };

      for (var key in results) {
        var val = results[key];

        if (val.indexOf(',') >= 0) {
          val = val.split(',');
        }

        if (Array.isArray(val)) {
          if (key === 'handlebars') {
            prepareBowerAsset(val[1]);
          } else {
            for (var i = 0, j = val.length; i < j; i++) {
              if (((path.extname(val[i]) === '.js') && !val[i].endsWith('.min.js')) || path.extname(val[i]) === '.css') {
                prepareBowerAsset(val[i]);
              }
            }
          }

        } else {
          prepareBowerAsset(val);
        }
      }

      templateScripts.development.push('js/<%= pkg.name %>.js');
      templateScripts.production.push('js/<%= pkg.name %>.js');

      done();
    });
  };

  grunt.registerTask('bower:development', 'Prepares scripts using bower components', function() {
    var done = this.async();

    bowerList(function() {
      grunt.task.run('template:development');
      done();
    });
  });

  grunt.registerTask('bower:production', 'Prepares scripts using bower components', function() {
    var done = this.async();

    bowerList(function() {
      grunt.task.run('template:production');
      done();
    });
  });

  grunt.registerTask('prebuild', 'Task before building the project', ['lyriaScene', 'lyriaAssetList', 'lyriaData', 'concat_sourcemap']);
  grunt.registerTask('test', 'Lints JavaScript and CSS files', ['jshint']);

  grunt.registerTask('development', 'Development build', ['prebuild', 'bower:development', 'stylus:development']);
  grunt.registerTask('production', 'Production build', ['prebuild', 'bower:production', 'uglify', 'copy', 'stylus:production']);
  grunt.registerTask('pack', 'Deploys project', ['production', 'compress']);

  grunt.registerTask('build', 'Builds the default project', ['development']);
  grunt.registerTask('default', 'Default task', ['development']);

  // The future in order
  grunt.registerTask('observe', 'Default task', ['development', 'watch']);

};
<commit_msg>Added connect task + Updated deploy task<commit_after>module.exports = function(grunt) {

  var fs = require('fs');
  require('es6-shim');
  var bower = require('bower');
  var path = require('path');

  var pkgFile = require('./package.json');
  var lyriaConfig = pkgFile.lyriaProject || {};

  var buildPrefix = 'builds';
  var buildVersion = pkgFile.version + '-' + grunt.template.today("yymmdd-HHMMss");
  var buildId = pkgFile.name + '-v' + buildVersion;
  var buildFolder = [buildPrefix, buildId].join('/');

  var libFiles = (fs.existsSync('./lib')) ? fs.readdirSync('./lib') : [];
  var styleFiles = (fs.existsSync('./css')) ? fs.readdirSync('./css') : [];

  var libFilesPriorities = ['almond', 'handlebars', 'fastclick', 'udefine'];

  var templateScripts = {
    development: [],
    production: []
  };
  var templateStyles = {
    development: [],
    production: []
  };

  var uglifyLibObject = {};
  var bowerStyleObject = {};

  for (var i = 0, j = libFiles.length; i < j; i++) {
    (function(iterator) {
      uglifyLibObject[path.join(buildFolder, 'lib', iterator)] = path.join('./lib', iterator);
      if (libFilesPriorities.indexOf(iterator) >= 0) {
        templateScripts.unshift('lib/' + iterator);
      } else {
        templateScripts.push('lib/' + iterator);
      }
    })(libFiles[i]);
  }

  uglifyLibObject[buildFolder + '/js/<%= pkg.name %>.js'] = '<%= concat_sourcemap.dist.dest %>';
  //templateScripts.push('js/<%= pkg.name %>.js');

  for (var k = 0, l = styleFiles.length; k < l; k++) {
    (function(iterator) {
      templateStyles.development.push('css/' + iterator);
      templateStyles.production.push('css/' + iterator);
    })(styleFiles[k]);
  }

  grunt.initConfig({
    pkg: pkgFile,
    lyriaConfig: lyriaConfig,
    buildVersion: buildVersion,
    buildFolder: buildFolder,
    concat_sourcemap: {
      options: {
        sourcesContent: true,
        sourceRoot: '/'
      },
      dist: {
        src: ['src/**/*.js'],
        dest: 'js/<%= pkg.name %>.js'
      }
    },
    copy: {
      assets: {
        files: [{
          expand: true,
          src: ['assets/**'],
          dest: '<%= buildFolder %>/',
          filter: function(filepath) {
            if ((filepath.indexOf(path.sep + 'scenes') >= 0) || (filepath.indexOf(path.sep + 'prefabs') >= 0)) {
              return false;
            } else {
              return true;
            }
          }
        }]
      },
      root: {
        files: [{
          expand: true,
          src: ['css/**/*', 'favicon.ico', '*.png'],
          dest: '<%= buildFolder %>/'
        }]
      },
      styles: {
        files: [{
          expand: true,
          src: ['css/**/*'],
          dest: '<%= buildFolder %>/'
        }]
      },
      bowerStyles: {
        files: bowerStyleObject
      }
    },
    template: {
      development: {
        src: 'template.html',
        dest: 'index.html',
        engine: 'handlebars',
        variables: {
          livereload: true,
          scripts: templateScripts.development,
          styles: templateStyles.development,
          mainModule: pkgFile.name,
          title: '<%= lyriaConfig.title %> (Development build <%= buildVersion %>)',
          description: lyriaConfig.description,
          author: lyriaConfig.author
        }
      },
      production: {
        src: 'template.html',
        dest: '<%= buildFolder %>/index.html',
        engine: 'handlebars',
        variables: {
          livereload: false,
          scripts: templateScripts.production,
          styles: templateStyles.production,
          mainModule: pkgFile.name,
          title: lyriaConfig.title,
          description: lyriaConfig.description,
          author: lyriaConfig.author
        }
      }
    },
    uglify: {
      production: {
        files: uglifyLibObject
      }
    },
    compress: {
      all: {
        options: {
          archive: '<%= buildFolder %>.zip'
        },
        files: [{
          cwd: '<%= buildFolder %>/',
          src: ['**'],
          dest: '<%= pkg.name %>/'
        }]
      }
    },
    stylus: {
      options: {
        paths: ['stylus', 'stylus/lyria'],
        urlfunc: 'embedurl',
        import: ['nib', 'asset'],
      },
      development: {
        options: {
          compress: false,
          linenos: true
        },
        files: {
          'css/<%= pkg.name %>.css': 'stylus/**/*.styl'
        }
      },
      production: {
        options: {
          compress: true
        },
        files: {
          '<%= buildFolder %>/css/<%= pkg.name %>.css': 'stylus/**/*.styl'
        }
      }
    },
    csslint: {
      lint: {
        src: ['css/mygame.css']
      }
    },
    jshint: {
      assets: {
        src: ['assets/**/*.js']
      },
      source: {
        src: ['src/**/*.js', '!src/generated/**/*.js']
      }
    },
    connect: {
      built: {
        options: {
          keepalive: true,
          base: '<%= buildFolder %>/',
          port: 9000
        }
      }
    },
    watch: {
      options: {
        // Start a live reload server on the default port 35729
        livereload: true,
      },
      stylus: {
        files: 'stylus/**/*.styl',
        tasks: ['stylus:development']
      },
      assetList: {
        files: 'assets/**/*',
        tasks: ['lyriaAssetList']
      },
      scenes: {
        files: 'assets/scenes/*',
        tasks: ['lyriaScene']
      },
      i18nData: {
        files: 'assets/i18n/**/*.json',
        tasks: ['lyriaData']
      },
      template: {
        files: 'template.html',
        tasks: ['bower']
      },
      concat: {
        files: 'src/**/*.js',
        tasks: ['concat_sourcemap']
      }
    },
    lyriaData: {
      options: {
        namespace: '<%= pkg.name %>'
      },
      all: {
        options: {
          name: 'i18n'
        },
        dest: 'src/generated/i18n.js',
        src: ['assets/i18n/**/*.json']
      }
    },
    lyriaAssetList: {
      options: {
        namespace: '<%= pkg.name %>'
      },
      all: {
        dest: 'src/generated/assetlist.js',
        src: ['assets/**/*', '!**/README.md'],
        filter: 'isFile'
      }
    },
    lyriaScene: {
      all: {
        options: {
          namespace: '<%= pkg.name %>'
        },
        files: [{
          dest: 'src/generated/scenelist.js',
          src: ['assets/scenes/*'],
          filter: 'isDirectory'
        }]
      }
    }
  });

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  var bowerList = function(done) {
    bower.commands.list({
      paths: true
    }).on('end', function(results) {
      var prepareBowerAsset = function(value) {
        value = path.relative(process.cwd(), value);

        // All forward slashes, please
        value = value.split('\\').join('/');

        if (!value.endsWith('.css')) {

          if (!value.endsWith('.js')) {
            value += '/' + key + '.js';
          }

          var libFile = ['lib', path.basename(value)].join('/');
          var buildLibFile = [buildFolder, libFile].join('/');
          uglifyLibObject[buildLibFile] = value;

          if (libFilesPriorities.indexOf(key) >= 0) {
            templateScripts.development.unshift(value);
            templateScripts.production.unshift(libFile);
          } else {
            templateScripts.development.push(value);
            templateScripts.production.push(libFile);
          }

        } else {
          var styleFile = ['css', path.basename(value)].join('/');
          bowerStyleObject[[buildFolder, styleFile].join('/')] = value;

          templateStyles.development.unshift(value);
          templateStyles.production.unshift(styleFile);
        }
      };

      for (var key in results) {
        var val = results[key];

        if (val.indexOf(',') >= 0) {
          val = val.split(',');
        }

        if (Array.isArray(val)) {
          if (key === 'handlebars') {
            prepareBowerAsset(val[1]);
          } else {
            for (var i = 0, j = val.length; i < j; i++) {
              if (((path.extname(val[i]) === '.js') && !val[i].endsWith('.min.js')) || path.extname(val[i]) === '.css') {
                prepareBowerAsset(val[i]);
              }
            }
          }

        } else {
          prepareBowerAsset(val);
        }
      }

      templateScripts.development.push('js/<%= pkg.name %>.js');
      templateScripts.production.push('js/<%= pkg.name %>.js');

      done();
    });
  };

  grunt.registerTask('bower:development', 'Prepares scripts using bower components', function() {
    var done = this.async();

    bowerList(function() {
      grunt.task.run('template:development');
      done();
    });
  });

  grunt.registerTask('bower:production', 'Prepares scripts using bower components', function() {
    var done = this.async();

    bowerList(function() {
      grunt.task.run('template:production');
      done();
    });
  });

  grunt.registerTask('prebuild', 'Task before building the project', ['lyriaScene', 'lyriaAssetList', 'lyriaData', 'concat_sourcemap']);
  grunt.registerTask('test', 'Lints JavaScript and CSS files', ['jshint']);

  grunt.registerTask('development', 'Development build', ['prebuild', 'bower:development', 'stylus:development']);
  grunt.registerTask('production', 'Production build', ['prebuild', 'bower:production', 'uglify', 'copy', 'stylus:production']);
  grunt.registerTask('pack', 'Packs project', ['production', 'compress']);
  grunt.registerTask('deploy', 'Builds project in production mode and starts a local server', ['production', 'connect'])

  grunt.registerTask('build', 'Builds the default project', ['development']);
  grunt.registerTask('default', 'Default task', ['development']);

  // The future in order
  grunt.registerTask('observe', 'Default task', ['development', 'watch']);

};
<|endoftext|>


<commit_before>angular.module('openlayers-directive').directive('olLayer', function($log, $q, olMapDefaults, olHelpers) {

    return {
        restrict: 'E',
        scope: {
            properties: '=olLayerProperties'
        },
        replace: false,
        require: '^openlayers',
        link: function(scope, element, attrs, controller) {
            var isDefined   = olHelpers.isDefined;
            var equals      = olHelpers.equals;
            var olScope     = controller.getOpenlayersScope();
            var createLayer = olHelpers.createLayer;
            var setVectorLayerEvents = olHelpers.setVectorLayerEvents;
            var detectLayerType = olHelpers.detectLayerType;
            var createStyle = olHelpers.createStyle;
            var isBoolean   = olHelpers.isBoolean;
            var addLayerBeforeMarkers = olHelpers.addLayerBeforeMarkers;
            var isNumber    = olHelpers.isNumber;
            var insertLayer = olHelpers.insertLayer;
            var removeLayer = olHelpers.removeLayer;

            olScope.getMap().then(function(map) {
                var projection = map.getView().getProjection();
                var defaults = olMapDefaults.setDefaults(olScope);
                var layerCollection = map.getLayers();
                var olLayer;

                scope.$on('$destroy', function() {
                    removeLayer(layerCollection, olLayer.index);
                    map.removeLayer(olLayer);
                });

                if (!isDefined(scope.properties)) {
                    if (isDefined(attrs.sourceType) && isDefined(attrs.sourceUrl)) {
                        var l = {
                            source: {
                                url: attrs.sourceUrl,
                                type: attrs.sourceType
                            }
                        };

                        olLayer = createLayer(l, projection, attrs.layerName);
                        if (detectLayerType(l) === 'Vector') {
                            setVectorLayerEvents(defaults.events, map, scope, attrs.name);
                        }
                        addLayerBeforeMarkers(layerCollection, olLayer);
                    }
                    return;
                }

                scope.$watch('properties', function(properties, oldProperties) {
                    if (!isDefined(properties.source) || !isDefined(properties.source.type)) {
                        return;
                    }

                    if (!isDefined(properties.visible)) {
                        properties.visible = true;
                        return;
                    }

                    if (!isDefined(properties.opacity)) {
                        properties.opacity = 1;
                        return;
                    }

                    var style;
                    if (!isDefined(olLayer)) {
                        olLayer = createLayer(properties, projection);
                        if (isDefined(properties.index)) {
                            insertLayer(layerCollection, properties.index, olLayer);
                        } else {
                            addLayerBeforeMarkers(layerCollection, olLayer);
                        }

                        if (detectLayerType(properties) === 'Vector') {
                            setVectorLayerEvents(defaults.events, map, scope, properties.name);
                        }

                        if (isBoolean(properties.visible)) {
                            olLayer.setVisible(properties.visible);
                        }

                        if (properties.opacity) {
                            olLayer.setOpacity(properties.opacity);
                        }

                        if (angular.isArray(properties.extent)) {
                            olLayer.setExtent(properties.extent);
                        }

                        if (properties.style) {
                            if (!angular.isFunction(properties.style)) {
                                style = createStyle(properties.style);
                            } else {
                                style = properties.style;
                            }
                            olLayer.setStyle(style);
                        }

                    } else {

                        if (isDefined(oldProperties) &&
                           !(equals(properties, oldProperties) && equals(properties.style, oldProperties.style))) {

                            if (!equals(properties.source, oldProperties.source)) {
                                var idx = olLayer.index;
                                layerCollection.removeAt(idx);
                                olLayer = createLayer(properties, projection);
                                if (isDefined(olLayer)) {
                                    insertLayer(layerCollection, idx, olLayer);

                                    if (detectLayerType(properties) === 'Vector') {
                                        setVectorLayerEvents(defaults.events, map, scope, properties.name);
                                    }
                                }
                            }

                            if (isDefined(properties.index) && properties.index !== olLayer.index) {
                                removeLayer(layerCollection, olLayer.index);
                                insertLayer(layerCollection, properties.index, olLayer);
                            }

                            if (isBoolean(properties.visible) && properties.visible !== oldProperties.visible) {
                                olLayer.setVisible(properties.visible);
                            }

                            if (properties.opacity !== oldProperties.opacity) {
                                if (isNumber(properties.opacity) || isNumber(parseFloat(properties.opacity))) {
                                    olLayer.setOpacity(properties.opacity);
                                }
                            }

                            if (isDefined(properties.style) && !equals(properties.style, oldProperties.style)) {
                                if (!angular.isFunction(properties.style)) {
                                    style = createStyle(properties.style);
                                } else {
                                    style = properties.style;
                                }
                                olLayer.setStyle(style);
                            }
                        }
                    }
                }, true);
            });
        }
    };
});
<commit_msg>Fix watcher to fire on method change<commit_after>angular.module('openlayers-directive').directive('olLayer', function($log, $q, olMapDefaults, olHelpers) {

    return {
        restrict: 'E',
        scope: {
            properties: '=olLayerProperties'
        },
        replace: false,
        require: '^openlayers',
        link: function(scope, element, attrs, controller) {
            var isDefined   = olHelpers.isDefined;
            var equals      = olHelpers.equals;
            var olScope     = controller.getOpenlayersScope();
            var createLayer = olHelpers.createLayer;
            var setVectorLayerEvents = olHelpers.setVectorLayerEvents;
            var detectLayerType = olHelpers.detectLayerType;
            var createStyle = olHelpers.createStyle;
            var isBoolean   = olHelpers.isBoolean;
            var addLayerBeforeMarkers = olHelpers.addLayerBeforeMarkers;
            var isNumber    = olHelpers.isNumber;
            var insertLayer = olHelpers.insertLayer;
            var removeLayer = olHelpers.removeLayer;

            olScope.getMap().then(function(map) {
                var projection = map.getView().getProjection();
                var defaults = olMapDefaults.setDefaults(olScope);
                var layerCollection = map.getLayers();
                var olLayer;

                scope.$on('$destroy', function() {
                    removeLayer(layerCollection, olLayer.index);
                    map.removeLayer(olLayer);
                });

                if (!isDefined(scope.properties)) {
                    if (isDefined(attrs.sourceType) && isDefined(attrs.sourceUrl)) {
                        var l = {
                            source: {
                                url: attrs.sourceUrl,
                                type: attrs.sourceType
                            }
                        };

                        olLayer = createLayer(l, projection, attrs.layerName);
                        if (detectLayerType(l) === 'Vector') {
                            setVectorLayerEvents(defaults.events, map, scope, attrs.name);
                        }
                        addLayerBeforeMarkers(layerCollection, olLayer);
                    }
                    return;
                }

                scope.$watchCollection('properties', function(properties, oldProperties) {
                    if (!isDefined(properties.source) || !isDefined(properties.source.type)) {
                        return;
                    }

                    if (!isDefined(properties.visible)) {
                        properties.visible = true;
                        return;
                    }

                    if (!isDefined(properties.opacity)) {
                        properties.opacity = 1;
                        return;
                    }

                    var style;
                    if (!isDefined(olLayer)) {
                        olLayer = createLayer(properties, projection);
                        if (isDefined(properties.index)) {
                            insertLayer(layerCollection, properties.index, olLayer);
                        } else {
                            addLayerBeforeMarkers(layerCollection, olLayer);
                        }

                        if (detectLayerType(properties) === 'Vector') {
                            setVectorLayerEvents(defaults.events, map, scope, properties.name);
                        }

                        if (isBoolean(properties.visible)) {
                            olLayer.setVisible(properties.visible);
                        }

                        if (properties.opacity) {
                            olLayer.setOpacity(properties.opacity);
                        }

                        if (angular.isArray(properties.extent)) {
                            olLayer.setExtent(properties.extent);
                        }

                        if (properties.style) {
                            if (!angular.isFunction(properties.style)) {
                                style = createStyle(properties.style);
                            } else {
                                style = properties.style;
                            }
                            olLayer.setStyle(style);
                        }

                    } else {

                        if (isDefined(oldProperties) &&
                           !(equals(properties, oldProperties) && equals(properties.style, oldProperties.style))) {

                            if (!equals(properties.source, oldProperties.source)) {
                                var idx = olLayer.index;
                                layerCollection.removeAt(idx);
                                olLayer = createLayer(properties, projection);
                                if (isDefined(olLayer)) {
                                    insertLayer(layerCollection, idx, olLayer);

                                    if (detectLayerType(properties) === 'Vector') {
                                        setVectorLayerEvents(defaults.events, map, scope, properties.name);
                                    }
                                }
                            }

                            if (isDefined(properties.index) && properties.index !== olLayer.index) {
                                removeLayer(layerCollection, olLayer.index);
                                insertLayer(layerCollection, properties.index, olLayer);
                            }

                            if (isBoolean(properties.visible) && properties.visible !== oldProperties.visible) {
                                olLayer.setVisible(properties.visible);
                            }

                            if (properties.opacity !== oldProperties.opacity) {
                                if (isNumber(properties.opacity) || isNumber(parseFloat(properties.opacity))) {
                                    olLayer.setOpacity(properties.opacity);
                                }
                            }

                            if (isDefined(properties.style) && !equals(properties.style, oldProperties.style)) {
                                if (!angular.isFunction(properties.style)) {
                                    style = createStyle(properties.style);
                                } else {
                                    style = properties.style;
                                }
                                olLayer.setStyle(style);
                            }
                        }
                    }
                }, true);
            });
        }
    };
});
<|endoftext|>


<commit_before>define("ace/snippets/php",["require","exports","module"], function(require, exports, module) {
"use strict";

exports.snippetText = "snippet <?\n\
	<?php\n\
\n\
	${1}\n\
snippet ec\n\
	echo ${1};\n\
snippet <?e\n\
	<?php echo ${1} ?>\n\
# this one is for php5.4\n\
snippet <?=\n\
	<?=${1}?>\n\
snippet ns\n\
	namespace ${1:Foo\\Bar\\Baz};\n\
	${2}\n\
snippet use\n\
	use ${1:Foo\\Bar\\Baz};\n\
	${2}\n\
snippet c\n\
	${1:abstract }class ${2:$FILENAME}\n\
	{\n\
		${3}\n\
	}\n\
snippet i\n\
	interface ${1:$FILENAME}\n\
	{\n\
		${2}\n\
	}\n\
snippet t.\n\
	$this->${1}\n\
snippet f\n\
	function ${1:foo}(${2:array }${3:$bar})\n\
	{\n\
		${4}\n\
	}\n\
# method\n\
snippet m\n\
	${1:abstract }${2:protected}${3: static} function ${4:foo}(${5:array }${6:$bar})\n\
	{\n\
		${7}\n\
	}\n\
# setter method\n\
snippet sm \n\
	/**\n\
	 * Sets the value of ${1:foo}\n\
	 *\n\
	 * @param ${2:$1} $$1 ${3:description}\n\
	 *\n\
	 * @return ${4:$FILENAME}\n\
	 */\n\
	${5:public} function set${6:$2}(${7:$2 }$$1)\n\
	{\n\
		$this->${8:$1} = $$1;\n\
		return $this;\n\
	}${9}\n\
# getter method\n\
snippet gm\n\
	/**\n\
	 * Gets the value of ${1:foo}\n\
	 *\n\
	 * @return ${2:$1}\n\
	 */\n\
	${3:public} function get${4:$2}()\n\
	{\n\
		return $this->${5:$1};\n\
	}${6}\n\
#setter\n\
snippet $s\n\
	${1:$foo}->set${2:Bar}(${3});\n\
#getter\n\
snippet $g\n\
	${1:$foo}->get${2:Bar}();\n\
\n\
# Tertiary conditional\n\
snippet =?:\n\
	$${1:foo} = ${2:true} ? ${3:a} : ${4};\n\
snippet ?:\n\
	${1:true} ? ${2:a} : ${3}\n\
\n\
snippet C\n\
	$_COOKIE['${1:variable}']${2}\n\
snippet E\n\
	$_ENV['${1:variable}']${2}\n\
snippet F\n\
	$_FILES['${1:variable}']${2}\n\
snippet G\n\
	$_GET['${1:variable}']${2}\n\
snippet P\n\
	$_POST['${1:variable}']${2}\n\
snippet R\n\
	$_REQUEST['${1:variable}']${2}\n\
snippet S\n\
	$_SERVER['${1:variable}']${2}\n\
snippet SS\n\
	$_SESSION['${1:variable}']${2}\n\
	\n\
# the following are old ones\n\
snippet inc\n\
	include '${1:file}';${2}\n\
snippet inc1\n\
	include_once '${1:file}';${2}\n\
snippet req\n\
	require '${1:file}';${2}\n\
snippet req1\n\
	require_once '${1:file}';${2}\n\
# Start Docblock\n\
snippet /*\n\
	/**\n\
	 * ${1}\n\
	 */\n\
# Class - post doc\n\
snippet doc_cp\n\
	/**\n\
	 * ${1:undocumented class}\n\
	 *\n\
	 * @package ${2:default}\n\
	 * @subpackage ${3:default}\n\
	 * @author ${4:`g:snips_author`}\n\
	 */${5}\n\
# Class Variable - post doc\n\
snippet doc_vp\n\
	/**\n\
	 * ${1:undocumented class variable}\n\
	 *\n\
	 * @var ${2:string}\n\
	 */${3}\n\
# Class Variable\n\
snippet doc_v\n\
	/**\n\
	 * ${3:undocumented class variable}\n\
	 *\n\
	 * @var ${4:string}\n\
	 */\n\
	${1:var} $${2};${5}\n\
# Class\n\
snippet doc_c\n\
	/**\n\
	 * ${3:undocumented class}\n\
	 *\n\
	 * @package ${4:default}\n\
	 * @subpackage ${5:default}\n\
	 * @author ${6:`g:snips_author`}\n\
	 */\n\
	${1:}class ${2:}\n\
	{\n\
		${7}\n\
	} // END $1class $2\n\
# Constant Definition - post doc\n\
snippet doc_dp\n\
	/**\n\
	 * ${1:undocumented constant}\n\
	 */${2}\n\
# Constant Definition\n\
snippet doc_d\n\
	/**\n\
	 * ${3:undocumented constant}\n\
	 */\n\
	define(${1}, ${2});${4}\n\
# Function - post doc\n\
snippet doc_fp\n\
	/**\n\
	 * ${1:undocumented function}\n\
	 *\n\
	 * @return ${2:void}\n\
	 * @author ${3:`g:snips_author`}\n\
	 */${4}\n\
# Function signature\n\
snippet doc_s\n\
	/**\n\
	 * ${4:undocumented function}\n\
	 *\n\
	 * @return ${5:void}\n\
	 * @author ${6:`g:snips_author`}\n\
	 */\n\
	${1}function ${2}(${3});${7}\n\
# Function\n\
snippet doc_f\n\
	/**\n\
	 * ${4:undocumented function}\n\
	 *\n\
	 * @return ${5:void}\n\
	 * @author ${6:`g:snips_author`}\n\
	 */\n\
	${1}function ${2}(${3})\n\
	{${7}\n\
	}\n\
# Header\n\
snippet doc_h\n\
	/**\n\
	 * ${1}\n\
	 *\n\
	 * @author ${2:`g:snips_author`}\n\
	 * @version ${3:$Id$}\n\
	 * @copyright ${4:$2}, `strftime('%d %B, %Y')`\n\
	 * @package ${5:default}\n\
	 */\n\
	\n\
# Interface\n\
snippet interface\n\
	/**\n\
	 * ${2:undocumented class}\n\
	 *\n\
	 * @package ${3:default}\n\
	 * @author ${4:`g:snips_author`}\n\
	 */\n\
	interface ${1:$FILENAME}\n\
	{\n\
		${5}\n\
	}\n\
# class ...\n\
snippet class\n\
	/**\n\
	 * ${1}\n\
	 */\n\
	class ${2:$FILENAME}\n\
	{\n\
		${3}\n\
		/**\n\
		 * ${4}\n\
		 */\n\
		${5:public} function ${6:__construct}(${7:argument})\n\
		{\n\
			${8:// code...}\n\
		}\n\
	}\n\
# define(...)\n\
snippet def\n\
	define('${1}'${2});${3}\n\
# defined(...)\n\
snippet def?\n\
	${1}defined('${2}')${3}\n\
snippet wh\n\
	while (${1:/* condition */}) {\n\
		${2:// code...}\n\
	}\n\
# do ... while\n\
snippet do\n\
	do {\n\
		${2:// code... }\n\
	} while (${1:/* condition */});\n\
snippet if\n\
	if (${1:/* condition */}) {\n\
		${2:// code...}\n\
	}\n\
snippet ifil\n\
	<?php if (${1:/* condition */}): ?>\n\
		${2:}\n\
	<?php endif; ?>\n\
snippet ife\n\
	if (${1:/* condition */}) {\n\
		${2:// code...}\n\
	} else {\n\
		${3:// code...}\n\
	}\n\
	${4}\n\
snippet ifeil\n\
	<?php if (${1:/* condition */}): ?>\n\
		${2:}\n\
	<?php else: ?>\n\
		${3:}\n\
	<?php endif; ?>\n\
	${4}\n\
snippet else\n\
	else {\n\
		${1:// code...}\n\
	}\n\
snippet elseif\n\
	elseif (${1:/* condition */}) {\n\
		${2:// code...}\n\
	}\n\
snippet switch\n\
	switch ($${1:variable}) {\n\
		case '${2:value}':\n\
			${3:// code...}\n\
			break;\n\
		${5}\n\
		default:\n\
			${4:// code...}\n\
			break;\n\
	}\n\
snippet case\n\
	case '${1:value}':\n\
		${2:// code...}\n\
		break;${3}\n\
snippet for\n\
	for ($${2:i} = 0; $$2 < ${1:count}; $$2${3:++}) {\n\
		${4: // code...}\n\
	}\n\
snippet foreach\n\
	foreach ($${1:variable} as $${2:value}) {\n\
		${3:// code...}\n\
	}\n\
snippet foreachil\n\
	<?php foreach ($${1:variable} as $${2:value}): ?>\n\
		${3:}\n\
	<?php endforeach; ?>\n\
snippet foreachk\n\
	foreach ($${1:variable} as $${2:key} => $${3:value}) {\n\
		${4:// code...}\n\
	}\n\
snippet foreachkil\n\
	<?php foreach ($${1:variable} as $${2:key} => $${3:value}): ?>\n\
		${4:}\n\
	<?php endforeach; ?>\n\
# $... = array (...)\n\
snippet array\n\
	$${1:arrayName} = array('${2}' => ${3});${4}\n\
snippet try\n\
	try {\n\
		${2}\n\
	} catch (${1:Exception} $e) {\n\
	}\n\
# lambda with closure\n\
snippet lambda\n\
	${1:static }function (${2:args}) use (${3:&$x, $y /*put vars in scope (closure) */}) {\n\
		${4}\n\
	};\n\
# pre_dump();\n\
snippet pd\n\
	echo '
'; var_dump(${1}); echo '
';\n\
# pre_dump(); die();\n\
snippet pdd\n\
	echo '
'; var_dump(${1}); echo '
'; die(${2:});\n\
snippet vd\n\
	var_dump(${1});\n\
snippet vdd\n\
	var_dump(${1}); die(${2:});\n\
snippet http_redirect\n\
	header (\"HTTP/1.1 301 Moved Permanently\"); \n\
	header (\"Location: \".URL); \n\
	exit();\n\
# Getters & Setters\n\
snippet gs\n\
	/**\n\
	 * Gets the value of ${1:foo}\n\
	 *\n\
	 * @return ${2:$1}\n\
	 */\n\
	public function get${3:$2}()\n\
	{\n\
		return $this->${4:$1};\n\
	}\n\
\n\
	/**\n\
	 * Sets the value of $1\n\
	 *\n\
	 * @param $2 $$1 ${5:description}\n\
	 *\n\
	 * @return ${6:$FILENAME}\n\
	 */\n\
	public function set$3(${7:$2 }$$1)\n\
	{\n\
		$this->$4 = $$1;\n\
		return $this;\n\
	}${8}\n\
# anotation, get, and set, useful for doctrine\n\
snippet ags\n\
	/**\n\
	 * ${1:description}\n\
	 * \n\
	 * @${7}\n\
	 */\n\
	${2:protected} $${3:foo};\n\
\n\
	public function get${4:$3}()\n\
	{\n\
		return $this->$3;\n\
	}\n\
\n\
	public function set$4(${5:$4 }$${6:$3})\n\
	{\n\
		$this->$3 = $$6;\n\
		return $this;\n\
	}\n\
snippet rett\n\
	return true;\n\
snippet retf\n\
	return false;\n\
";
exports.scope = "php";

});
<commit_msg>Update tmp/bower_components/ace-builds/src/snippets/php.js<commit_after><|endoftext|>