<commit_before>/*!
 * Copyright 2017 Joji Doi, Greg Mendez-Weeks
 * Licensed under the MIT license
 *
 * Format: http://jsbeautifier.org/
 * - with Indent with 2 spaces
 * - Remove all extra newlines
 * - Wrap lines near 110 characters
 * - Braces with control statement
 * - Add one indent level
 */
var jsonResult;
var mq = window.matchMedia("(min-width: 40em)");
var barContainer = document.getElementById("myScrollspy");
var bar = document.getElementById("navBar");
resizeContent();
var isMobile = false;
function decode(string) {
  return string.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
isMobile = true;
}

function resizeContent() {
  if (mq.matches) {
    bar.className = "nav nav-pills nav-stacked ";
    barContainer.className = "col-sm-1 bg-faded sidebar";
    // window width is at least 40em
  } else {
    bar.className = "breadcrumb";
    barContainer.className = "breadcrumb-item";
    // window width is less than 40em
  }
}

function getMediaFilePath(mediaItem, dirName) {
  return "ext-content" + decode(dirName + "/" + mediaItem.name);
}

function getExt(mediaItem) {
  if(mediaItem.name != null){
    var end = mediaItem.name.toString().toLowerCase();
    var ind = end.lastIndexOf(".");
    end = end.substring(ind);
    return end;
  }return;
}

function renderPdf(mediaItem, dir) {
  // Note embed nor iframe works great to render pdf. So, this is workaround until better alternative is found.
  //window.location = getMediaFilePath(mediaItem, dir);
    if(!isMobile){
      $(".bubble-audio-title").text(mediaItem.name);
      $("#pdf_elm").empty(); // clear previous source element
      var pdf_src = $("", {
        "src": getMediaFilePath(mediaItem, dir),
        "type": "application/pdf",
        "class": "txt",
        }).appendTo("#pdf_elm");
      $("#pdf_elm").load();
    }else{
        window.location = getMediaFilePath(mediaItem, dir);
    }
}

function renderText(mediaItem, dir) {
  $(".bubble-audio-title").text(mediaItem.name);
  $("#pdf_elm").empty(); // clear previous source element
  var pdf_src = $("", {
    "src": getMediaFilePath(mediaItem, dir),
    "class": "txt",
    "height": "50em",
    "width": "100%"
  }).appendTo("#pdf_elm");
  $("#pdf_elm").load();
}

function renderDoc(mediaItem) {
  var mediaType = getExt(mediaItem);
  switch (mediaType) {
    case ".pdf":
      renderPdf(mediaItem);
      break;
    case ".txt":
      renderText(mediaItem);
      break;
    default:
      console.log("Unsupported media type " + mediaType);
  }
}

function renderAudio(mediaItem, dir) {
  $(".bubble-audio-title").text(mediaItem.name);
  $("#audio_elm").empty(); // clear previous source element
  var type = getExt(mediaItem).substring(1);
  var video_src = $("<source></source>", {
    "src": getMediaFilePath(mediaItem, dir),
    "type": "audio/" + type
  }).appendTo("#audio_elm");
  $("#audio_elm").load();
}

function renderVideo(mediaItem, dir) {
  var type = getExt(mediaItem).substring(1);
  $("#video_elm").empty(); // clear previous source element
  var sour = $("<source></source>", {
    "src": getMediaFilePath(mediaItem, dir),
    "type": "video/" + type,
  }).appendTo("#video_elm");
  $("#video_elm").load();
}

function renderPhoto(mediaItem, dir) {
  $("#img_elm").empty(); // clear previous source element
  var video_src = $("", {
    "src": getMediaFilePath(mediaItem, dir),
    "class": "modal-content"
  }).appendTo("#img_elm");
  $("#img_elm").load();
}
//
// Photo viewer is still under construction.
//
function renderPhotoOld(mediaItem) {
  webix.ui({
    view: "window",
    id: "image_window",
    fullscreen: true,
    head: {
      view: "toolbar",
      margin: -10,
      cols: [{
        view: "label",
        label: "~~ Images Beta ~~"
      }, {
        view: "icon",
        icon: "times-circle",
        click: function() {
          $$('image_window').close();
        }
      }]
    },
    body: {
      view: "carousel",
      id: "bubble_carousel",
      fullscreen: true,
      cols: getImageFilePathsFromCache()
    }
  });
  $$("bubble_carousel").setActive(mediaItem.id);
  $$("image_window").show();
}
/*
 * Retrieve cached image file path data.
 * See cacheImageFilePaths(media_file_list) function for cache creation.
 */
function getImageFilePathsFromCache() {
  return $("body").data("image file list");
}
/*
 * Save image file paths data in cache for later reuse via getImageFilePathsFromCache() function.
 */
function cacheImageFilePaths(media_file_list) {
  function img(obj) {
    return '
' + obj
      .name + '
';
  }
  console.log("This should be called only once.");
  var imageFilePaths = [];
  media_file_list.forEach(function(media_file) {
    if (media_file.type.toString().toLowerCase() == "photos") {
      imageFilePaths.push({
        id: media_file.id,
        css: "image",
        template: img,
        data: webix.copy({
          src: getMediaFilePath(media_file),
          title: media_file.name
        })
      });
    }
  });
  $("body").data("image file list", imageFilePaths);
}
var folderStack = [];

function renderMediaDynamic(mediaItem, title) {
  if (mediaItem.type == "directory") {
    var elementIcon;
    var element;
    elementIcon = document.getElementById(mediaItem.name + "Icon");
    var opened = false;
    for (var i = 0; i < folderStack.length; i++) {
      if ((folderStack[i].indexOf("/" + mediaItem.name + "/") > -1) || (folderStack[i].substring(folderStack[
          i].lastIndexOf("/") + 1) == mediaItem.name)) {
        element = document.getElementById(folderStack[i]);
        element.outerHTML = "";
        delete element;
        var elephant = document.getElementById(folderStack[i] + "bar");
        elephant.outerHTML = "";
        delete elephant;
        elementIcon.src = "img/folder.png";
        folderStack.splice(i, 1);
        i--;
        opened = true;
      }
    }
    if (!opened) {
      elementIcon.src = "img/openFolder.png";
      folderStack.push(elementIcon.parentElement.parentElement.id + "/" + mediaItem.name);
      addNavBar(elementIcon.parentElement.parentElement.id + "/" + mediaItem.name, elementIcon.parentElement.parentElement);
      getFilesInDir(mediaItem.contents, elementIcon.parentElement.parentElement.id + "/" + mediaItem.name);
      elementIcon.parentElement.parentElement.scrollIntoView();
    }
  } else {
    switch (getExt(mediaItem)) {
      case ".ogg":
      case ".mp3":
        renderAudio(mediaItem, title);
        break;
      case ".pdf":
        renderPdf(mediaItem, title);
        break;
      case ".webm":
      case ".mp4":
        renderVideo(mediaItem, title);
        break;
      case ".png":
      case ".jpg":
        renderPhoto(mediaItem, title);
        break;
      case ".txt":
        renderText(mediaItem, title);
        mediaSrc = "img/textFile.png";
        break;
        //case "tv":
        // break;
      default:
        mediaSrc = "img/unreadable.png";
        break;
    }
  }
}

function getCurrentDir(title) {
  return title.substring(title.lastIndexOf("/") + 1);
}

function addNavBar(name, parent) {
  if (name != "") {
    var nam = name + "bar";
    var nav = $("

", {
      "class": "",
      "id": nam,
    });
    var txt = $("", {});
    txt.html(getCurrentDir(name));
    txt.appendTo(nav);
    nav.appendTo("#navBar");
  } else {
    var nam = "Root" + "bar";
    var nav = $("

", {
      "class": "",
      "id": nam,
    });
    var txt = $("", {
      "href": "#" + ""
    });
    txt.html(getCurrentDir("Root"));
    txt.appendTo(nav);
    nav.appendTo("#navBar");
  }
  nav.on("click", function() {
    parent.scrollIntoView();
  });
}

