<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require bootstrap
//= require jquery.infinitescroll

// Enable infinite scroll on activities and timeline entries lists
(function() {
  $(document).ready(function() {
    return $("#activities").infinitescroll({
      navSelector: "ul.pagination",
      nextSelector: "ul.pagination a[rel=next]",
      itemSelector: "#activities div.activity"
    });
  });

  $(document).ready(function() {
    return $("#timeline_entries").infinitescroll({
      navSelector: "ul.pagination",
      nextSelector: "ul.pagination a[rel=next]",
      itemSelector: "#timeline_entries div.timeline_entry"
    });
  });
}).call(this);
<commit_msg>timeline_entries => news_feed / better infinitescroll messages<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require bootstrap
//= require jquery.infinitescroll

// Enable infinite scroll on activities and timeline entries lists
(function() {
  $(document).ready(function() {
    return $("#activities").infinitescroll({
      navSelector: "ul.pagination",
      nextSelector: "ul.pagination a[rel=next]",
      itemSelector: "#activities div.activity",
      loading: {
        msgText: "Loading more activities...",
        finishedMsg: "No more activities."
      }
    });
  });

  $(document).ready(function() {
    return $("#news_feed").infinitescroll({
      navSelector: "ul.pagination",
      nextSelector: "ul.pagination a[rel=next]",
      itemSelector: "#news_feed div.activity",
      loading: {
        msgText: "Loading more news...",
        finishedMsg: "No more news."
      }
    });
  });
}).call(this);
<|endoftext|>


<commit_before>//jshint jquery:true
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require_tree .

$(document).ready(function(){

  $(document).on("click", "#login-button", function(event){
    event.preventDefault();
    $(".errors").empty();
    $(".overlay").fadeIn(400);
    $(".login-container").show();
  });

  $(document).on("click", "#x", function(event){
    $(".overlay, .login-container, #new-post-container, #edit-user-container, register-container").hide();
    $("form").each(function() { this.reset() });
  });

  $(document).on("submit", "#login-form", function(event){
    event.preventDefault();
    var url = window.location.href;
    var loginData = $(this).serialize();
    var request = $.ajax({
      method: "post",
      url: "/signin",
      data: loginData
    })

    .done(function(response) {
      window.location.replace(url);
    })

    .fail(function(response) {
      $(".errors").text("Email or Password is Incorrect");
    });
  });

  $(document).on("click", ".left-section a", function(event){
    event.preventDefault();
    $(".errors").empty();
    $(".login-container, #new-post-container").hide();
    // get new user
    var request = $.ajax({
      method: "get",
      url: "/users/new"
    })
    .done(function(response) {
      $(".reg-form").append(response);
      $(".register-container").show();
    })
    .fail(function(response) {
      $(".errors").text("Could not load new user form");
    });
  });

  $(document).on("submit", "#register-form", function(event){
    event.preventDefault();
    var url = window.location.href;
    var newUserData = $(this).serialize();
    var request = $.ajax({
      method: "post",
      url: "/users",
      data: newUserData
    })

    .done(function(response){
      window.location.replace(url);
    })

    .fail(function(response) {
      $(".errors").text("There was a problem with your registration form. Please make sure all fields are filled out correctly.").css("color", "red");
    });
  });

  // USER JS

  $(document).on("click", "#update", function(event){
    event.preventDefault();
    $(".overlay").fadeIn(400);
    $("#edit-user-container").show();
  });

  $(document).on("submit", ".user-edit", function(event){
    event.preventDefault();
    console.log("Here we are");
    var postData = $(this).serialize();
    console.log(postData);
    var method = $(this).attr("method");
    var url = $(this).attr("action");
    var return_url = window.location.href;

    var request = $.ajax({
                  url: url,
                  method: method,
                  data: postData
                  });
    request.done(function(response){
      window.location.replace(return_url);
    });
    request.fail(function(response){
      $(".errors").text("All fields must be filled.");
    });
  });

  // Chains & Messages

  $(document).on("click", "#reply-link", function(event){
    event.preventDefault();
    var url = $(this).attr("href");

    $.ajax({
      method: 'get',
      url: url
    })

    .done(function(html){
      $(".overlay").fadeIn(400);
      $("#new-message-container").append(html);
    });
  });

  $(document).on("click", "#message-close", function(){
    $("#new-message-container").empty();
    $(".overlay").fadeOut(400);
  });

  $(document).on("submit", "#new-message-form", function(event){
    event.preventDefault();
    var url = $(this).attr("action");
    var method = $(this).attr("method");
    var messageData = $(this).serialize();

    $.ajax({
      method: method,
      url: url,
      data: messageData
    })

    .done(function(response){
      $("#new-message-container").empty();
      $(".overlay").fadeOut(400);
      $("#reply").html("Message Sent!")
    });
  });

  $(document).on("click", ".chain-show", function(event){
    event.preventDefault();
    var id = ($(this).attr("id"));
    var url = $(this).attr("href");
    divId = ($(this).parents().eq(1).attr("id"))

    var request = $.ajax({
            url: url,
            method: "get",
            data: id
    });

    request.done(function(response){
      $(".overlay").fadeIn(400);
      $("#message-container").append(response);
      $("#message-container").show();
    });
  });

  $(document).on("click", "#chain-close", function(event){
    event.preventDefault();
    $(this).parent().empty();
    $("#message-container").hide();
    $(".overlay").fadeOut(400);

  })

  $(document).on("submit", "#new-reply-form", function(event){
    event.preventDefault();
    var url = $(this).attr("action");
    var method = $(this).attr("method");
    var messageData = $(this).serialize();

    $.ajax({
      method: method,
      url: url,
      data: messageData
    })
    .done(function(response){
      $("#message-container").empty();
      $("#message-container").hide();
      $(".overlay").fadeOut(400);
      $("#" + divId).replaceWith(response);
    });
  });

  // Goole translate move navbar
  $("#googlenav").on("click", "#google-translate", function(){
    $("#googlenav").addClass("google-wide");
  });

});
<commit_msg>fix JS file<commit_after>//jshint jquery:true
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require_tree .

$(document).ready(function(){

  $(document).on("click", "#login-button", function(event){
    event.preventDefault();
    $(".errors").empty();
    $(".overlay").fadeIn(400);
    $(".login-container").show();
  });

  $(document).on("click", "#x", function(event){
    $(".overlay, .login-container, #new-post-container, #edit-user-container, register-container").hide();
    $("form").each(function() { this.reset() });
  });

  $(document).on("submit", "#login-form", function(event){
    event.preventDefault();
    var url = window.location.href;
    var loginData = $(this).serialize();
    var request = $.ajax({
      method: "post",
      url: "/signin",
      data: loginData
    });

    request.done(function(response) {
      window.location.replace(url);
    });

    request.fail(function(response) {
      $(".errors").text("Email or Password is Incorrect");
    });
  });

  $(document).on("click", ".left-section a", function(event){
    event.preventDefault();
    $(".errors").empty();
    $(".login-container, #new-post-container").hide();
    // get new user
    var request = $.ajax({
      method: "get",
      url: "/users/new"
    });
    request.done(function(response) {
      $(".reg-form").append(response);
      $(".register-container").show();
    });
    request.fail(function(response) {
      $(".errors").text("Could not load new user form");
    });
  });

  $(document).on("submit", "#register-form", function(event){
    event.preventDefault();
    var url = window.location.href;
    var newUserData = $(this).serialize();
    var request = $.ajax({
      method: "post",
      url: "/users",
      data: newUserData
    });

    request.done(function(response){
      window.location.replace(url);
    });

    request.fail(function(response) {
      $(".errors").text("There was a problem with your registration form. Please make sure all fields are filled out correctly.").css("color", "red");
    });
  });

  // USER JS

  $(document).on("click", "#update", function(event){
    event.preventDefault();
    $(".overlay").fadeIn(400);
    $("#edit-user-container").show();
  });

  $(document).on("submit", ".user-edit", function(event){
    event.preventDefault();
    console.log("Here we are");
    var postData = $(this).serialize();
    console.log(postData);
    var method = $(this).attr("method");
    var url = $(this).attr("action");
    var return_url = window.location.href;

    var request = $.ajax({
                  url: url,
                  method: method,
                  data: postData
                  });
    request.done(function(response){
      window.location.replace(return_url);
    });
    request.fail(function(response){
      $(".errors").text("All fields must be filled.");
    });
  });

  // Chains & Messages

  $(document).on("click", "#reply-link", function(event){
    event.preventDefault();
    var url = $(this).attr("href");

    var request = $.ajax({
      method: 'get',
      url: url
    });

    request.done(function(html){
      $(".overlay").fadeIn(400);
      $("#new-message-container").append(html);
    });
  });

  $(document).on("click", "#message-close", function(){
    $("#new-message-container").empty();
    $(".overlay").fadeOut(400);
  });

  $(document).on("submit", "#new-message-form", function(event){
    event.preventDefault();
    var url = $(this).attr("action");
    var method = $(this).attr("method");
    var messageData = $(this).serialize();

    $.ajax({
      method: method,
      url: url,
      data: messageData
    })

    .done(function(response){
      $("#new-message-container").empty();
      $(".overlay").fadeOut(400);
      $("#reply").html("Message Sent!");
    });
  });

  $(document).on("click", ".chain-show", function(event){
    event.preventDefault();
    var id = ($(this).attr("id"));
    var url = $(this).attr("href");
    divId = ($(this).parents().eq(1).attr("id"));

    var request = $.ajax({
            url: url,
            method: "get",
            data: id
    });

    request.done(function(response){
      $(".overlay").fadeIn(400);
      $("#message-container").append(response);
      $("#message-container").show();
    });
  });

  $(document).on("click", "#chain-close", function(event){
    event.preventDefault();
    $(this).parent().empty();
    $("#message-container").hide();
    $(".overlay").fadeOut(400);

  });

  $(document).on("submit", "#new-reply-form", function(event){
    event.preventDefault();
    var url = $(this).attr("action");
    var method = $(this).attr("method");
    var messageData = $(this).serialize();

    $.ajax({
      method: method,
      url: url,
      data: messageData
    })
    .done(function(response){
      $("#message-container").empty();
      $("#message-container").hide();
      $(".overlay").fadeOut(400);
      $("#" + divId).replaceWith(response);
    });
  });

  // Goole translate move navbar
  $("#googlenav").on("click", "#google-translate", function(){
    $("#googlenav").addClass("google-wide");
  });

});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require chosen-jquery
//= require fancybox
//= require jquery.nested-fields
//= require jquery.are-you-sure
//= require_tree .