function getFilesInDir(dir, title) {
  var mediaDirs = jsonResult;
  var currentDir = getCurrentDir(title);
  var directory = $("

", {
    "id": title,
    "class": "container"
  });
  directory.appendTo("#files_list");
  if (title != "") {
    var name = $("
" + currentDir + "
", {});
  } else {
    var name = $("
Root
", {});
  }
  name.appendTo(directory);
  $.each(dir, function(i, mediaItem) {
    var mediaSrc = getMediaFilePath(mediaItem, title);
    var divType = "img";
    var modalType = "";
    if (mediaItem.type == "directory") {
      mediaSrc = "img/folder.png";
    } else {
      switch (getExt(mediaItem)) {
        //   case "document":
        //  mediaSrc = mediaItem;
        //break;
        case ".ogg":
        case ".mp3":
          mediaSrc = "img/musicFile.png";
          modalType = "audio";
          break;
        case ".pdf":
          mediaSrc = "img/pdfFile.png";
          modalType = "pdf";
          break;
        case ".webm":
        case ".mp4":
          if(!isMobile){
            modalType = "video";
              divType = "video";
          }
          else{
              modalType = "video";
              divType = "img";
              mediaSrc = "img/videoFile.png";
          }
          break;
        case ".png":
        case ".jpg":
          modalType = "img";
          break;
        case ".txt":
          mediaSrc = "img/textFile.png";
          modalType = "pdf";
          break;
          //case "tv":
          // break;
        default:
          mediaSrc = "img/unreadable.png";
          break;
      }
    }
    var wrapper = $("

", {
      "class": "thumbContainer",
    });
    var image = $("<" + divType + "></" + divType + ">", {
      "id": mediaItem.name + "Icon",
      "class": "bubble_thumb",
      "data-toggle": "modal",
      "data-target": "#" + modalType + "_modal",
      "value": mediaItem,
      "src": mediaSrc
    });
    var lnk = $("", {
      "class": "fileName",
      "data-toggle": "modal",
      "data-target": "#" + modalType + "_modal",
      "value": mediaItem
    });
    lnk.html(mediaItem.name);
    lnk.on("click", function() {
      renderMediaDynamic(mediaItem, title);
    });
    image.html(mediaItem.name);
    image.on("click", function() {
      renderMediaDynamic(mediaItem, title);
    });
    // wrapper.append(image);
    //wrapper.append(lnk);
    wrapper.appendTo(directory);
    image.appendTo(wrapper);
    lnk.appendTo(wrapper);
  });
}
$.getJSON("data/media_files_list_v3.json", function(result) {
  jsonResult = result;
  var parent = document.getElementById("files_list");
  addNavBar("", parent);
  getFilesInDir(result, "");
}); // end of getJSON()
$("#audio_modal").on("hide.bs.modal", function(e) {
  $("#audio_elm")[0].pause();
});
$("#video_modal").on("hide.bs.modal", function(e) {
  $("#video_elm")[0].pause();
});<commit_msg>Disabled video preview, it is unreliable when run from bubble<commit_after>/*!
 * Copyright 2017 Joji Doi, Greg Mendez-Weeks
 * Licensed under the MIT license
 *
 * Format: http://jsbeautifier.org/
 * - with Indent with 2 spaces
 * - Remove all extra newlines
 * - Wrap lines near 110 characters
 * - Braces with control statement
 * - Add one indent level
 */
var jsonResult;
var mq = window.matchMedia("(min-width: 40em)");
var barContainer = document.getElementById("myScrollspy");
var bar = document.getElementById("navBar");
resizeContent();
var isMobile = false;
function decode(string) {
  return string.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
isMobile = true;
}

function resizeContent() {
  if (mq.matches) {
    bar.className = "nav nav-pills nav-stacked ";
    barContainer.className = "col-sm-1 bg-faded sidebar";
    // window width is at least 40em
  } else {
    bar.className = "breadcrumb";
    barContainer.className = "breadcrumb-item";
    // window width is less than 40em
  }
}

function getMediaFilePath(mediaItem, dirName) {
  return "ext-content" + decode(dirName + "/" + mediaItem.name);
}

function getExt(mediaItem) {
  if(mediaItem.name != null){
    var end = mediaItem.name.toString().toLowerCase();
    var ind = end.lastIndexOf(".");
    end = end.substring(ind);
    return end;
  }return;
}

function renderPdf(mediaItem, dir) {
  // Note embed nor iframe works great to render pdf. So, this is workaround until better alternative is found.
  //window.location = getMediaFilePath(mediaItem, dir);
    if(!isMobile){
      $(".bubble-audio-title").text(mediaItem.name);
      $("#pdf_elm").empty(); // clear previous source element
      var pdf_src = $("", {
        "src": getMediaFilePath(mediaItem, dir),
        "type": "application/pdf",
        "class": "txt",
        }).appendTo("#pdf_elm");
      $("#pdf_elm").load();
    }else{
        window.location = getMediaFilePath(mediaItem, dir);
    }
}

function renderText(mediaItem, dir) {
  $(".bubble-audio-title").text(mediaItem.name);
  $("#pdf_elm").empty(); // clear previous source element
  var pdf_src = $("", {
    "src": getMediaFilePath(mediaItem, dir),
    "class": "txt",
    "height": "50em",
    "width": "100%"
  }).appendTo("#pdf_elm");
  $("#pdf_elm").load();
}

function renderDoc(mediaItem) {
  var mediaType = getExt(mediaItem);
  switch (mediaType) {
    case ".pdf":
      renderPdf(mediaItem);
      break;
    case ".txt":
      renderText(mediaItem);
      break;
    default:
      console.log("Unsupported media type " + mediaType);
  }
}

function renderAudio(mediaItem, dir) {
  $(".bubble-audio-title").text(mediaItem.name);
  $("#audio_elm").empty(); // clear previous source element
  var type = getExt(mediaItem).substring(1);
  var video_src = $("<source></source>", {
    "src": getMediaFilePath(mediaItem, dir),
    "type": "audio/" + type
  }).appendTo("#audio_elm");
  $("#audio_elm").load();
}

function renderVideo(mediaItem, dir) {
  var type = getExt(mediaItem).substring(1);
  $("#video_elm").empty(); // clear previous source element
  var sour = $("<source></source>", {
    "src": getMediaFilePath(mediaItem, dir),
    "type": "video/" + type,
  }).appendTo("#video_elm");
  $("#video_elm").load();
}

function renderPhoto(mediaItem, dir) {
  $("#img_elm").empty(); // clear previous source element
  var video_src = $("", {
    "src": getMediaFilePath(mediaItem, dir),
    "class": "modal-content"
  }).appendTo("#img_elm");
  $("#img_elm").load();
}
//
// Photo viewer is still under construction.
//
function renderPhotoOld(mediaItem) {
  webix.ui({
    view: "window",
    id: "image_window",
    fullscreen: true,
    head: {
      view: "toolbar",
      margin: -10,
      cols: [{
        view: "label",
        label: "~~ Images Beta ~~"
      }, {
        view: "icon",
        icon: "times-circle",
        click: function() {
          $$('image_window').close();
        }
      }]
    },
    body: {
      view: "carousel",
      id: "bubble_carousel",
      fullscreen: true,
      cols: getImageFilePathsFromCache()
    }
  });
  $$("bubble_carousel").setActive(mediaItem.id);
  $$("image_window").show();
}
/*
 * Retrieve cached image file path data.
 * See cacheImageFilePaths(media_file_list) function for cache creation.
 */
function getImageFilePathsFromCache() {
  return $("body").data("image file list");
}
/*
 * Save image file paths data in cache for later reuse via getImageFilePathsFromCache() function.
 */
function cacheImageFilePaths(media_file_list) {
  function img(obj) {
    return '
' + obj
      .name + '
';
  }
  console.log("This should be called only once.");
  var imageFilePaths = [];
  media_file_list.forEach(function(media_file) {
    if (media_file.type.toString().toLowerCase() == "photos") {
      imageFilePaths.push({
        id: media_file.id,
        css: "image",
        template: img,
        data: webix.copy({
          src: getMediaFilePath(media_file),
          title: media_file.name
        })
      });
    }
  });
  $("body").data("image file list", imageFilePaths);
}
var folderStack = [];

function renderMediaDynamic(mediaItem, title) {
  if (mediaItem.type == "directory") {
    var elementIcon;
    var element;
    elementIcon = document.getElementById(mediaItem.name + "Icon");
    var opened = false;
    for (var i = 0; i < folderStack.length; i++) {
      if ((folderStack[i].indexOf("/" + mediaItem.name + "/") > -1) || (folderStack[i].substring(folderStack[
          i].lastIndexOf("/") + 1) == mediaItem.name)) {
        element = document.getElementById(folderStack[i]);
        element.outerHTML = "";
        delete element;
        var elephant = document.getElementById(folderStack[i] + "bar");
        elephant.outerHTML = "";
        delete elephant;
        elementIcon.src = "img/folder.png";
        folderStack.splice(i, 1);
        i--;
        opened = true;
      }
    }
    if (!opened) {
      elementIcon.src = "img/openFolder.png";
      folderStack.push(elementIcon.parentElement.parentElement.id + "/" + mediaItem.name);
      addNavBar(elementIcon.parentElement.parentElement.id + "/" + mediaItem.name, elementIcon.parentElement.parentElement);
      getFilesInDir(mediaItem.contents, elementIcon.parentElement.parentElement.id + "/" + mediaItem.name);
      elementIcon.parentElement.parentElement.scrollIntoView();
    }
  } else {
    switch (getExt(mediaItem)) {
      case ".ogg":
      case ".mp3":
        renderAudio(mediaItem, title);
        break;
      case ".pdf":
        renderPdf(mediaItem, title);
        break;
      case ".webm":
      case ".mp4":
        renderVideo(mediaItem, title);
        break;
      case ".png":
      case ".jpg":
        renderPhoto(mediaItem, title);
        break;
      case ".txt":
        renderText(mediaItem, title);
        mediaSrc = "img/textFile.png";
        break;
        //case "tv":
        // break;
      default:
        mediaSrc = "img/unreadable.png";
        break;
    }
  }
}

function getCurrentDir(title) {
  return title.substring(title.lastIndexOf("/") + 1);
}

function addNavBar(name, parent) {
  if (name != "") {
    var nam = name + "bar";
    var nav = $("

", {
      "class": "",
      "id": nam,
    });
    var txt = $("", {});
    txt.html(getCurrentDir(name));
    txt.appendTo(nav);
    nav.appendTo("#navBar");
  } else {
    var nam = "Root" + "bar";
    var nav = $("

", {
      "class": "",
      "id": nam,
    });
    var txt = $("", {
      "href": "#" + ""
    });
    txt.html(getCurrentDir("Root"));
    txt.appendTo(nav);
    nav.appendTo("#navBar");
  }
  nav.on("click", function() {
    parent.scrollIntoView();
  });
}

function getFilesInDir(dir, title) {
  var mediaDirs = jsonResult;
  var currentDir = getCurrentDir(title);
  var directory = $("

", {
    "id": title,
    "class": "container"
  });
  directory.appendTo("#files_list");
  if (title != "") {
    var name = $("
" + currentDir + "
", {});
  } else {
    var name = $("
Root
", {});
  }
  name.appendTo(directory);
  $.each(dir, function(i, mediaItem) {
    var mediaSrc = getMediaFilePath(mediaItem, title);
    var divType = "img";
    var modalType = "";
    if (mediaItem.type == "directory") {
      mediaSrc = "img/folder.png";
    } else {
      switch (getExt(mediaItem)) {
        //   case "document":
        //  mediaSrc = mediaItem;
        //break;
        case ".ogg":
        case ".mp3":
          mediaSrc = "img/musicFile.png";
          modalType = "audio";
          break;
        case ".pdf":
          mediaSrc = "img/pdfFile.png";
          modalType = "pdf";
          break;
        case ".webm":
        case ".mp4":
              modalType = "video";
              divType = "img";
              mediaSrc = "img/videoFile.png";
          }
          break;
        case ".png":
        case ".jpg":
          modalType = "img";
          break;
        case ".txt":
          mediaSrc = "img/textFile.png";
          modalType = "pdf";
          break;
          //case "tv":
          // break;
        default:
          mediaSrc = "img/unreadable.png";
          break;
      }
    }
    var wrapper = $("

", {
      "class": "thumbContainer",
    });
    var image = $("<" + divType + "></" + divType + ">", {
      "id": mediaItem.name + "Icon",
      "class": "bubble_thumb",
      "data-toggle": "modal",
      "data-target": "#" + modalType + "_modal",
      "value": mediaItem,
      "src": mediaSrc
    });
    var lnk = $("", {
      "class": "fileName",
      "data-toggle": "modal",
      "data-target": "#" + modalType + "_modal",
      "value": mediaItem
    });
    lnk.html(mediaItem.name);
    lnk.on("click", function() {
      renderMediaDynamic(mediaItem, title);
    });
    image.html(mediaItem.name);
    image.on("click", function() {
      renderMediaDynamic(mediaItem, title);
    });
    // wrapper.append(image);
    //wrapper.append(lnk);
    wrapper.appendTo(directory);
    image.appendTo(wrapper);
    lnk.appendTo(wrapper);
  });
}
$.getJSON("data/media_files_list_v3.json", function(result) {
  jsonResult = result;
  var parent = document.getElementById("files_list");
  addNavBar("", parent);
  getFilesInDir(result, "");
}); // end of getJSON()
$("#audio_modal").on("hide.bs.modal", function(e) {
  $("#audio_elm")[0].pause();
});
$("#video_modal").on("hide.bs.modal", function(e) {
  $("#video_elm")[0].pause();
});<|endoftext|>


<commit_before>var React = require('react');
var Link = require('react-router').Link;

var SearchForm = React.createClass({

    componentDidMount: function() {
        this.refs.estateType.value = this.props.searchCriteria.estateType;
        this.refs.localisation.value = this.props.searchCriteria.localisation;
        this.refs.priceMin.value = this.props.searchCriteria.price.min;
        this.refs.priceMax.value = this.props.searchCriteria.price.max;
        this.refs.roomNbr.value = this.props.searchCriteria.roomNbr;
        this.refs.squareMin.value = this.props.searchCriteria.square.min;
        this.refs.squareMax.value = this.props.searchCriteria.square.max;
        this.refs.garage.value = this.props.searchCriteria.garage;
        this.refs.terrace.value = this.props.searchCriteria.terrace;
    },
    handleMoreCriteria: function() {
    },
    handleSaveSearch: function() {
      function cleanArray(actual) {
        var newArray = new Array();
        for (var i = 0; i < actual.length; i++) {
          if (actual[i]) {
            newArray.push(actual[i]);
          }
        }
        return newArray;
      }
      var estateType = [this.refs.house.checked?"house":undefined, this.refs.appart.checked?"appart":undefined,this.refs.ground.checked?"ground":undefined,this.refs.investment.checked?"investment":undefined,this.refs.commercial.checked?"commercial":undefined];
      estateType = cleanArray(estateType);
      var localisation = this.refs.localisation.value;
      var priceMin = this.refs.priceMin.value;
      var priceMax = this.refs.priceMax.value;
      var roomNbrMin = this.refs.roomNbrMin.value;
      var roomNbrMax = this.refs.roomNbrMax.value;
      // var squareMin = this.refs.squareMin.value;
      // var squareMax = this.refs.squareMax.value;
      // var garage = this.refs.garage.value;
      // var terrace = this.refs.terrace.value;

      var searchCriteria = {
          estateType: estateType,
          localisation: localisation,
          price: {
              min: priceMin,
              max: priceMax
          },
          roomNbr:  {
              min: roomNbrMin,
              max: roomNbrMax
          }
          // square: {
          //     min: '',
          //     max: ''
          // },
          // garage: squareMax,
          // terrace: terrace
      };

      this.props.onClickSearch(searchCriteria);
      alert("searchCriteria "+searchCriteria);
    },

    render: function() {
        return (

                <form className="form-horizontal" role="form">
                  Type de bien:

                    <input type="checkbox" name="house" ref="house" value="house"/>Maison

                    <input type="checkbox" name="appart" ref="appart" value="appart"/>Appartemment

                    <input type="checkbox" name="ground" ref="ground" value="ground"/>Terrain à batir

                    <input type="checkbox" name="investment" ref="investment" value="investment"/>Immeuble de rapport

                    <input type="checkbox" name="commercial" ref="commercial" value="commercial"/>Surface commerciale

                  Localisation:
                  <input type="text" name="localisation" className="form-control" ref="localisation" />
                  Prix: entre
                  <input type="text" name="priceMin" className="form-control" ref="priceMin" />
                  et<input type="text" name="priceMax" className="form-control" ref="priceMax" />
                  Nombre de chambres:

                      <input type="text" name="roomNbrMin" className="form-control" ref="roomNbrMin" />
                        à
                      <input type="text" name="roomNbrMax" className="form-control" ref="roomNbrMax" />

                    <input type="button" id="btnMore" className="btn btn-primary btn-sm" value="more" onClick={this.handleMoreCriteria}/>

                    <input type="button" id="btnSearch" className="btn btn-primary btn-sm pull-right" value="Search" onClick={this.handleSaveSearch}/>

                </form>

        );
    }
});