$(document).ready(function() {
  $(document).on("click", ".banner_remover", function() {
    $("." + $(this).data("banner-class")).remove();
    return false;
  });
});

$(document).ready(function () {
  if (!$('input').hasClass("multiclick")) {
    $('form').submit(function() {
      $("input[type='submit']", this).attr("disabled", "disabled");
      $("input[type='submit']", this).val("Please wait...");
    });
  }
});

$(document).ready(function() {
  $('form').areYouSure();
});

/* Generic sorting dataTable */
$(document).ready(function() {
  $(".sortable").each(function() {
    if ($(this).hasClass('searchable')) {
       search = true;
    } else {
       search = false;
    }
   $(this).DataTable({
     "bFilter": search,
     "bInfo": false,
     "bPaginate": false,
     "autoWidth": false,
     "orderClasses": false
   });
  });
});

/* Blatantly stoles from competitor.js.coffee */
var enable_chosen = function() {
  $('.chosen-select').chosen({
    allow_single_deselect: true,
    search_contains: true,
    no_results_text: 'No matches',
    width: '200px'});
};

$(document).ready(function(e) {
  $('FORM').each(function() {
    if ($(this).hasClass('multiple_nested')) {
      $('.nested_nested').nestedFields({
        afterInsert: function(item) {
          enable_chosen();
        }
      });
    }
    else
    {
      $(this).nestedFields({
        afterInsert: function(item) {
          enable_chosen();
        }
     });
    }
  });
});

// Sorting the list

var get_sortable_string = function() {
  additional = ""
  if ($('.drag_drop_sortable').data('additional')) {
    additional = $("#" + $('.drag_drop_sortable').data('additional')).serialize()
    if (additional != "") {
      additional = "&" + additional
    }
  }

  return $('.drag_drop_sortable').sortable('serialize') + additional
}

var set_sortable = function() {
  $('.drag_drop_sortable').sortable({
    axis: 'y',
    dropOnEmpty: false,
    //handle: '.handle',
    cursor: 'crosshair',
    items: 'tr',
    opacity: 0.4,
    scroll: true,
    update: function(){
      $.ajax({
        type: 'post',
        data: get_sortable_string(),
        dataType: 'script',
        complete: function(request){
          $('.drag_drop_sortable').effect('highlight');
        },
        url: $('.drag_drop_sortable').data('target')})
    }
  }).disableSelection();
}
$(document).ready(function(){
  set_sortable();
});

$(function() {
  $(".not_qualified").each(function() {
    $(this).attr('title', 'Not Qualified');
  });
});
<commit_msg>fix login behavior with 'are you sure' javascript<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require chosen-jquery
//= require fancybox
//= require jquery.nested-fields
//= require jquery.are-you-sure
//= require_tree .

$(document).ready(function() {
  $(document).on("click", ".banner_remover", function() {
    $("." + $(this).data("banner-class")).remove();
    return false;
  });
});

$(document).ready(function () {
  if (!$('input').hasClass("multiclick")) {
    $('form').submit(function() {
      $("input[type='submit']", this).attr("disabled", "disabled");
      $("input[type='submit']", this).val("Please wait...");
    });
  }
});

$(document).ready(function() {
  // this conflicts with using a password manager on the log-in page
  $('form').not(".new_user").areYouSure();
});

/* Generic sorting dataTable */
$(document).ready(function() {
  $(".sortable").each(function() {
    if ($(this).hasClass('searchable')) {
       search = true;
    } else {
       search = false;
    }
   $(this).DataTable({
     "bFilter": search,
     "bInfo": false,
     "bPaginate": false,
     "autoWidth": false,
     "orderClasses": false
   });
  });
});

/* Blatantly stoles from competitor.js.coffee */
var enable_chosen = function() {
  $('.chosen-select').chosen({
    allow_single_deselect: true,
    search_contains: true,
    no_results_text: 'No matches',
    width: '200px'});
};

$(document).ready(function(e) {
  $('FORM').each(function() {
    if ($(this).hasClass('multiple_nested')) {
      $('.nested_nested').nestedFields({
        afterInsert: function(item) {
          enable_chosen();
        }
      });
    }
    else
    {
      $(this).nestedFields({
        afterInsert: function(item) {
          enable_chosen();
        }
     });
    }
  });
});

// Sorting the list

var get_sortable_string = function() {
  additional = ""
  if ($('.drag_drop_sortable').data('additional')) {
    additional = $("#" + $('.drag_drop_sortable').data('additional')).serialize()
    if (additional != "") {
      additional = "&" + additional
    }
  }

  return $('.drag_drop_sortable').sortable('serialize') + additional
}

var set_sortable = function() {
  $('.drag_drop_sortable').sortable({
    axis: 'y',
    dropOnEmpty: false,
    //handle: '.handle',
    cursor: 'crosshair',
    items: 'tr',
    opacity: 0.4,
    scroll: true,
    update: function(){
      $.ajax({
        type: 'post',
        data: get_sortable_string(),
        dataType: 'script',
        complete: function(request){
          $('.drag_drop_sortable').effect('highlight');
        },
        url: $('.drag_drop_sortable').data('target')})
    }
  }).disableSelection();
}
$(document).ready(function(){
  set_sortable();
});