module.exports.SearchForm = SearchForm;
<commit_msg>searchForm<commit_after>var React = require('react');
var Link = require('react-router').Link;

var SearchForm = React.createClass({

    componentDidMount: function() {
        this.refs.estateType.value = this.props.searchCriteria.estateType;
        this.refs.localisation.value = this.props.searchCriteria.localisation;
        this.refs.priceMin.value = this.props.searchCriteria.price.min;
        this.refs.priceMax.value = this.props.searchCriteria.price.max;
        this.refs.roomNbr.value = this.props.searchCriteria.roomNbr;
        this.refs.squareMin.value = this.props.searchCriteria.square.min;
        this.refs.squareMax.value = this.props.searchCriteria.square.max;
        this.refs.garage.value = this.props.searchCriteria.garage;
        this.refs.terrace.value = this.props.searchCriteria.terrace;
    },
    handleMoreCriteria: function() {
    },
    handleSaveSearch: function() {
      function cleanArray(actual) {
        var newArray = new Array();
        for (var i = 0; i < actual.length; i++) {
          if (actual[i]) {
            newArray.push(actual[i]);
          }
        }
        return newArray;
      }
      var estateType = [this.refs.house.checked?"house":undefined, this.refs.appart.checked?"appart":undefined,this.refs.ground.checked?"ground":undefined,this.refs.investment.checked?"investment":undefined,this.refs.commercial.checked?"commercial":undefined];
      estateType = cleanArray(estateType);
      var localisation = this.refs.localisation.value;
      var priceMin = this.refs.priceMin.value;
      var priceMax = this.refs.priceMax.value;
      var roomNbrMin = this.refs.roomNbrMin.value;
      var roomNbrMax = this.refs.roomNbrMax.value;
      // var squareMin = this.refs.squareMin.value;
      // var squareMax = this.refs.squareMax.value;
      // var garage = this.refs.garage.value;
      // var terrace = this.refs.terrace.value;

      var searchCriteria = {
          estateType: estateType,
          localisation: localisation,
          price: {
              min: priceMin,
              max: priceMax
          },
          roomNbr:  {
              min: roomNbrMin,
              max: roomNbrMax
          }
          // square: {
          //     min: '',
          //     max: ''
          // },
          // garage: squareMax,
          // terrace: terrace
      };

      this.props.onClickSearch(searchCriteria);
    },

    render: function() {
        return (

                <form className="form-horizontal" role="form">
                  Type de bien:

                    <input type="checkbox" name="house" ref="house" value="house"/>Maison

                    <input type="checkbox" name="appart" ref="appart" value="appart"/>Appartemment

                    <input type="checkbox" name="ground" ref="ground" value="ground"/>Terrain à batir

                    <input type="checkbox" name="investment" ref="investment" value="investment"/>Immeuble de rapport

                    <input type="checkbox" name="commercial" ref="commercial" value="commercial"/>Surface commerciale

                  Localisation:
                  <input type="text" name="localisation" className="form-control" ref="localisation" />
                  Prix: entre
                  <input type="text" name="priceMin" className="form-control" ref="priceMin" />
                  et<input type="text" name="priceMax" className="form-control" ref="priceMax" />
                  Nombre de chambres:

                      <input type="text" name="roomNbrMin" className="form-control" ref="roomNbrMin" />
                        à
                      <input type="text" name="roomNbrMax" className="form-control" ref="roomNbrMax" />

                    <input type="button" id="btnMore" className="btn btn-primary btn-sm" value="more" onClick={this.handleMoreCriteria}/>

                    <input type="button" id="btnSearch" className="btn btn-primary btn-sm pull-right" value="Search" onClick={this.handleSaveSearch}/>

                </form>

        );
    }
});

module.exports.SearchForm = SearchForm;
<|endoftext|>


<commit_before>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
            $('#container').removeClass('container');
            $('#container').css('margin', '20px');
            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);

                            });
                        },
                    });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).attr('checked'));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).attr('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).attr('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).attr('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).attr('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).attr('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).attr('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).attr('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).attr('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).attr('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).attr('checked'));
        });
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });

        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked == 'checked')
            totalChecked++;
        else
            totalChecked--;

        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                selfObj.initDataTable();
                selfObj.bindEvents();
				$('.dropdown-toggle').bind('click',function(){
					$(this).next().slideToggle();
				});
            }

        });
    }
    var customFieldName = 'All';
    var customColumnName = 'all';
    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {
        $('#addKeyword').click(function () {
            if ($('#keywordSearch').val() != '') {
                if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                    Filters = JSON.parse($('#facet_keyword_search').val());
                }
                else {
                    Filters = new Array();
                }
                for (x in Filters) {
                    if (Filters[x].value == $('#keywordSearch').val()) {
                        alert($('#keywordSearch').val() + " filter is already applied.");
                        return false;
                    }
                }
                var temp = {};
                temp.value = $('#keywordSearch').val();
                temp.type = customColumnName;
                Filters.push(temp);

                $('#facet_keyword_search').val(JSON.stringify(Filters));

                filterRecords();
            }
        });
    }
}

<commit_msg>worked on the facet<commit_after>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
            $('#container').removeClass('container');
            $('#container').css('margin', '20px');
            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);

                            });
                        },
                    });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).attr('checked'));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).attr('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).attr('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).attr('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).attr('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).attr('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).attr('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).attr('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).attr('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).attr('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).attr('checked'));
        });
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });

        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked == 'checked')
            totalChecked++;
        else
            totalChecked--;

        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                selfObj.initDataTable();
                selfObj.bindEvents();
				$('.dropdown-toggle-custom').bind('click',function(){
					$(this).next().slideToggle();
				});
            }

        });
    }
    var customFieldName = 'All';
    var customColumnName = 'all';
    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {
        $('#addKeyword').click(function () {
            if ($('#keywordSearch').val() != '') {
                if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                    Filters = JSON.parse($('#facet_keyword_search').val());
                }
                else {
                    Filters = new Array();
                }
                for (x in Filters) {
                    if (Filters[x].value == $('#keywordSearch').val()) {
                        alert($('#keywordSearch').val() + " filter is already applied.");
                        return false;
                    }
                }
                var temp = {};
                temp.value = $('#keywordSearch').val();
                temp.type = customColumnName;
                Filters.push(temp);

                $('#facet_keyword_search').val(JSON.stringify(Filters));

                filterRecords();
            }
        });
    }
}

<|endoftext|>


<commit_before>import React from 'react'
import Dropdown from './dropdown.js'
import Navbar from './navbar.js'
import CollectionsBox from './collections-box.js'
import Search from './search.js'

const sizeOptions = [10, 50, 200, 1000]
const SEARCH_GUIDE = 'https://github.com/hoover/search/wiki/Guide-to-search-terms'

export const SORT_RELEVANCE = 'Relevance'
export const SORT_NEWEST = 'Newest'
export const SORT_OLDEST = 'Oldest'
export const SORT_OPTIONS = [SORT_RELEVANCE, SORT_NEWEST, SORT_OLDEST]

class SearchPage extends React.Component {

  parseQuery(url) {
    var rv = {}
    if (url.indexOf('?') > -1) {
      url.match(/\?(.*)/)[1].split('&').forEach(function (pair) {
        var kv = pair.split('=').map(decodeURIComponent)
        var k = kv[0], v = kv[1]
        if (!rv[k]) {
          rv[k] = []
        }
        rv[k].push(v)
      })
    }
    return rv
  }

  constructor(props) {
    super(props)
    var args = this.parseQuery(window.location.href)
    this.state = {
      q: args.q ? ("" + args.q).replace(/\+/g, ' ') : "",
      size: args.size ? +args.size : 10,
      order: args.order ? args.order[0] : SORT_OPTIONS[0],
      args: args,
      collections: [],
      selectedCollections: [],
      query: null,
      page: '',
    }
  }

  componentDidMount() {
    this.getCollections()
  }

  getCollections() {
    $.get('/collections', function (resp) {
      var collections = resp
      var selectedCollections = null
      var query = null
      var args = this.state.args
      if (args.collections) {
        var sel = '' + args.collections
        selectedCollections = sel ? sel.split('+') : []
      }
      else {
        selectedCollections = resp.map(function (c) {
          return c.name
        })
      }

      if (this.state.q) {
        query = {
          q: this.state.q,
          collections: selectedCollections,
          page: args.p ? +args.p : 1,
          size: this.state.size,
          order: this.state.order,
        }
      }

      this.setState({
        collections,
        selectedCollections,
        query,
      })
    }.bind(this))
  }

  render() {
    let refreshForm = () => { this.refs.form.submit() }
    return (
      <form id="search-form" ref="form">

Hoover

              <input name="q" defaultValue={this.state.q}
                   type="search"
                   className="form-control"
                   placeholder="Search..."/>

                Refine your search using this handy{' '}
                guide.

                <Dropdown
                  name="size"
                  label="Results per page"
                  values={sizeOptions}
                  value={this.state.size}
                  onChanged={refreshForm}
                  />

{' '}

                <Dropdown
                  name="order"
                  label="Sort by"
                  values={SORT_OPTIONS}
                  value={this.state.order}
                  onChanged={refreshForm}
                />

{' '}
              <button type="submit">search</button>

            <Navbar />

          <CollectionsBox
            collections={this.state.collections}
            selected={this.state.selectedCollections}
            onChanged={(selected) => this.setState({selectedCollections: selected})} />
          <Search
            query={this.state.query}
            collections={this.state.selectedCollections} />

      </form>
    )
  }
}

export default SearchPage
<commit_msg>fix indentation<commit_after>import React from 'react'
import Dropdown from './dropdown.js'
import Navbar from './navbar.js'
import CollectionsBox from './collections-box.js'
import Search from './search.js'

const sizeOptions = [10, 50, 200, 1000]
const SEARCH_GUIDE = 'https://github.com/hoover/search/wiki/Guide-to-search-terms'

export const SORT_RELEVANCE = 'Relevance'
export const SORT_NEWEST = 'Newest'
export const SORT_OLDEST = 'Oldest'
export const SORT_OPTIONS = [SORT_RELEVANCE, SORT_NEWEST, SORT_OLDEST]

class SearchPage extends React.Component {

  parseQuery(url) {
    var rv = {}
    if (url.indexOf('?') > -1) {
      url.match(/\?(.*)/)[1].split('&').forEach(function (pair) {
        var kv = pair.split('=').map(decodeURIComponent)
        var k = kv[0], v = kv[1]
        if (!rv[k]) {
          rv[k] = []
        }
        rv[k].push(v)
      })
    }
    return rv
  }

  constructor(props) {
    super(props)
    var args = this.parseQuery(window.location.href)
    this.state = {
      q: args.q ? ("" + args.q).replace(/\+/g, ' ') : "",
      size: args.size ? +args.size : 10,
      order: args.order ? args.order[0] : SORT_OPTIONS[0],
      args: args,
      collections: [],
      selectedCollections: [],
      query: null,
      page: '',
    }
  }

  componentDidMount() {
    this.getCollections()
  }

  getCollections() {
    $.get('/collections', function (resp) {
      var collections = resp
      var selectedCollections = null
      var query = null
      var args = this.state.args
      if (args.collections) {
        var sel = '' + args.collections
        selectedCollections = sel ? sel.split('+') : []
      }
      else {
        selectedCollections = resp.map(function (c) {
          return c.name
        })
      }

      if (this.state.q) {
        query = {
          q: this.state.q,
          collections: selectedCollections,
          page: args.p ? +args.p : 1,
          size: this.state.size,
          order: this.state.order,
        }
      }

      this.setState({
        collections,
        selectedCollections,
        query,
      })
    }.bind(this))
  }

  render() {
    let refreshForm = () => { this.refs.form.submit() }
    return (
      <form id="search-form" ref="form">

Hoover

              <input
                name="q"
                defaultValue={this.state.q}
                type="search"
                className="form-control"
                placeholder="Search..."
                />

                Refine your search using this handy{' '}
                guide.

                <Dropdown
                  name="size"
                  label="Results per page"
                  values={sizeOptions}
                  value={this.state.size}
                  onChanged={refreshForm}
                  />

{' '}

                <Dropdown
                  name="order"
                  label="Sort by"
                  values={SORT_OPTIONS}
                  value={this.state.order}
                  onChanged={refreshForm}
                />

{' '}
              <button type="submit">search</button>

            <Navbar />

          <CollectionsBox
            collections={this.state.collections}
            selected={this.state.selectedCollections}
            onChanged={(selected) => this.setState({selectedCollections: selected})} />
          <Search
            query={this.state.query}
            collections={this.state.selectedCollections} />

      </form>
    )
  }
}

export default SearchPage
<|endoftext|>


<commit_before>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    var customFieldName = 'All';
    var customColumnName = 'all';
    var ajaxSaveStateUrl = null;
    var selectAllRecords = false;
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the ajax URL for selected rows of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSaveStateUrl = function (source) {
        ajaxSaveStateUrl = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
//			$('#container').removeClass('container');
//			$('#container').css('margin', '20px');
            var selected = [];
            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);
                                console.log(json);
                            });
                        },
                        "createdRow": function (row, data, index) {
                            var input = $(row).find("td:first").html();
                            row.id = "row-" + $(input).attr('value');
                        },
                        "ajax": ajaxSaveStateUrl,
                        "rowCallback": function (row, data) {
                            if ($.inArray(row.id, selected) !== -1) {
                                $(row).addClass('selected');
                                $(selected).each(function (key, value) {
                                    var input = $("#" + value + " td:first").html();
                                    $("#" + $(input).attr('id')).attr("checked", "checked");
                                    $("#" + $(input).attr('id')).prop("checked", true);
                                });
                            }
                        }
                    });
            $('#records tbody').on('click', 'tr', function () {
                var id = this.id;
                var index = $.inArray(id, selected);
                if (index === -1) {
                    selected.push(id);
                } else {
                    selected.splice(index, 1);
                }
                $(this).toggleClass('selected', function () {
                    var input = $("#" + id + " td:first").html();
                    if ($(this).hasClass('selected') === true) {
                        $("#" + $(input).attr('id')).attr("checked", "checked");
                        $("#" + $(input).attr('id')).prop("checked", true);
                    } else {
                        $("#" + $(input).attr('id')).removeAttr("checked");
                    }
                    selfObj.saveState($(input).attr('value'));
                });

            });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        selfObj.isAnySearch();
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).prop("checked"));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).prop('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).prop('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).prop('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).prop('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).prop('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).prop('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).prop('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).prop('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).prop('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).prop('checked'));
        });
        initTriStateCheckBox('is_review_check', 'is_review_check_state', true);
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });
        $('#reset_all').click(function () {
            selfObj.resetAll();
        });

        selfObj.addCustomToken();
        $('#addKeyword').click(function () {
            selfObj.addKeyword();
        });
        $('#keywordSearch').keypress(function (e) {
            if (e.which == 13) {
                selfObj.addKeyword();
            }
        });

        selfObj.removeFilter();
        selfObj.removeKeywordFilter();
        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked)
            totalChecked++;
        else
            totalChecked--;
        if (totalChecked < 0)
            totalChecked = 0;
        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.blockUI({
            message: 'Please wait...',
            css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff',
                zIndex: 999999
            }
        });
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                var source = $('#metro-js').attr('src');
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = source;
                script.id = "metro-js";
                $("#recordsContainer").append(script);
                selfObj.initDataTable();
                selfObj.bindEvents();
                $('body').scrollTop(0);
                $.unblockUI();
            }

        });
    }

    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {
        if ($('#keywordSearch').val() != '') {
            if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                Filters = JSON.parse($('#facet_keyword_search').val());
            }
            else {
                Filters = new Array();
            }
            for (x in Filters) {
                if (Filters[x].value == $('#keywordSearch').val()) {
                    alert($('#keywordSearch').val() + " filter is already applied.");
                    return false;
                }
            }
            var temp = {};
            temp.value = $('#keywordSearch').val();
            temp.type = customColumnName;
            Filters.push(temp);

            $('#facet_keyword_search').val(JSON.stringify(Filters));
            customFieldName = 'All';
            customColumnName = 'all';
            filterRecords();
        }
    }

    this.removeFilter = function () {
        $('.delFilter').click(function () {
            elementID = $(this).attr('data-elementId');
            type = $(this).attr('data-type');
            $('#' + elementID).prop('checked', false);
            checkParentFacet(type);
        });
    }
    this.removeKeywordFilter = function () {
        $('.deleteKeyword').click(function () {
            var index = $.trim($(this).data().index);
            Filters = JSON.parse($('#facet_keyword_search').val());
            delete (Filters[index]);
            Filters.splice(index, 1);
            $('#facet_keyword_search').val(JSON.stringify(Filters));
            filterRecords();
        });

    }
    this.resetAll = function () {
        $('#formSearch').find('input:hidden, input:text, select').val('');
        $('#formSearch').find('input:radio, input:checkbox')
                .removeAttr('checked').removeAttr('selected');
        filterRecords();
    }
    this.isAnySearch = function () {
        if ($('.search_keys').length > 0) {
            $('#reset_all').show();
        }
        else {
            $('#reset_all').hide();

        }

    }
    this.selectAllRecords = function () {
        $('#selectAll').click(function () {
            if($(this).prop('checked') == true){
                selectAllRecords = true;
               $('input[name=record_checkbox]').attr('checked', 'checked');
               $('input[name=record_checkbox]').prop('checked',true);
            }else if($(this).prop('checked') == false){
                selectAllRecords = false;
               $('input[name=record_checkbox]').removeAttr('checked');
               $('input[name=record_checkbox]').prop('checked',false);
            }
            selfObj.saveState(0, '', 1);
        });
    }

    this.saveState = function (elementID, select, isChecked) {
        var id = '';
        var checked = 0;
        var isAll = 0;
        if (select) {
            if (select == 'all') {
                checked = isChecked;
                isAll = 1;
            }
            else {
                checked = isChecked;
                $('input[name=record_checkbox]').each(function () {
                    id += $(this).val() + ',';
                });
            }
        }
        else {
            id = elementID;
            if ($('#row_' + elementID).attr('checked'))
                checked = 1;
        }

        $.ajax({
            type: 'POST',
            url: ajaxSaveStateUrl,
            data: {id: id, checked: checked, is_all: isAll, },
            dataType: 'json',
            success: function (response)
            {

            }
        });
    }
}