$(function() {
  $(".not_qualified").each(function() {
    $(this).attr('title', 'Not Qualified');
  });
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .

$(function(){ $(document).foundation(); });
<commit_msg>Exclude ActiveAdmin JS from main application<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require layout
//= require welcome

$(function(){ $(document).foundation(); });
<|endoftext|>


<commit_before>// TODO create a model from a local config object. not from a store config
var env = process.env;

var fs = require('fs');
var cache = require(env.Z_PATH_CACHE + 'cache');
var storeFactory = require(env.Z_PATH_STORES + 'factory');
var object = require(env.Z_PATH_UTILS + 'object');

var pojoModels = cache.pojo('models');
var compModels = cache.comp('models');

// read available store adapters to adapter cache
var adapatersPath = __dirname + '/adapters/';
var adapters = fs.readdirSync(adapatersPath);

// save adapter paths in adapter cache
for (var i = 0; i < adapters.length; ++i) {
    adapters[adapters[i]] = adapatersPath + adapters[i] + '/' + adapters[i] + '.js';
}

exports.setup = setup;
exports.factory = factory;

function setup (instance) {

    // listen for message events
    instance._request = messageHandler;
    instance._modelService = factoryService;
}

function factory (name, role, callback) {

    // check cache
    var model = pojoModels.get(name, role);

    if (model === 0) {
        return callback(new Error('Model ' + name + ' not found.'));
    }

    if (model) {
        return callback(null, model);
    }

    // get and set model config from composition store
    compModels.set(name, role, function (err, comp_model) {

        if (err || !comp_model) {
            return callback(err || new Error('Model ' + name + ' not found.'));
        }

        // get connected store
        storeFactory(comp_model.store, role, function (err, store) {

            if (err) {
                return callback(err);
            }

            // handle error and check if adapter exists
            if (err || !adapters[comp_model.adapter]) {
                return callback(err || new Error('Model adapter "' + comp_model.adapter + '" not available.'));
            }

            // require adapter
            if (typeof adapters[comp_model.adapter] === 'string') {
                adapters[comp_model.adapter] = require(adapters[comp_model.adapter]);
            }

            // save model in cache
            model = adapters[comp_model.adapter].model(store, comp_model);

            // extend model with query function
            model.query = createQuery;

            // save adapter name on model
            model._adapter = comp_model.adapter;

            // query container
            model.queries = {};

            // create queries from the config
            if (comp_model.queries) {
                for (var i = 0; i < comp_model.queries.length; ++i) {
                    model.query(comp_model.queries[i]);
                }
            }

            // save roles on model
            model._roles = comp_model.roles;

            // save model in cache
            pojoModels.set(name, model);

            callback(null, model);
        });
    });
}

// listen to model request
function factoryService (err, name, callback) {
    var self = this;

    // check message
    if (!name) {
        return callback('Bad message');
    }

    // send the model schema to the client
    factory(name, self.link.role, function (err, model) {

        if (err) {
            return callback(err);
        }

        var clientModel = {
            name: model.name,
            schema: model.schema
        };

        callback(null, clientModel);
    });
}

// handle requests
function createQuery (config) {
    var self = this;
    var handler;

    // get custom query handlers
    if (config.handler) {
        handler = object.path(config.handler/* TODO pass instance*/);

        if (typeof handler === 'function') {
            handler = config.handler.call(self, config.request);
        }
    }

    // create a query handler with the adapters query factory
    handler = adapters[self._adapter].query.call(self, config.request);

    // don't add query to container if no hander is created
    if (!handler) {
        return;
    }

    // add query function to query container
    self.queries[config.name] = function (data, callback) {

        // copy request object
        var request = JSON.parse(JSON.stringify(config.request));

        // merge data into request
        if (config.add && data) {

            var value;

            // extend request object
            for (var key in config.add) {

                if ((value = object.path(config.add[key], data))) {
                    request[key] = value;
                }
            }
        }

        // merge the static data to the request
        if (config.data) {
            for (var key in config.data) {
                request[key] = config.data[key];
            }
        }

        // nest flat paths
        request = object.deep(request);

        // execute query with request infos
        handler(request, callback);
    };
}

// handle model data request
function messageHandler (err, message, callback) {
    var self = this;

    // check message
    if (!message || !message.m || !message.q) {
        return callback(new Error('Bad message.'));
    }

    // get model from cache
    var model = pojoModels.get(message.m, self.link.role);

    if (!model) {
        return callback(new Error('Model "' + message.m + '" not found.'));
    }

    if (!model.queries[message.q]) {
        return callback(new Error('Model query "' + message.q + '" not found.'));
    }

    // do model query request
    model.queries[message.q](message.d, callback);
}
<commit_msg>XMerge branch 'model-queries' of github.com:jillix/engine into model-queries<commit_after>// TODO create a model from a local config object. not from a store config
var env = process.env;

var fs = require('fs');
var cache = require(env.Z_PATH_CACHE + 'cache');
var storeFactory = require(env.Z_PATH_STORES + 'factory');
var object = require(env.Z_PATH_UTILS + 'object');

var pojoModels = cache.pojo('models');
var compModels = cache.comp('models');

// read available store adapters to adapter cache
var adapatersPath = __dirname + '/adapters/';
var adapters = fs.readdirSync(adapatersPath);

// save adapter paths in adapter cache
for (var i = 0; i < adapters.length; ++i) {
    adapters[adapters[i]] = adapatersPath + adapters[i] + '/' + adapters[i] + '.js';
}

exports.setup = setup;
exports.factory = factory;

function setup (instance) {

    // listen for message events
    instance._request = messageHandler;
    instance._modelService = factoryService;
}

function factory (name, role, callback) {

    // check cache
    var model = pojoModels.get(name, role);

    if (model === 0) {
        return callback(new Error('Model ' + name + ' not found.'));
    }

    if (model) {
        return callback(null, model);
    }

    // get and set model config from composition store
    compModels.set(name, role, function (err, comp_model) {

        if (err || !comp_model) {
            return callback(err || new Error('Model ' + name + ' not found.'));
        }

        // get connected store
        storeFactory(comp_model.store, role, function (err, store) {

            if (err) {
                return callback(err);
            }

            // handle error and check if adapter exists
            if (err || !adapters[comp_model.adapter]) {
                return callback(err || new Error('Model adapter "' + comp_model.adapter + '" not available.'));
            }

            // require adapter
            if (typeof adapters[comp_model.adapter] === 'string') {
                adapters[comp_model.adapter] = require(adapters[comp_model.adapter]);
            }

            // save model in cache
            model = adapters[comp_model.adapter].model(store, comp_model);

            // extend model with query function
            model.query = createQuery;

            // save adapter name on model
            model._adapter = comp_model.adapter;

            // query container
            model.queries = {};

            // create queries from the config
            if (comp_model.queries) {
                for (var i = 0; i < comp_model.queries.length; ++i) {
                    model.query(comp_model.queries[i]);
                }
            }

            // save roles on model
            model._roles = comp_model.roles;

            // save model in cache
            pojoModels.set(name, model);

            callback(null, model);
        });
    });
}

// listen to model request
function factoryService (err, name, callback) {
    var self = this;

    // check message
    if (!name) {
        return callback('Bad message');
    }

    // send the model schema to the client
    factory(name, self.link.role, function (err, model) {

        if (err) {
            return callback(err);
        }

        var clientModel = {
            name: model.name,
            schema: model.schema
        };

        callback(null, clientModel);
    });
}

// handle requests
function createQuery (config) {
    var self = this;
    var handler;

    // get custom query handlers
    if (config.handler) {
        handler = object.path(config.handler/* TODO pass instance*/);

        if (typeof handler === 'function') {
            handler = config.handler.call(self, config.request);
        }
    } else {
        // create a query handler with the adapters query factory
        handler = adapters[self._adapter].query.call(self, config.request);
    }

    // don't add query to container if no hander is created
    if (!handler) {
        return;
    }

    // add query function to query container
    self.queries[config.name] = function (data, callback) {

        // copy request object
        var request = JSON.parse(JSON.stringify(config.request));

        // merge data into request
        if (config.add && data) {

            var value;

            // extend request object
            for (var key in config.add) {

                if ((value = object.path(config.add[key], data))) {
                    request[key] = value;
                }
            }
        }

        // nest flat paths
        request = object.deep(request);

        // execute query with request infos
        handler(request, callback);
    };
}

// handle model data request
function messageHandler (err, message, callback) {
    var self = this;

    // check message
    if (!message || !message.m || !message.q) {
        return callback(new Error('Bad message.'));
    }

    // get model from cache
    var model = pojoModels.get(message.m, self.link.role);

    if (!model) {
        return callback(new Error('Model "' + message.m + '" not found.'));
    }

    if (!model.queries[message.q]) {
        return callback(new Error('Model query "' + message.q + '" not found.'));
    }

    // do model query request
    model.queries[message.q](message.d, callback);
}
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

$(document).on("ready", function(){
  var container = document.querySelector('#container');
  var msnry = new Masonry(container);
  // layout Masonry again after all images have loaded
  imagesLoaded( container, function() {
    msnry.layout();
  });

  window.setInterval(function(){
    $.ajax({
      type: "GET",
      url: "/",
      contentType: "application/json; charset=utf-8",
      ifModified: true,
      dataType: "json",
      success: function(data, status){
        console.log(data);
        console.log(status);
        if(status != "notmodified") {
          $("#container").empty();
          var bgColor = 0;
          for (var i = 0; i < data.length; i++){
            bgColor += 1;
            var obj = data[i];
            var tweet = new Tweet(obj.text, obj.screen_name, obj.created_at_formatted, obj.profile_image_url, obj.media_url);
            render(tweet).addClass("background-color-"+bgColor);
            if(bgColor == 4) { bgColor = 0 }
          }
            var container = document.querySelector('#container');
            var msnry = new Masonry(container);
            imagesLoaded( container, function() {
                msnry.layout();
            });
        }
      }
    });
  }, 60000);

});

function Tweet(text, screen_name, created_at, profile_image_url, media_url) {
  return {
    text: text,
    screen_name: screen_name,
    created_at: created_at,
    profile_image_url: profile_image_url,
    media_url: media_url
  };
}

function render(tweet) {
  var container = $("#container")
  container.append("

")
  var tweetContainer = container.find(".tweet-container").last()

  tweetContainer.append("

");
  tweetContainer.find(".tweet-text").text(tweet.text);

  tweetContainer.append("

");
  tweetContainer.find(".tweet-username").html(" @" + tweet.screen_name);

  tweetContainer.append("

");
  if (tweet.media_url){
    tweetContainer.find(".tweet-picture").html("");
  }

  tweetContainer.append("

");
  tweetContainer.find(".tweet-created-at").text(tweet.created_at);
  return tweetContainer;
}
<commit_msg>added a debugging<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

$(document).on("ready", function(){
  var container = document.querySelector('#container');
  var msnry = new Masonry(container);
  // layout Masonry again after all images have loaded
  imagesLoaded( container, function() {
    alert();
    msnry.layout();
  });

  window.setInterval(function(){
    $.ajax({
      type: "GET",
      url: "/",
      contentType: "application/json; charset=utf-8",
      ifModified: true,
      dataType: "json",
      success: function(data, status){
        console.log(data);
        console.log(status);
        if(status != "notmodified") {
          $("#container").empty();
          var bgColor = 0;
          for (var i = 0; i < data.length; i++){
            bgColor += 1;
            var obj = data[i];
            var tweet = new Tweet(obj.text, obj.screen_name, obj.created_at_formatted, obj.profile_image_url, obj.media_url);
            render(tweet).addClass("background-color-"+bgColor);
            if(bgColor == 4) { bgColor = 0 }
          }
            var container = document.querySelector('#container');
            var msnry = new Masonry(container);
            imagesLoaded( container, function() {
                msnry.layout();
            });
        }
      }
    });
  }, 60000);

});

function Tweet(text, screen_name, created_at, profile_image_url, media_url) {
  return {
    text: text,
    screen_name: screen_name,
    created_at: created_at,
    profile_image_url: profile_image_url,
    media_url: media_url
  };
}

function render(tweet) {
  var container = $("#container")
  container.append("

")
  var tweetContainer = container.find(".tweet-container").last()

  tweetContainer.append("

");
  tweetContainer.find(".tweet-text").text(tweet.text);

  tweetContainer.append("

");
  tweetContainer.find(".tweet-username").html(" @" + tweet.screen_name);

  tweetContainer.append("

");
  if (tweet.media_url){
    tweetContainer.find(".tweet-picture").html("");
  }

  tweetContainer.append("

");
  tweetContainer.find(".tweet-created-at").text(tweet.created_at);
  return tweetContainer;
}
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require modernizr.custom
//= require jquery
//= require rails
//= require underscore
//= require backbone
//= require backbone-support
//= require mustache
//= require moment
//= require d3.v2
//= require backbone-bootstrap
//= require_tree .

$( document ).ready(function() {
  $( 'select#user_current_company_id' ).live( 'change', function() {
    $( this ).closest( 'form' ).submit();
  });
});
<commit_msg>add missing require for jquery ui min<commit_after>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require modernizr.custom
//= require jquery
//= require jquery-ui-1.8.17.custom.min
//= require rails
//= require underscore
//= require backbone
//= require backbone-support
//= require mustache
//= require moment
//= require d3.v2
//= require backbone-bootstrap
//= require_tree .

$( document ).ready(function() {
  $( 'select#user_current_company_id' ).live( 'change', function() {
    $( this ).closest( 'form' ).submit();
  });
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require modernizr-2.6.1.min
//= require markitup/jquery.markitup
//= require markitup/sets/markdown/set
//= require bootstrap-alert
//= require bootstrap-modal
//= require pdf
//= require compatibility
//= require_tree .<commit_msg>Removed pdf.js from manifest<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require modernizr-2.6.1.min
//= require markitup/jquery.markitup
//= require markitup/sets/markdown/set
//= require bootstrap-alert
//= require bootstrap-modal
//= require_tree .<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//

//= require ./app/lib/core/jquery-2.1.4.js
//= require ./app/lib/core/jquery-ui-1.11.2.js
//= require ./app/lib/core/underscore-1.8.3.js

//= require ./app/lib/animations/velocity.min.js
//= require ./app/lib/animations/velocity.ui.js

//not_used= require_tree ./app/lib/spine
//= require ./app/lib/spine/spine.coffee
//= require ./app/lib/spine/ajax.coffee
//= require ./app/lib/spine/local.coffee
//= require ./app/lib/spine/route.coffee

//= require ./app/lib/flot/jquery.flot.js
//= require ./app/lib/flot/jquery.flot.selection.js

//not_used= require_tree ./app/lib/bootstrap
//= require ./app/lib/bootstrap/dropdown.js
//= require ./app/lib/bootstrap/tooltip.js
//= require ./app/lib/bootstrap/popover.js
//= require ./app/lib/bootstrap/popover-enhance.js

// modified by Felix Jan-2014
//= require ./app/lib/bootstrap/modal.js

//= require ./app/lib/bootstrap/tab.js
//= require ./app/lib/bootstrap/transition.js
//= require ./app/lib/bootstrap/button.js
//= require ./app/lib/bootstrap/collapse.js
//= require ./app/lib/bootstrap/bootstrap-timepicker.js

//= require ./app/lib/rangy/rangy-core.js
//= require ./app/lib/rangy/rangy-classapplier.js
//= require ./app/lib/rangy/rangy-textrange.js
//= require ./app/lib/rangy/rangy-highlighter.js

//= require_tree ./app/lib/base

//= require ./app/index.js.coffee

// IE8 workaround for missing console.log
if (!window.console) {
  window.console = {}
}
if (!console.log) {
  console.log = function(){}
}

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

Date.prototype.getWeek = function() {
  var onejan = new Date(this.getFullYear(),0,1);
  return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}

function difference(object1, object2) {
  var changes = {};
  for ( var name in object1 ) {
    if ( name in object2 ) {
      if ( _.isObject( object2[name] ) && !_.isArray( object2[name] ) ) {
        var diff = difference( object1[name], object2[name] );
        if ( !_.isEmpty( diff ) ) {
            changes[name] = diff;
        }
      } else if ( !_.isEqual( object1[name], object2[name] ) ) {
        changes[name] = object2[name];
      }
    }
  }
  return changes;
}

// clone, just data, no instances of objects
function clone(item, full) {

  // just return/clone false conditions
  if (!item) { return item }

  var itemType = item.constructor.name

  // IE behavior // doesn't know item.constructor.name, detect it by underscore
  if (itemType === undefined) {
    if (_.isArray(item)) {
      itemType = 'Array'
    }
    else if (_.isNumber(item)) {
      itemType = 'Number'
    }
    else if (_.isString(item)) {
      itemType = 'String'
    }
    else if (_.isBoolean(item)) {
      itemType = 'Boolean'
    }
    else if (_.isFunction(item)) {
      itemType = 'Function'
    }
    else if (_.isObject(item)) {
      itemType = 'Object'
    }
  }

  // ignore certain objects
  var acceptedInstances = [ 'Object', 'Number', 'String', 'Boolean', 'Array' ]
  if (full) {
    acceptedInstances.push( 'Function' )
  }

  // check if item is accepted to get cloned
  if (itemType && !_.contains(acceptedInstances, itemType)) {
    console.log('no acceptedInstances', itemType, item)
    return
  }

  // copy array
  var result;
  if (itemType == 'Array')  {
    result = []
    item.forEach(function(child, index, array) {
      result[index] = clone( child, full )
    });
  }

  // copy function
  else if (itemType == 'Function') {
    result = item.bind({})
  }

  // copy object
  else if (itemType == 'Object') {
    result = {}
    for(var key in item) {
      if (item.hasOwnProperty(key)) {
        result[key] = clone( item[key], full )
      }
    }
  }
  // copy others
  else {
    result = item
  }
  return result
}

// taken from http://stackoverflow.com/questions/4459928/how-to-deep-clone-in-javascript
function clone2(item) {
    if (!item) { return item; } // null, undefined values check

    var types = [ Number, String, Boolean ],
        result;

    // normalizing primitives if someone did new String('aaa'), or new Number('444');
    types.forEach(function(type) {
        if (item instanceof type) {
            result = type( item );
        }
    });

    if (typeof result == "undefined") {
        if (Object.prototype.toString.call( item ) === "[object Array]") {
            result = [];
            item.forEach(function(child, index, array) {
                result[index] = clone( child );
            });
        } else if (typeof item == "object") {
            // testing that this is DOM
            if (item.nodeType && typeof item.cloneNode == "function") {
                var result = item.cloneNode( true );
            } else if (!item.prototype) { // check that this is a literal
                if (item instanceof Date) {
                    result = new Date(item);
                } else {
                    // it is an object literal
                    result = {};
                    for (var i in item) {
                        result[i] = clone( item[i] );
                    }
                }
            } else {
                // depending what you would like here,
                // just keep the reference, or create new object
                if (false && item.constructor) {
                    // would not advice to do that, reason? Read below
                    result = new item.constructor();
                } else {
                    result = item;
                }
            }
        } else {
            result = item;
        }
    }

    return result;
}

jQuery.event.special.remove = {
  remove: function(e) {
    if (e.handler) e.handler();
  }
};

// start application
jQuery(function(){
  new App.Run();
});<commit_msg>Added function to underscore convert strings.<commit_after>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//

//= require ./app/lib/core/jquery-2.1.4.js
//= require ./app/lib/core/jquery-ui-1.11.2.js
//= require ./app/lib/core/underscore-1.8.3.js

//= require ./app/lib/animations/velocity.min.js
//= require ./app/lib/animations/velocity.ui.js

//not_used= require_tree ./app/lib/spine
//= require ./app/lib/spine/spine.coffee
//= require ./app/lib/spine/ajax.coffee
//= require ./app/lib/spine/local.coffee
//= require ./app/lib/spine/route.coffee

//= require ./app/lib/flot/jquery.flot.js
//= require ./app/lib/flot/jquery.flot.selection.js

//not_used= require_tree ./app/lib/bootstrap
//= require ./app/lib/bootstrap/dropdown.js
//= require ./app/lib/bootstrap/tooltip.js
//= require ./app/lib/bootstrap/popover.js
//= require ./app/lib/bootstrap/popover-enhance.js

// modified by Felix Jan-2014
//= require ./app/lib/bootstrap/modal.js

//= require ./app/lib/bootstrap/tab.js
//= require ./app/lib/bootstrap/transition.js
//= require ./app/lib/bootstrap/button.js
//= require ./app/lib/bootstrap/collapse.js
//= require ./app/lib/bootstrap/bootstrap-timepicker.js

//= require ./app/lib/rangy/rangy-core.js
//= require ./app/lib/rangy/rangy-classapplier.js
//= require ./app/lib/rangy/rangy-textrange.js
//= require ./app/lib/rangy/rangy-highlighter.js

//= require_tree ./app/lib/base

//= require ./app/index.js.coffee

// IE8 workaround for missing console.log
if (!window.console) {
  window.console = {}
}
if (!console.log) {
  console.log = function(){}
}

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

Date.prototype.getWeek = function() {
  var onejan = new Date(this.getFullYear(),0,1);
  return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}

function difference(object1, object2) {
  var changes = {};
  for ( var name in object1 ) {
    if ( name in object2 ) {
      if ( _.isObject( object2[name] ) && !_.isArray( object2[name] ) ) {
        var diff = difference( object1[name], object2[name] );
        if ( !_.isEmpty( diff ) ) {
            changes[name] = diff;
        }
      } else if ( !_.isEqual( object1[name], object2[name] ) ) {
        changes[name] = object2[name];
      }
    }
  }
  return changes;
}

// clone, just data, no instances of objects
function clone(item, full) {

  // just return/clone false conditions
  if (!item) { return item }

  var itemType = item.constructor.name

  // IE behavior // doesn't know item.constructor.name, detect it by underscore
  if (itemType === undefined) {
    if (_.isArray(item)) {
      itemType = 'Array'
    }
    else if (_.isNumber(item)) {
      itemType = 'Number'
    }
    else if (_.isString(item)) {
      itemType = 'String'
    }
    else if (_.isBoolean(item)) {
      itemType = 'Boolean'
    }
    else if (_.isFunction(item)) {
      itemType = 'Function'
    }
    else if (_.isObject(item)) {
      itemType = 'Object'
    }
  }

  // ignore certain objects
  var acceptedInstances = [ 'Object', 'Number', 'String', 'Boolean', 'Array' ]
  if (full) {
    acceptedInstances.push( 'Function' )
  }

  // check if item is accepted to get cloned
  if (itemType && !_.contains(acceptedInstances, itemType)) {
    console.log('no acceptedInstances', itemType, item)
    return
  }

  // copy array
  var result;
  if (itemType == 'Array')  {
    result = []
    item.forEach(function(child, index, array) {
      result[index] = clone( child, full )
    });
  }

  // copy function
  else if (itemType == 'Function') {
    result = item.bind({})
  }

  // copy object
  else if (itemType == 'Object') {
    result = {}
    for(var key in item) {
      if (item.hasOwnProperty(key)) {
        result[key] = clone( item[key], full )
      }
    }
  }
  // copy others
  else {
    result = item
  }
  return result
}

// taken from http://stackoverflow.com/questions/4459928/how-to-deep-clone-in-javascript
function clone2(item) {
    if (!item) { return item; } // null, undefined values check

    var types = [ Number, String, Boolean ],
        result;

    // normalizing primitives if someone did new String('aaa'), or new Number('444');
    types.forEach(function(type) {
        if (item instanceof type) {
            result = type( item );
        }
    });

    if (typeof result == "undefined") {
        if (Object.prototype.toString.call( item ) === "[object Array]") {
            result = [];
            item.forEach(function(child, index, array) {
                result[index] = clone( child );
            });
        } else if (typeof item == "object") {
            // testing that this is DOM
            if (item.nodeType && typeof item.cloneNode == "function") {
                var result = item.cloneNode( true );
            } else if (!item.prototype) { // check that this is a literal
                if (item instanceof Date) {
                    result = new Date(item);
                } else {
                    // it is an object literal
                    result = {};
                    for (var i in item) {
                        result[i] = clone( item[i] );
                    }
                }
            } else {
                // depending what you would like here,
                // just keep the reference, or create new object
                if (false && item.constructor) {
                    // would not advice to do that, reason? Read below
                    result = new item.constructor();
                } else {
                    result = item;
                }
            }
        } else {
            result = item;
        }
    }

    return result;
}

// taken from https://github.com/epeli/underscore.string/blob/master/underscored.js
function underscored (str) {
  return str.trim().replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/[-\s]+/g, '_').toLowerCase();
}

jQuery.event.special.remove = {
  remove: function(e) {
    if (e.handler) e.handler();
  }
};

// start application
jQuery(function(){
  new App.Run();
});<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require adapt.min
//= require jquery/jquery
//= require jquery/jquery_ujs
//= require jquery/jquery.bind-with-delay
//= require jquery/jquery.observer
//= require jquery/jquery.elastic
//= require jquery/jquery.bsmselect
//= require jquery/jquery.bsmselect.compatibility
//= require jquery/jquery.bsmselect.sortable
//= require jquery/jquery.reject.min
//= require raphael/raphael-min
//= require raphael/g.raphael-min
//= require raphael/g.pie-min
//= require jquery/jquery.facebox
//= require jquery/jquery.placeholder
//
//not for now: //= require_tree .

//TODO: move everything below to separate javascript files

// ajax loader
$(function() {
  // show #loading element
  $('#loading').ajaxStart(function() { $(this).fadeIn(150); })
               .ajaxStop(function() { $(this).fadeOut(150); });
  // but not for rails' automatic $.ajax calls
  $.rails.ajax = function(options) {
    return $.ajax($.extend(options, {global: false}));
  }
});

// application events
$(function() {
  //table sorting
  $(".items_list th a").live("click", function(e) {
    $.getScript(this.href);
    //fallback for old browsers
    if (!('pushState' in window.history)) return true
    //ensure middle, control and command clicks act normally
    //if (e.which == 2 || e.metaKey || e.ctrlKey) return true
    //push history!
    history.pushState(null, document.title, this.href);
    e.preventDefault();
  });

  //server 'virtual' toggling
  $('#server_virtual').live('change', function(e) {
    $('.hidden-if-virtual').toggleClass("virtual");
    if ($('input#server_virtual').attr('checked') == true) {
      $('#server-hardware-title').html("Ressources");
    } else {
      $('#server-hardware-title').html("Matériel");
    }
  });

  //filters observer
  submitFilters = function() {
    $.get($("#filters").attr("action"), $("#filters").serialize(), null, "script");
    //fallback for old browsers
    if (!('replaceState' in window.history)) return true
    //push our search to history
    var filters = jQuery.param( jQuery.grep( $('#filters').serializeArray(), function(o){ return o.name != "utf8" && o.value != "" } ) )
    var url = $("#filters").attr("action").split("?")[0] + "?" + filters
    history.replaceState(null, document.title, url);
  }
  $(".filters input").bindWithDelay("keyup", submitFilters, 300);
  $(".filters select").change(submitFilters);

  //back button for pushState's
  $(window).bind("popstate", function() {
    //commented out since it makes calls to ".js"'s urls even when not necessary at all (welcome page for instance)
    //TODO: switch to jquery-pjax ftw!
    //$.getScript(location.href);
  });

  //multiselect with bsmSelect plugin
  bsmizeSelects();

  //hide alert messages
  $('#flash').delay(4000).slideUp(300);

  //faceboxes
  $('a[rel*=facebox]').facebox();
});

// context
$(function(){
  $(".contextswitch").click(function(e){
    var a=$(this), d=a.closest(".toggle");
    if (a.hasClass("activated")) {
      a.removeClass("activated");
    } else {
      a.addClass("activated");
      e.stopPropagation();
      $(document).one("click", {contextSwitch: a}, function(e){ e.data.contextSwitch.removeClass("activated"); });
    }
  })
});

// some checkboxes acts as radio buttons on servers/show view
$(function(){
  $('input[type="checkbox"].main_ip').live('change', function() {
    if ($(this).is(":checked")) {
      var id = $(this).attr("id");
      $('input[type="checkbox"].main_ip:checked').each(function() {
        if ($(this).attr("id") != id) $(this).attr("checked", false);
      });
    }
  });
});

//bsm plugin
function bsmizeSelects() {
  $("select[multiple]").bsmSelect({
    showEffect: function($el){ $el.fadeIn(); },
    hideEffect: function($el){ $el.fadeOut(function(){ $(this).remove();}); },
    title: 'Sélectionnez...',
    highlight: 'highlight',
    addItemTarget: 'original',
    removeLabel: 'x',
    containerClass: 'bsmContainer',                // Class for container that wraps this widget
    listClass: 'bsmList-custom',                   // Class for the list ($ol)
    listItemClass: 'bsmListItem-custom',           // Class for the
 list items
    listItemLabelClass: 'bsmListItemLabel-custom', // Class for the label text that appears in list items
    removeClass: 'bsmListItemRemove-custom',       // Class given to the "remove" link
  });
}

// nested forms
function remove_fields(link) {
  $(link).prev("input[type=hidden]").val("1");
  $(link).closest(".fields").hide();
}

function add_fields(link, association, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + association, "g")
  $(link).parent().before(content.replace(regexp, new_id));
  bsmizeSelects();
}

// elastic <textarea>'s
$(function() {
  $('textarea').elastic().unbind('blur');
});

//fixed table column sizes
function fixTableHeaders() {
  $('.fixed-size, .fix-on-scroll').children().each(function() { fixElementSize($(this)); });
  $('td.multirow').siblings().andSelf().each(function() { fixElementSize($(this)); });
}
function fixElementSize(elem) {
  elem.css('width', parseInt(elem.innerWidth()) - parseInt(elem.css('paddingLeft')) - parseInt(elem.css('paddingRight')));
}

$(window).load(function() {
  //fix table headers one time after everything is loaded
  fixTableHeaders();

  //fixed table headers on scroll
  var selector = '.fix-on-scroll';
  if ($(selector).length < 1) return false;
  $(selector).each(function() {
    this.initialTopOffset = $(this).offset().top; // - parseFloat($(selector).css('marginTop').replace(/auto/, 0));
  });

  //fix headers on scroll
  $(window).scroll(function (event) {
    fixHeadersOnScroll();
  });
  //fix headers once everything is loaded (in case we're not at the top)
  fixHeadersOnScroll();

  function fixHeadersOnScroll() {
    // what the y position of the scroll is
    var y = $(window).scrollTop();
    $(selector).each(function() {
      // whether that's below the form
      if (y >= this.initialTopOffset) {
        // if so, ad the fixed class
        $(this).addClass('fixed');
      } else {
        // otherwise remove it
        $(this).removeClass('fixed');
      }
    });
  }
});

//top menu items
$(function() {
  var otherOpen = false;
  $('.has-submenu:not(.active)>a').live('click', openSubMenu);
  $('.has-submenu:not(.active)>a').live('mouseenter', openSubMenuIfOtherOpen);
  $('.has-submenu.active>a').live('click', closeAllSubMenus);
  function openSubMenu(event) {
    closeAllSubMenus();
    var button = $(this).parent().addClass('active');
    var menu = $(this).children('div');
    var h = (button.outerHeight) ? button.outerHeight() : button.height();
    menu.addClass('active')
        .click(function(e) { e.stopPropagation(); })
    $(document).one('click', {button: button}, closeSubMenu);
    otherOpen = true;
    return false;
  }
  function openSubMenuIfOtherOpen(event) {
    if (otherOpen) { $(this).trigger('click'); }
  }
  function closeSubMenu(event) {
    if (!$(event.target).hasClass("submenu") && !$(event.target).closest('.has-submenu').hasClass('active')) {
      event.data.button.removeClass('active');
      otherOpen = false;
    } else {
      $(document).one('click', {button: event.data.button}, closeSubMenu);
    }
  }
  function closeAllSubMenus() {
    $('.has-submenu').removeClass('active');
    otherOpen = false;
    return false;
  }
});
<commit_msg>Changed 'remove' sign for bsm multiselect inputs<commit_after>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require adapt.min
//= require jquery/jquery
//= require jquery/jquery_ujs
//= require jquery/jquery.bind-with-delay
//= require jquery/jquery.observer
//= require jquery/jquery.elastic
//= require jquery/jquery.bsmselect
//= require jquery/jquery.bsmselect.compatibility
//= require jquery/jquery.bsmselect.sortable
//= require jquery/jquery.reject.min
//= require raphael/raphael-min
//= require raphael/g.raphael-min
//= require raphael/g.pie-min
//= require jquery/jquery.facebox
//= require jquery/jquery.placeholder
//
//not for now: //= require_tree .

//TODO: move everything below to separate javascript files

// ajax loader
$(function() {
  // show #loading element
  $('#loading').ajaxStart(function() { $(this).fadeIn(150); })
               .ajaxStop(function() { $(this).fadeOut(150); });
  // but not for rails' automatic $.ajax calls
  $.rails.ajax = function(options) {
    return $.ajax($.extend(options, {global: false}));
  }
});

// application events
$(function() {
  //table sorting
  $(".items_list th a").live("click", function(e) {
    $.getScript(this.href);
    //fallback for old browsers
    if (!('pushState' in window.history)) return true
    //ensure middle, control and command clicks act normally
    //if (e.which == 2 || e.metaKey || e.ctrlKey) return true
    //push history!
    history.pushState(null, document.title, this.href);
    e.preventDefault();
  });

  //server 'virtual' toggling
  $('#server_virtual').live('change', function(e) {
    $('.hidden-if-virtual').toggleClass("virtual");
    if ($('input#server_virtual').attr('checked') == true) {
      $('#server-hardware-title').html("Ressources");
    } else {
      $('#server-hardware-title').html("Matériel");
    }
  });

  //filters observer
  submitFilters = function() {
    $.get($("#filters").attr("action"), $("#filters").serialize(), null, "script");
    //fallback for old browsers
    if (!('replaceState' in window.history)) return true
    //push our search to history
    var filters = jQuery.param( jQuery.grep( $('#filters').serializeArray(), function(o){ return o.name != "utf8" && o.value != "" } ) )
    var url = $("#filters").attr("action").split("?")[0] + "?" + filters
    history.replaceState(null, document.title, url);
  }
  $(".filters input").bindWithDelay("keyup", submitFilters, 300);
  $(".filters select").change(submitFilters);

  //back button for pushState's
  $(window).bind("popstate", function() {
    //commented out since it makes calls to ".js"'s urls even when not necessary at all (welcome page for instance)
    //TODO: switch to jquery-pjax ftw!
    //$.getScript(location.href);
  });

  //multiselect with bsmSelect plugin
  bsmizeSelects();

  //hide alert messages
  $('#flash').delay(4000).slideUp(300);

  //faceboxes
  $('a[rel*=facebox]').facebox();
});

// context
$(function(){
  $(".contextswitch").click(function(e){
    var a=$(this), d=a.closest(".toggle");
    if (a.hasClass("activated")) {
      a.removeClass("activated");
    } else {
      a.addClass("activated");
      e.stopPropagation();
      $(document).one("click", {contextSwitch: a}, function(e){ e.data.contextSwitch.removeClass("activated"); });
    }
  })
});

// some checkboxes acts as radio buttons on servers/show view
$(function(){
  $('input[type="checkbox"].main_ip').live('change', function() {
    if ($(this).is(":checked")) {
      var id = $(this).attr("id");
      $('input[type="checkbox"].main_ip:checked').each(function() {
        if ($(this).attr("id") != id) $(this).attr("checked", false);
      });
    }
  });
});

//bsm plugin
function bsmizeSelects() {
  $("select[multiple]").bsmSelect({
    showEffect: function($el){ $el.fadeIn(); },
    hideEffect: function($el){ $el.fadeOut(function(){ $(this).remove();}); },
    title: 'Sélectionnez...',
    highlight: 'highlight',
    addItemTarget: 'original',
    removeLabel: '×',
    containerClass: 'bsmContainer',                // Class for container that wraps this widget
    listClass: 'bsmList-custom',                   // Class for the list ($ol)
    listItemClass: 'bsmListItem-custom',           // Class for the
 list items
    listItemLabelClass: 'bsmListItemLabel-custom', // Class for the label text that appears in list items
    removeClass: 'bsmListItemRemove-custom',       // Class given to the "remove" link
  });
}

// nested forms
function remove_fields(link) {
  $(link).prev("input[type=hidden]").val("1");
  $(link).closest(".fields").hide();
}

function add_fields(link, association, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + association, "g")
  $(link).parent().before(content.replace(regexp, new_id));
  bsmizeSelects();
}

// elastic <textarea>'s
$(function() {
  $('textarea').elastic().unbind('blur');
});

//fixed table column sizes
function fixTableHeaders() {
  $('.fixed-size, .fix-on-scroll').children().each(function() { fixElementSize($(this)); });
  $('td.multirow').siblings().andSelf().each(function() { fixElementSize($(this)); });
}
function fixElementSize(elem) {
  elem.css('width', parseInt(elem.innerWidth()) - parseInt(elem.css('paddingLeft')) - parseInt(elem.css('paddingRight')));
}

$(window).load(function() {
  //fix table headers one time after everything is loaded
  fixTableHeaders();

  //fixed table headers on scroll
  var selector = '.fix-on-scroll';
  if ($(selector).length < 1) return false;
  $(selector).each(function() {
    this.initialTopOffset = $(this).offset().top; // - parseFloat($(selector).css('marginTop').replace(/auto/, 0));
  });

  //fix headers on scroll
  $(window).scroll(function (event) {
    fixHeadersOnScroll();
  });
  //fix headers once everything is loaded (in case we're not at the top)
  fixHeadersOnScroll();

  function fixHeadersOnScroll() {
    // what the y position of the scroll is
    var y = $(window).scrollTop();
    $(selector).each(function() {
      // whether that's below the form
      if (y >= this.initialTopOffset) {
        // if so, ad the fixed class
        $(this).addClass('fixed');
      } else {
        // otherwise remove it
        $(this).removeClass('fixed');
      }
    });
  }
});

//top menu items
$(function() {
  var otherOpen = false;
  $('.has-submenu:not(.active)>a').live('click', openSubMenu);
  $('.has-submenu:not(.active)>a').live('mouseenter', openSubMenuIfOtherOpen);
  $('.has-submenu.active>a').live('click', closeAllSubMenus);
  function openSubMenu(event) {
    closeAllSubMenus();
    var button = $(this).parent().addClass('active');
    var menu = $(this).children('div');
    var h = (button.outerHeight) ? button.outerHeight() : button.height();
    menu.addClass('active')
        .click(function(e) { e.stopPropagation(); })
    $(document).one('click', {button: button}, closeSubMenu);
    otherOpen = true;
    return false;
  }
  function openSubMenuIfOtherOpen(event) {
    if (otherOpen) { $(this).trigger('click'); }
  }
  function closeSubMenu(event) {
    if (!$(event.target).hasClass("submenu") && !$(event.target).closest('.has-submenu').hasClass('active')) {
      event.data.button.removeClass('active');
      otherOpen = false;
    } else {
      $(document).one('click', {button: event.data.button}, closeSubMenu);
    }
  }
  function closeAllSubMenus() {
    $('.has-submenu').removeClass('active');
    otherOpen = false;
    return false;
  }
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require turbolinks
//= require_tree .<commit_msg>work = yes flag for rails js alert pop-ups<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require turbolinks
//= require_tree .
//= require jquery
//= require jquery_ujs<|endoftext|>


<commit_before>'use strict';
/*global global, require, process, module, baejs*/
/*jslint node: true */

var monk = require('monk');
var db;
var url;
if(process.env.SERVER_SOFTWARE==="bae/3.0"){
    url = "xPOla3Kq34SikGXnVWGUFNjj:UIZ1RYdBSiauTePP8gzoxYp9YjoQGumn@mongo.duapp.com:8908/urAFiIKlkjhtaLrPNvit";
    console.log(url +' mongodb is init');
    db = monk(url);
}else{
    url = 'mywin.int/spider';
    console.log(url +' mongodb is init');
    db = monk(url);
}
var collections = {};
collections.haha = db.get("sp_haha");
collections.youmin = db.get("sp_youmin");
collections.spider = db.get("spider");
collections.HahaJoke = db.get("HahaJoke");

module.exports.db = db;
module.exports.cns = collections;
module.exports.url = url;

<commit_msg>add   ar db<commit_after>'use strict';
/*global global, require, process, module, baejs*/
/*jslint node: true */

var monk = require('monk');
var os = require('os');
var db;
var url;
if (process.env.SERVER_SOFTWARE === "bae/3.0") {
    url = "xPOla3Kq34SikGXnVWGUFNjj:UIZ1RYdBSiauTePP8gzoxYp9YjoQGumn@mongo.duapp.com:8908/urAFiIKlkjhtaLrPNvit";
} else if (os.platform()==='linux' && os.hostname()=='jsonsong' ) {
    url = '127.0.0.1/spider';
}else{
    url = 'mywin.int/spider';
}
db = monk(url);
console.log(url + ' mongodb is init');
var collections = {};
collections.haha = db.get("sp_haha");
collections.youmin = db.get("sp_youmin");
collections.spider = db.get("spider");
collections.HahaJoke = db.get("HahaJoke");

module.exports.db = db;
module.exports.cns = collections;
module.exports.url = url;

<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//

//= require ./app/lib/core/jquery-2.2.1.js
//= require ./app/lib/core/jquery-ui-1.11.4.js
//= require ./app/lib/core/underscore-1.8.3.js

//= require ./app/lib/animations/velocity.min.js
//= require ./app/lib/animations/velocity.ui.js

//not_used= require_tree ./app/lib/spine
//= require ./app/lib/spine/spine.coffee
//= require ./app/lib/spine/ajax.coffee
//= require ./app/lib/spine/local.coffee
//= require ./app/lib/spine/route.coffee

//= require ./app/lib/flot/jquery.flot.js
//= require ./app/lib/flot/jquery.flot.selection.js

//not_used= require_tree ./app/lib/bootstrap
//= require ./app/lib/bootstrap/dropdown.js
//= require ./app/lib/bootstrap/tooltip.js
//= require ./app/lib/bootstrap/popover.js
//= require ./app/lib/bootstrap/popover-enhance.js

// modified by Felix Jan-2014
//= require ./app/lib/bootstrap/modal.js

//= require ./app/lib/bootstrap/tab.js
//= require ./app/lib/bootstrap/transition.js
//= require ./app/lib/bootstrap/button.js
//= require ./app/lib/bootstrap/collapse.js
//= require ./app/lib/bootstrap/bootstrap-timepicker.js
//= require ./app/lib/bootstrap/bootstrap-datepicker.js

//= require ./app/lib/rangy/rangy-core.js
//= require ./app/lib/rangy/rangy-classapplier.js
//= require ./app/lib/rangy/rangy-textrange.js
//= require ./app/lib/rangy/rangy-highlighter.js

//= require_tree ./app/lib/base

//= require ./app/index.coffee

// IE8 workaround for missing console.log
if (!window.console) {
  window.console = {}
}
if (!console.log) {
  console.log = function(){}
}

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

Date.prototype.getWeek = function() {
  var onejan = new Date(this.getFullYear(),0,1);
  return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}

function difference(object1, object2) {
  var changes = {};
  for (var name in object1) {
    if (name in object2) {
      if (_.isObject(object2[name]) && !_.isArray(object2[name])) {
        var diff = difference(object1[name], object2[name]);
        if (!_.isEmpty(diff)) {
            changes[name] = diff;
        }
      } else if (!_.isEqual(object1[name], object2[name])) {
        changes[name] = object2[name];
      }
    }
  }
  return changes;
}

// returns the byte length of an utf8 string
// taken from http://stackoverflow.com/questions/5515869/string-length-in-bytes-in-javascript
function byteLength(str) {
  var s = str.length
  for (var i=str.length-1; i>=0; i--) {
    var code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s+=2
    if (code >= 0xDC00 && code <= 0xDFFF) i-- //trail surrogate
  }
  return s
}

// clone, just data, no instances of objects
function clone(item, full) {

  // just return/clone false conditions
  if (!item) { return item }

  var itemType = item.constructor.name

  // IE behavior // doesn't know item.constructor.name, detect it by underscore
  if (itemType === undefined) {
    if (_.isArray(item)) {
      itemType = 'Array'
    }
    else if (_.isNumber(item)) {
      itemType = 'Number'
    }
    else if (_.isString(item)) {
      itemType = 'String'
    }
    else if (_.isBoolean(item)) {
      itemType = 'Boolean'
    }
    else if (_.isFunction(item)) {
      itemType = 'Function'
    }
    else if (_.isObject(item)) {
      itemType = 'Object'
    }
  }

  // ignore certain objects
  var acceptedInstances = [ 'Object', 'Number', 'String', 'Boolean', 'Array' ]
  if (full) {
    acceptedInstances.push('Function')
  }

  // check if item is accepted to get cloned
  if (itemType && !_.contains(acceptedInstances, itemType)) {
    console.log('no acceptedInstances', itemType, item)
    console.trace()
    return
  }

  // copy array
  var result;
  if (itemType == 'Array')  {
    result = []
    item.forEach(function(child, index, array) {
      result[index] = clone( child, full )
    });
  }

  // copy function
  else if (itemType == 'Function') {
    result = item.bind({})
  }

  // copy object
  else if (itemType == 'Object') {
    result = {}
    for(var key in item) {
      if (item.hasOwnProperty(key)) {
        result[key] = clone(item[key], full)
      }
    }
  }
  // copy others
  else {
    result = item
  }
  return result
}

// taken from https://github.com/epeli/underscore.string/blob/master/underscored.js
function underscored(str) {
  return str.trim().replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/[-\s]+/g, '_').toLowerCase();
}

function toCamelCase(str) {
  return str
    .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
    .replace(/\s/g, '')
    .replace(/^(.)/, function($1) { return $1.toUpperCase(); });
};

function isRetina(){
  if (window.matchMedia) {
    var mq = window.matchMedia("only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen  and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)");
    return (mq && mq.matches || (window.devicePixelRatio > 1));
  }
}

jQuery.event.special.remove = {
  remove: function(e) {
    if (e.handler) e.handler();
  }
};

// checkbox-replacement helper
// native checkbox focus behaviour is the following:
// tab to checkbox: :focus state and focus outline
// click on checkbox: :focus state but no focus outline
$('body').on('click', '.checkbox-replacement, .radio-replacement', function(event){
  $(event.currentTarget).find('input').addClass('is-active')
});
$('body').on('blur', '.checkbox-replacement input, .radio-replacement input', function(){
  $(this).removeClass('is-active')
});

// remove attributes by regex
// http://stackoverflow.com/questions/8968767/remove-multiple-html5-data-attributes-with-jquery
jQuery.fn.removeAttrs = function(regex) {
  return this.each(function() {
    var $this = $(this),
      names = [];
    $.each(this.attributes, function(i, attr) {
      if (attr && attr.specified && regex.test(attr.name)) {
        $this.removeAttr(attr.name);
      }
    });
  });
};

// based on jquery serializeArray
// changes
// - set type based on data('field-type')
// - also catch [disabled] params
jQuery.fn.extend( {
  serializeArrayWithType: function() {
    var r20 = /%20/g,
      rbracket = /\[\]$/,
      rCRLF = /\r?\n/g,
      rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
      rsubmittable = /^(?:input|select|textarea|keygen)/i;
    var rcheckableType = ( /^(?:checkbox|radio)$/i );
    return this.map( function() {

      // Can add propHook for "elements" to filter or add form elements
      var elements = jQuery.prop( this, "elements" );
      return elements ? jQuery.makeArray( elements ) : this;
    } )
    .filter( function() {
      var type = this.type;

      return this.name &&
        rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
        ( this.checked || !rcheckableType.test( type ) );
    } )
    .map( function( i, elem ) {
      var $elem = jQuery( this );
      var val = $elem.val();
      var type = $elem.data('field-type');

      var result;
      if ( val == null ) {

        // be sure that also null values are transfered
        // https://github.com/zammad/zammad/issues/944
        if ( $elem.prop('multiple') ) {
          result = { name: elem.name, value: null, type: type };
        }
        else {
          result = null
        }
      }
      else if ( jQuery.isArray( val ) ) {
        result = jQuery.map( val, function( val ) {
          return { name: elem.name, value: val.replace( rCRLF, "\r\n" ), type: type };
        } );
      }
      else {
        result = { name: elem.name, value: val.replace( rCRLF, "\r\n" ), type: type };
      }
      return result;
    } ).get();
  }
} );

// start application
jQuery(function(){
  new App.Run();
});
<commit_msg>Fixes #2609 - Zammad shows Customers in Owner-Selection on IE (root cause: App.ControllerForm returns no params on IE 11).<commit_after>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//

//= require ./app/lib/core/jquery-2.2.1.js
//= require ./app/lib/core/jquery-ui-1.11.4.js
//= require ./app/lib/core/underscore-1.8.3.js

//= require ./app/lib/animations/velocity.min.js
//= require ./app/lib/animations/velocity.ui.js

//not_used= require_tree ./app/lib/spine
//= require ./app/lib/spine/spine.coffee
//= require ./app/lib/spine/ajax.coffee
//= require ./app/lib/spine/local.coffee
//= require ./app/lib/spine/route.coffee

//= require ./app/lib/flot/jquery.flot.js
//= require ./app/lib/flot/jquery.flot.selection.js

//not_used= require_tree ./app/lib/bootstrap
//= require ./app/lib/bootstrap/dropdown.js
//= require ./app/lib/bootstrap/tooltip.js
//= require ./app/lib/bootstrap/popover.js
//= require ./app/lib/bootstrap/popover-enhance.js

// modified by Felix Jan-2014
//= require ./app/lib/bootstrap/modal.js

//= require ./app/lib/bootstrap/tab.js
//= require ./app/lib/bootstrap/transition.js
//= require ./app/lib/bootstrap/button.js
//= require ./app/lib/bootstrap/collapse.js
//= require ./app/lib/bootstrap/bootstrap-timepicker.js
//= require ./app/lib/bootstrap/bootstrap-datepicker.js

//= require ./app/lib/rangy/rangy-core.js
//= require ./app/lib/rangy/rangy-classapplier.js
//= require ./app/lib/rangy/rangy-textrange.js
//= require ./app/lib/rangy/rangy-highlighter.js

//= require_tree ./app/lib/base

//= require ./app/index.coffee

// IE8 workaround for missing console.log
if (!window.console) {
  window.console = {}
}
if (!console.log) {
  console.log = function(){}
}

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

Date.prototype.getWeek = function() {
  var onejan = new Date(this.getFullYear(),0,1);
  return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}

function difference(object1, object2) {
  var changes = {};
  for (var name in object1) {
    if (name in object2) {
      if (_.isObject(object2[name]) && !_.isArray(object2[name])) {
        var diff = difference(object1[name], object2[name]);
        if (!_.isEmpty(diff)) {
            changes[name] = diff;
        }
      } else if (!_.isEqual(object1[name], object2[name])) {
        changes[name] = object2[name];
      }
    }
  }
  return changes;
}

// returns the byte length of an utf8 string
// taken from http://stackoverflow.com/questions/5515869/string-length-in-bytes-in-javascript
function byteLength(str) {
  var s = str.length
  for (var i=str.length-1; i>=0; i--) {
    var code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s+=2
    if (code >= 0xDC00 && code <= 0xDFFF) i-- //trail surrogate
  }
  return s
}

// clone, just data, no instances of objects
function clone(item, full) {

  // just return/clone false conditions
  if (!item) { return item }

  var itemType = item.constructor.name

  // IE behavior // doesn't know item.constructor.name, detect it by underscore
  if (itemType === undefined) {
    if (_.isArray(item)) {
      itemType = 'Array'
    }
    else if (_.isNumber(item)) {
      itemType = 'Number'
    }
    else if (_.isString(item)) {
      itemType = 'String'
    }
    else if (_.isBoolean(item)) {
      itemType = 'Boolean'
    }
    else if (_.isFunction(item)) {
      itemType = 'Function'
    }
    else if (_.isObject(item)) {
      itemType = 'Object'
    }
  }

  // ignore certain objects
  var acceptedInstances = [ 'Object', 'Number', 'String', 'Boolean', 'Array' ]
  if (full) {
    acceptedInstances.push('Function')
  }

  // check if item is accepted to get cloned
  if (itemType && !_.contains(acceptedInstances, itemType)) {
    console.log('no acceptedInstances', itemType, item)
    console.trace()
    return
  }

  // copy array
  var result;
  if (itemType == 'Array')  {
    result = []
    item.forEach(function(child, index, array) {
      result[index] = clone( child, full )
    });
  }

  // copy function
  else if (itemType == 'Function') {
    result = item.bind({})
  }

  // copy object
  else if (itemType == 'Object') {
    result = {}
    for(var key in item) {
      if (item.hasOwnProperty(key)) {
        result[key] = clone(item[key], full)
      }
    }
  }
  // copy others
  else {
    result = item
  }
  return result
}

// taken from https://github.com/epeli/underscore.string/blob/master/underscored.js
function underscored(str) {
  return str.trim().replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/[-\s]+/g, '_').toLowerCase();
}

function toCamelCase(str) {
  return str
    .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
    .replace(/\s/g, '')
    .replace(/^(.)/, function($1) { return $1.toUpperCase(); });
};

function isRetina(){
  if (window.matchMedia) {
    var mq = window.matchMedia("only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen  and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)");
    return (mq && mq.matches || (window.devicePixelRatio > 1));
  }
}

jQuery.event.special.remove = {
  remove: function(e) {
    if (e.handler) e.handler();
  }
};

// checkbox-replacement helper
// native checkbox focus behaviour is the following:
// tab to checkbox: :focus state and focus outline
// click on checkbox: :focus state but no focus outline
$('body').on('click', '.checkbox-replacement, .radio-replacement', function(event){
  $(event.currentTarget).find('input').addClass('is-active')
});
$('body').on('blur', '.checkbox-replacement input, .radio-replacement input', function(){
  $(this).removeClass('is-active')
});

// remove attributes by regex
// http://stackoverflow.com/questions/8968767/remove-multiple-html5-data-attributes-with-jquery
jQuery.fn.removeAttrs = function(regex) {
  return this.each(function() {
    var $this = $(this),
      names = [];
    $.each(this.attributes, function(i, attr) {
      if (attr && attr.specified && regex.test(attr.name)) {
        $this.removeAttr(attr.name);
      }
    });
  });
};

// based on jquery serializeArray
// changes
// - set type based on data('field-type')
// - also catch [disabled] params
jQuery.fn.extend( {
  serializeArrayWithType: function() {
    var r20 = /%20/g,
      rbracket = /\[\]$/,
      rCRLF = /\r?\n/g,
      rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
      rsubmittable = /^(?:input|select|textarea|keygen)/i;
    var rcheckableType = ( /^(?:checkbox|radio)$/i );
    return this.map( function() {

      // We dont use jQuery.prop( this, "elements" ); here anymore
      // because it did not work out for IE 11
      var elements = $(this).find('*').filter(':input');
      return elements ? jQuery.makeArray( elements ) : this;
    } )
    .filter( function() {
      var type = this.type;

      return this.name &&
        rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
        ( this.checked || !rcheckableType.test( type ) );
    } )
    .map( function( i, elem ) {
      var $elem = jQuery( this );
      var val = $elem.val();
      var type = $elem.data('field-type');

      var result;
      if ( val == null ) {

        // be sure that also null values are transfered
        // https://github.com/zammad/zammad/issues/944
        if ( $elem.prop('multiple') ) {
          result = { name: elem.name, value: null, type: type };
        }
        else {
          result = null
        }
      }
      else if ( jQuery.isArray( val ) ) {
        result = jQuery.map( val, function( val ) {
          return { name: elem.name, value: val.replace( rCRLF, "\r\n" ), type: type };
        } );
      }
      else {
        result = { name: elem.name, value: val.replace( rCRLF, "\r\n" ), type: type };
      }
      return result;
    } ).get();
  }
} );

// start application
jQuery(function(){
  new App.Run();
});
<|endoftext|>