<commit_msg>records selections<commit_after>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    var customFieldName = 'All';
    var customColumnName = 'all';
    var ajaxSaveStateUrl = null;
    var selectAllRecords = false;
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the ajax URL for selected rows of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSaveStateUrl = function (source) {
        ajaxSaveStateUrl = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
//			$('#container').removeClass('container');
//			$('#container').css('margin', '20px');
            var selected = [];
            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);
                                console.log(json.iTotalDisplayRecords);
                            });
                        },
                        "createdRow": function (row, data, index) {
                            var input = $(row).find("td:first").html();
                            row.id = "row-" + $(input).attr('value');
                        },
                        "ajax": ajaxSaveStateUrl,
                        "rowCallback": function (row, data) {
                            if ($.inArray(row.id, selected) !== -1) {
                                $(row).addClass('selected');
                                $(selected).each(function (key, value) {
                                    var input = $("#" + value + " td:first").html();
                                    $("#" + $(input).attr('id')).attr("checked", "checked");
                                    $("#" + $(input).attr('id')).prop("checked", true);
                                });
                            }
                        }
                    });
            $('#records tbody').on('click', 'tr', function () {
                var id = this.id;
                var index = $.inArray(id, selected);
                if (index === -1) {
                    selected.push(id);
                } else {
                    selected.splice(index, 1);
                }
                $(this).toggleClass('selected', function () {
                    var input = $("#" + id + " td:first").html();
                    if ($(this).hasClass('selected') === true) {
                        $("#" + $(input).attr('id')).attr("checked", "checked");
                        $("#" + $(input).attr('id')).prop("checked", true);
                    } else {
                        $("#" + $(input).attr('id')).removeAttr("checked");
                    }
                    selfObj.saveState($(input).attr('value'));
                });

            });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        selfObj.isAnySearch();
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).prop("checked"));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).prop('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).prop('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).prop('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).prop('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).prop('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).prop('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).prop('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).prop('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).prop('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).prop('checked'));
        });
        initTriStateCheckBox('is_review_check', 'is_review_check_state', true);
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });
        $('#reset_all').click(function () {
            selfObj.resetAll();
        });

        selfObj.addCustomToken();
        $('#addKeyword').click(function () {
            selfObj.addKeyword();
        });
        $('#keywordSearch').keypress(function (e) {
            if (e.which == 13) {
                selfObj.addKeyword();
            }
        });

        selfObj.removeFilter();
        selfObj.removeKeywordFilter();
        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked)
            totalChecked++;
        else
            totalChecked--;
        if (totalChecked < 0)
            totalChecked = 0;
        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.blockUI({
            message: 'Please wait...',
            css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff',
                zIndex: 999999
            }
        });
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                var source = $('#metro-js').attr('src');
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = source;
                script.id = "metro-js";
                $("#recordsContainer").append(script);
                selfObj.initDataTable();
                selfObj.bindEvents();
                $('body').scrollTop(0);
                $.unblockUI();
            }

        });
    }

    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {
        if ($('#keywordSearch').val() != '') {
            if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                Filters = JSON.parse($('#facet_keyword_search').val());
            }
            else {
                Filters = new Array();
            }
            for (x in Filters) {
                if (Filters[x].value == $('#keywordSearch').val()) {
                    alert($('#keywordSearch').val() + " filter is already applied.");
                    return false;
                }
            }
            var temp = {};
            temp.value = $('#keywordSearch').val();
            temp.type = customColumnName;
            Filters.push(temp);

            $('#facet_keyword_search').val(JSON.stringify(Filters));
            customFieldName = 'All';
            customColumnName = 'all';
            filterRecords();
        }
    }

    this.removeFilter = function () {
        $('.delFilter').click(function () {
            elementID = $(this).attr('data-elementId');
            type = $(this).attr('data-type');
            $('#' + elementID).prop('checked', false);
            checkParentFacet(type);
        });
    }
    this.removeKeywordFilter = function () {
        $('.deleteKeyword').click(function () {
            var index = $.trim($(this).data().index);
            Filters = JSON.parse($('#facet_keyword_search').val());
            delete (Filters[index]);
            Filters.splice(index, 1);
            $('#facet_keyword_search').val(JSON.stringify(Filters));
            filterRecords();
        });

    }
    this.resetAll = function () {
        $('#formSearch').find('input:hidden, input:text, select').val('');
        $('#formSearch').find('input:radio, input:checkbox')
                .removeAttr('checked').removeAttr('selected');
        filterRecords();
    }
    this.isAnySearch = function () {
        if ($('.search_keys').length > 0) {
            $('#reset_all').show();
        }
        else {
            $('#reset_all').hide();

        }

    }
    this.selectAllRecords = function () {
        $('#selectAll').click(function () {
            if($(this).prop('checked') == true){
                selectAllRecords = true;
               $('input[name=record_checkbox]').attr('checked', 'checked');
               $('input[name=record_checkbox]').prop('checked',true);
            }else if($(this).prop('checked') == false){
                selectAllRecords = false;
               $('input[name=record_checkbox]').removeAttr('checked');
               $('input[name=record_checkbox]').prop('checked',false);
            }
            selfObj.saveState(0, '', 1);
        });
    }

    this.saveState = function (elementID, select, isChecked) {
        var id = '';
        var checked = 0;
        var isAll = 0;
        if (select) {
            if (select == 'all') {
                checked = isChecked;
                isAll = 1;
            }
            else {
                checked = isChecked;
                $('input[name=record_checkbox]').each(function () {
                    id += $(this).val() + ',';
                });
            }
        }
        else {
            id = elementID;
            if ($('#row_' + elementID).attr('checked'))
                checked = 1;
        }

        $.ajax({
            type: 'POST',
            url: ajaxSaveStateUrl,
            data: {id: id, checked: checked, is_all: isAll, },
            dataType: 'json',
            success: function (response)
            {

            }
        });
    }
}

<|endoftext|>


<commit_before>// @copyright: 2013 Single D Software - All Rights Reserved
// @summary: JavaScript logic for the Light Maestro GUI

'use strict';

function selectFixtures() {
    var type = $(this).html();
    var whitesChecked = type == 'All' || type == 'Whites';
    var colorsChecked = type == 'All' || type == 'Colors';
    $('input[class="fixture-white"]').prop('checked', whitesChecked);
    $('input[class="fixture-color"]').prop('checked', colorsChecked);
    $('input[type="checkbox"]').checkboxradio('refresh');
}

function changeValues(event) {
    var alpha = parseFloat($('#value-alpha').val());
    var red = parseFloat($('#value-red').val());
    var green = parseFloat($('#value-green').val());
    var blue = parseFloat($('#value-blue').val());
    var channels = {}
    $('input[type="checkbox"]').each( function() {
        if($(this).prop('checked')) {
           var id = parseInt($(this).attr('id').split('-')[1]);
           channels[id + 0] = alpha;
           channels[id + 1] = red;
           channels[id + 2] = green;
           channels[id + 3] = blue;
       }
    });
    $.ajax({data: JSON.stringify({'channels': channels})});
}

// Things to do before the page is shown.
$(document).bind('pagebeforeshow', function() {

    // Set up AJAX calls.
    $.ajaxSetup({method: 'POST', url: '/channels/_load', headers: {'content-type': 'application/json'}});

    // Disable any ability to select text in the GUI.
    $('body').bind('selectstart',function() {
        return false;
    });

    // Bind the select fixture function to selection buttons.
    $('button').bind('tap', selectFixtures);

    // Bind the change value function to the sliders (TODO make this one call).
    $('#value-alpha').bind('change', changeValues);
    $('#value-red').bind('change', changeValues);
    $('#value-green').bind('change', changeValues);
    $('#value-blue').bind('change', changeValues);

});

<commit_msg>Add some todo notes.<commit_after>// @copyright: 2013 Single D Software - All Rights Reserved
// @summary: JavaScript logic for the Light Maestro GUI

'use strict';

// TODO comments
// TODO read channel values when picking individual fixture
// TODO arrange banks
// TODO add "select all in bank" button? perhaps with double tap or long-press?

function selectFixtures() {
    var type = $(this).html();
    var whitesChecked = type == 'All' || type == 'Whites';
    var colorsChecked = type == 'All' || type == 'Colors';
    $('input[class="fixture-white"]').prop('checked', whitesChecked);
    $('input[class="fixture-color"]').prop('checked', colorsChecked);
    $('input[type="checkbox"]').checkboxradio('refresh');
}

function changeValues(event) {
    var alpha = parseFloat($('#value-alpha').val());
    var red = parseFloat($('#value-red').val());
    var green = parseFloat($('#value-green').val());
    var blue = parseFloat($('#value-blue').val());
    var channels = {}
    $('input[type="checkbox"]').each( function() {
        if($(this).prop('checked')) {
           var id = parseInt($(this).attr('id').split('-')[1]);
           channels[id + 0] = alpha;
           channels[id + 1] = red;
           channels[id + 2] = green;
           channels[id + 3] = blue;
       }
    });
    $.ajax({data: JSON.stringify({'channels': channels})});
}

// Things to do before the page is shown.
$(document).bind('pagebeforeshow', function() {

    // Set up AJAX calls.
    $.ajaxSetup({method: 'POST', url: '/channels/_load', headers: {'content-type': 'application/json'}});

    // Disable any ability to select text in the GUI.
    $('body').bind('selectstart',function() {
        return false;
    });

    // Bind the select fixture function to selection buttons.
    $('button').bind('tap', selectFixtures);

    // Bind the change value function to the sliders (TODO make this one call).
    $('#value-alpha').bind('change', changeValues);
    $('#value-red').bind('change', changeValues);
    $('#value-green').bind('change', changeValues);
    $('#value-blue').bind('change', changeValues);

});

<|endoftext|>


<commit_before>var __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

SimpleSchema.debug = true; // TODO Remove after launch

if(!this.Schema){
  Schema = {};
};

var analyticsSchema = new SimpleSchema({
  byConnection: {
    type: Number,
    defaultValue: 0
  },
  byIP: {
    type: Number,
    defaultValue: 0
  },
  byId: {
    type: Number,
    defaultValue: 0
  },
  total: {
    type: Number,
    defaultValue: 0
  }
});

this.StoryStats = new Mongo.Collection("story_stats");

this.StoryStats.deny({
  insert: function() {
    return true;
  },
  update: function() {
    return true
  },
  remove: function() {
    return true
  }
});

var deepAnalyticsSchema = new SimpleSchema({
  uniqueViewersByConnection: {
    type: [String],
    defaultValue: []
  },
  uniqueViewersByIP: {
    type: [String],
    defaultValue: []
  },
  uniqueViewersByUserId: {
    type: [String],
    defaultValue: []
  },
  all: {
    type: [Object],
    blackbox: true
  }
});

Schema.StoryStats = new SimpleSchema({
  storyId: {
    type: String
  },
  deepAnalytics: {
    type: Object,
    optional: true
  },
  'deepAnalytics.views': {
    type: deepAnalyticsSchema
  },
  'deepAnalytics.shares': {
    type: deepAnalyticsSchema
  },
  analytics: {
    type: analyticsSchema,
    optional: true
  },
  'analytics.views': {
    type: analyticsSchema
  },
  'analytics.shares': {
    type: analyticsSchema
  }
});

this.StoryStats.attachSchema(Schema.StoryStats);

this.StoryHistories = new Mongo.Collection("story_histories");

this.Deepstreams = new Mongo.Collection("deepstreams", {
  transform: function(doc) {
    return new Deepstream(doc);
  }
});

this.Deepstreams.allow({
  insert: function () {
    return true;
  },
  update: function () {
    return true
  },
  remove: function () {
    return true;
  }
});

ContextBlocks = new Mongo.Collection("context_blocks", {
  transform: newTypeSpecificContextBlock
});

if(!this.Schema){
  Schema = {};
}

Schema.ContextReferenceProfile = new SimpleSchema({
  id: {
    type: String,
    optional: true
  },

  creationDate: {
    type: String,
    optional: true
  },

  username: {
    type: String,
    optional: true
  },

  userId: {
    type: String,
    optional: true
  },

  source: {
    type: String,
    optional: true
  },

  artworkUrl: {
    type: String,
    optional: true
  },

  previewImage: {
    type: String,
    optional: true
  },

  title: {
    type: String,
    optional: true,
    defaultValue: ''
  },

  description: {
    type: String,
    optional: true,
    defaultValue: ''
  },
  fileExtension: {
    type: String,
    optional: true
  },

  // Image

  flickrFarm: {
    type: String,
    optional: true
  },
  flickrSecret: {
    type: String,
    optional: true
  },
  flickrServer: {
    type: String,
    optional: true
  },
  uploadDate: {
    type: Date,
    optional: true
  },
  ownerName: {
    type: String,
    optional: true
  },

  hasWebM: {
    type: Boolean,
    optional: true
  },

  hasMP4: {
    type: Boolean,
    optional: true
  },

  // Image upload, Imgur
  width: {
    type: Number,
    optional: true
  },
  height: {
    type: Number,
    optional: true
  },

  // twitter
  retweet: {
    type: String,
    optional: true
  },
  creationDate: {
    type: String,
    optional: true
  },
  username: {
    type: String,
    optional: true
  },
  screenname: {
    type: String,
    optional: true
  },
  userId: {
    type: String,
    optional: true
  },
  userPic: {
    type: String,
    optional: true
  },
  text: {
    type: String,
    optional: true
  },
  entities: {
    type: Object,
    optional: true,
    blackbox: true
  },
  extendedEntities: {
    type: Object,
    optional: true,
    blackbox: true
  },
  retweetedStatus: {
    type: Object,
    optional: true,
    blackbox: true
  },

  // Link
  title: { type: String, optional: true },
  thumbnailUrl: { type: String, optional: true },
  url: { type: String, optional: true },
  originalUrl: { type: String, optional: true },
  providerName: { type: String, optional: true },
  providerUrl: { type: String, optional: true },
  authorUrl: { type: String, optional: true },
  authorName: { type: String, optional: true },
  thumbnailHeight: { type: Number, optional: true },
  thumbnailWidth: { type: Number, optional: true },
  embedlyType: { type: String, optional: true },
  imageOnLeft: { type: Boolean, optional: true },

  // Rich or Extract
  html: { type: String, optional: true },

  // Map

  mapQuery: {
    type: String,
    optional: true
  },
  mapType: {
    type: String,
    allowedValues: ['roadmap', 'satellite'],
    defaultValue: 'satellite',
    optional: true,
    autoform: {
      afFieldInput: {
        firstOption: false,
        options: 'allowed'
      }
    }
  }

});

Schema.ContextBlocks = new SimpleSchema({
  streamShortId: {
    type: String
  },
  authorId: {
    type: String
  },
  type: {
    type: String
  },
  source: {
    type: String,
    optional: true
  },
  fromEmbedly: {
    type: Boolean,
    optional: true
  },
  version: {
    type: String,
    optional: true
  },
  rank: {
    type: Number,
    optional: true
  },
  savedAt: {
    type: Date,
    optional: true
  },
  publishedAt: {
    type: Date,
    optional: true
  },
  createdAt: {
    type: Date,
    autoValue: function() {
      if (this.isInsert) {
        return new Date;
      } else if (this.isUpsert) {
        return {$setOnInsert: new Date};
      } else {
        this.unset();
      }
    },
    optional: true // optional because only added this fieldjust before launch
  },
  fullDetails: {
    type: Object,
    optional: true,
    blackbox: true
  },
  description: {
    type: String,
    optional: true
  },
  content: {
    type: String,
    trim: false,
    optional: true
  },
  published: {
    type: Boolean,
    defaultValue: false
  },
  everPublished: {
    type: Boolean,
    defaultValue: false
  },
  reference: {
    type: Schema.ContextReferenceProfile,
    optional: true
  },

  searchQuery: {
    type:String,
    optional:true
  },
  searchOption: {
    type: String,
    optional:true
  }
});

ContextBlocks.attachSchema(Schema.ContextBlocks);

this.ContextBlocks.deny({
  insert: function() {
    return true;
  },
  update: function() {
    return true
  },
  remove: function() {
    return true
  }
});

this.Streams = new Mongo.Collection("streams", {
  transform: function(doc) {
    return new Stream(doc);
  }
});
<commit_msg>stream transform meant that bambuser results weren't getting returned in methods<commit_after>var __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

SimpleSchema.debug = true; // TODO Remove after launch

if(!this.Schema){
  Schema = {};
};

var analyticsSchema = new SimpleSchema({
  byConnection: {
    type: Number,
    defaultValue: 0
  },
  byIP: {
    type: Number,
    defaultValue: 0
  },
  byId: {
    type: Number,
    defaultValue: 0
  },
  total: {
    type: Number,
    defaultValue: 0
  }
});

this.StoryStats = new Mongo.Collection("story_stats");

this.StoryStats.deny({
  insert: function() {
    return true;
  },
  update: function() {
    return true
  },
  remove: function() {
    return true
  }
});

var deepAnalyticsSchema = new SimpleSchema({
  uniqueViewersByConnection: {
    type: [String],
    defaultValue: []
  },
  uniqueViewersByIP: {
    type: [String],
    defaultValue: []
  },
  uniqueViewersByUserId: {
    type: [String],
    defaultValue: []
  },
  all: {
    type: [Object],
    blackbox: true
  }
});

Schema.StoryStats = new SimpleSchema({
  storyId: {
    type: String
  },
  deepAnalytics: {
    type: Object,
    optional: true
  },
  'deepAnalytics.views': {
    type: deepAnalyticsSchema
  },
  'deepAnalytics.shares': {
    type: deepAnalyticsSchema
  },
  analytics: {
    type: analyticsSchema,
    optional: true
  },
  'analytics.views': {
    type: analyticsSchema
  },
  'analytics.shares': {
    type: analyticsSchema
  }
});

this.StoryStats.attachSchema(Schema.StoryStats);

this.StoryHistories = new Mongo.Collection("story_histories");

this.Deepstreams = new Mongo.Collection("deepstreams", {
  transform: function(doc) {
    return new Deepstream(doc);
  }
});

this.Deepstreams.allow({
  insert: function () {
    return true;
  },
  update: function () {
    return true
  },
  remove: function () {
    return true;
  }
});

ContextBlocks = new Mongo.Collection("context_blocks", {
  transform: newTypeSpecificContextBlock
});

if(!this.Schema){
  Schema = {};
}

Schema.ContextReferenceProfile = new SimpleSchema({
  id: {
    type: String,
    optional: true
  },

  creationDate: {
    type: String,
    optional: true
  },

  username: {
    type: String,
    optional: true
  },

  userId: {
    type: String,
    optional: true
  },

  source: {
    type: String,
    optional: true
  },

  artworkUrl: {
    type: String,
    optional: true
  },

  previewImage: {
    type: String,
    optional: true
  },

  title: {
    type: String,
    optional: true,
    defaultValue: ''
  },

  description: {
    type: String,
    optional: true,
    defaultValue: ''
  },
  fileExtension: {
    type: String,
    optional: true
  },

  // Image

  flickrFarm: {
    type: String,
    optional: true
  },
  flickrSecret: {
    type: String,
    optional: true
  },
  flickrServer: {
    type: String,
    optional: true
  },
  uploadDate: {
    type: Date,
    optional: true
  },
  ownerName: {
    type: String,
    optional: true
  },

  hasWebM: {
    type: Boolean,
    optional: true
  },

  hasMP4: {
    type: Boolean,
    optional: true
  },

  // Image upload, Imgur
  width: {
    type: Number,
    optional: true
  },
  height: {
    type: Number,
    optional: true
  },

  // twitter
  retweet: {
    type: String,
    optional: true
  },
  creationDate: {
    type: String,
    optional: true
  },
  username: {
    type: String,
    optional: true
  },
  screenname: {
    type: String,
    optional: true
  },
  userId: {
    type: String,
    optional: true
  },
  userPic: {
    type: String,
    optional: true
  },
  text: {
    type: String,
    optional: true
  },
  entities: {
    type: Object,
    optional: true,
    blackbox: true
  },
  extendedEntities: {
    type: Object,
    optional: true,
    blackbox: true
  },
  retweetedStatus: {
    type: Object,
    optional: true,
    blackbox: true
  },

  // Link
  title: { type: String, optional: true },
  thumbnailUrl: { type: String, optional: true },
  url: { type: String, optional: true },
  originalUrl: { type: String, optional: true },
  providerName: { type: String, optional: true },
  providerUrl: { type: String, optional: true },
  authorUrl: { type: String, optional: true },
  authorName: { type: String, optional: true },
  thumbnailHeight: { type: Number, optional: true },
  thumbnailWidth: { type: Number, optional: true },
  embedlyType: { type: String, optional: true },
  imageOnLeft: { type: Boolean, optional: true },

  // Rich or Extract
  html: { type: String, optional: true },

  // Map

  mapQuery: {
    type: String,
    optional: true
  },
  mapType: {
    type: String,
    allowedValues: ['roadmap', 'satellite'],
    defaultValue: 'satellite',
    optional: true,
    autoform: {
      afFieldInput: {
        firstOption: false,
        options: 'allowed'
      }
    }
  }

});

Schema.ContextBlocks = new SimpleSchema({
  streamShortId: {
    type: String
  },
  authorId: {
    type: String
  },
  type: {
    type: String
  },
  source: {
    type: String,
    optional: true
  },
  fromEmbedly: {
    type: Boolean,
    optional: true
  },
  version: {
    type: String,
    optional: true
  },
  rank: {
    type: Number,
    optional: true
  },
  savedAt: {
    type: Date,
    optional: true
  },
  publishedAt: {
    type: Date,
    optional: true
  },
  createdAt: {
    type: Date,
    autoValue: function() {
      if (this.isInsert) {
        return new Date;
      } else if (this.isUpsert) {
        return {$setOnInsert: new Date};
      } else {
        this.unset();
      }
    },
    optional: true // optional because only added this fieldjust before launch
  },
  fullDetails: {
    type: Object,
    optional: true,
    blackbox: true
  },
  description: {
    type: String,
    optional: true
  },
  content: {
    type: String,
    trim: false,
    optional: true
  },
  published: {
    type: Boolean,
    defaultValue: false
  },
  everPublished: {
    type: Boolean,
    defaultValue: false
  },
  reference: {
    type: Schema.ContextReferenceProfile,
    optional: true
  },

  searchQuery: {
    type:String,
    optional:true
  },
  searchOption: {
    type: String,
    optional:true
  }
});

ContextBlocks.attachSchema(Schema.ContextBlocks);

this.ContextBlocks.deny({
  insert: function() {
    return true;
  },
  update: function() {
    return true
  },
  remove: function() {
    return true
  }
});

this.Streams = new Mongo.Collection("streams");
<|endoftext|>