<commit_before>/* Pyro for Firebase*/
  // Pyro Platform Firebase:
  var pyroRef = new Firebase('http://pyro.firebaseio.com');
  // Constructor:
  function Pyro (argPyroData, errorCb) {
    //Check for existance of Firebase
    if(typeof Firebase != 'undefined' && typeof argPyroData != 'undefined') {
      if(argPyroData.hasOwnProperty('url')){
        // [TODO] Check that url is firebase
        this.url = argPyroData.url;
        this.mainRef = new Firebase(argPyroData.url);
        this.pyroRef = pyroRef;
        // Not Required variables
        if(argPyroData.hasOwnProperty('secret')) {
          this.secret = argPyroData.secret;
        }
        if(argPyroData.hasOwnProperty('name')) {
          this.name = argPyroData.name;
        } else {
          //Regex name from url
          // this.name =
        }
      } else {
        console.error('Missing firebase url.');
        if(errorCb) {
          errorCb({message:'Please provide your when running new Pyro() firebase URL'});
        }
      }
      return this;
    } else if(typeof argPyroData == 'undefined') {
      console.error('New pyro object does not include nessesary information.');
    }
    else throw Error('Firebase library does not exist. Check that firebase.js is included in your index.html file.');
    //for incorrect scope
    // if (window === this) {
    //     return new _(id);
    //  }
  }
  Pyro.prototype = {
    userSignup: function(argUserData, successCb, errorCb) {
      emailSignup(argSignupData, successCb, errorCb);
    },
    authAnonymously: function(){
      //check for auth info
      var auth = this.mainRef.getAuth();
      console.log('authAnonymously', auth);
      var currentThis = this;
      if(auth != null) {
        this.mainRef.authAnonymously(function(error, authData){
          if (error) {
            console.log('Login Failed!', error);
          } else {
            console.log('Authenticated successfully with payload:', authData);
            var anon = {uid: authData.uid, provider:authData.provider};
            currentThis.mainRef.child('users').child(authData.uid).set(anon);
          }
        });
      } else {
        //auth exists
      }
    },
    login: function(argLoginData, successCb, errorCb) {
      console.log('Pyro login:', arguments);
      var self = this;
      // check for existnace of main ref
      authWithPassword(argLoginData, self.mainRef, successCb, errorCb);
    },
    logout:function(){
      this.mainRef.unauth();
    },
    getAuth: function() {
      console.log('getAuth called');
      var authData = this.mainRef.getAuth();
      if (authData) {
        return authData;
      } else {
        console.warn('Not Authenticated');
        return null;
      }
    },
    getListByAuthor: function(argListName, callback) {
      var auth = this.getAuth();
      if(auth != null) {
        this.mainRef.child(argListName).orderByChild('author').equalTo(auth.uid).on('value', function(listSnap){
          callback(listSnap.val());
        });
      } else {
        console.warn('listByAuthor cannot load list without current user');
      }
    },
    createObject: function(argListName, argObject, callback) {
      var auth = this.getAuth();
      if(auth) {
        argObject.author = auth.uid;
      }
      var newObj = this.mainRef.child(argListName).push(argObject, function(){
        console.log('New object of type:' + argListName + ' was created successfully:', newObj);
        callback(newObj);
      })
    },
    getUser: function(callback) {
      if (this.getAuth() != null) {
        console.log('Authenticated user with email:', this.getAuth().password.email);
        var self = this;
        userById(this.getAuth().uid, self.mainRef.child('users'), function(returnedAccount){
          console.log('checkForUser loaded user:', returnedAccount);
          callback(returnedAccount);
        });
      } else {
        callback(null);
      }
    },
    getListByAuthor:function(argListName, callback){
      // [TODO] Better method of checking auth
      console.log('getListByAuthor:', argListName);
      var listRef = this.mainRef.child(argListName);
      this.getUser(function(account){
        if(account != null) {
          console.log('getInstances running for:', account);
          listRef.orderByChild('author').equalTo(account.email).limitToFirst(1).on('value', function(userInstancesSnap){
            callback(userInstancesSnap.val());
          });
        }
      });
    },
    // Functions specific to managing Pyro instances (Pyro inception)
    getInstances: function(callback) {
      // [TODO] Better method of checking auth
      var instancesRef = this.instancesRef;
      this.getUser(function(account){
        if(account != null) {
          console.log('getInstances running for:', account);
          instancesRef.orderByChild('author').equalTo(account.email).on('value', function(userInstancesSnap){
            callback(userInstancesSnap.val());
          });
        }
      });
    },
    loadInstance: function(argInstanceData, successCb, errorCb) {
      console.log('loadInstance:', argInstanceData);
      this.currentInstance = {name:argInstanceData.name}
      checkForInstance(this, function(instanceRef){
        successCb(instanceRef.val());
      }, errorCb);
    },
    instanceRef: function(argInstanceData, successCb, errorCb) {
      console.log('loadInstance:', argInstanceData);
      this.currentInstance = {name:argInstanceData.name}
      checkForInstance(this, successCb, errorCb);
    },
    // addAdminModule: function() {
    //   console.log('add admin module called', this);
    //   var self = this;
    //   if(PyroAdmin) {
    //     console.log('PyroAdmin exists... Creating instance');
    //     var pyroAdmin = new PyroAdmin(self);
    //   }
    // },
    getUserCount: function(callback){
      var self = this;
      this.mainRef.child('users').on('value', function(usersListSnap){
        callback(usersListSnap.numChildren());
      });
    },
    getUserList: function(callback){
      this.mainRef.child('users').on('value', function(usersListSnap){
        callback(usersListSnap.val());
      });
    },
    createInstance: function (argPyroData, successCb, errorCb) {
      var self = this;
      if(argPyroData.hasOwnProperty('name') && argPyroData.hasOwnProperty('secret')){
        // [TODO] Check that url is firebase
        this.mainRef = new Firebase(self.url);
        checkForInstance(this, function(returnedInstance){
          successCb(returnedInstance);
        });
        //request admin auth token

        // var xmlhttp = new XMLHttpRequest();
        //   xmlhttp.open("POST", "http://pyro-server.herokuapp.com/auth");
        //   xmlhttp.onreadystatechange = function() {
        //     if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        //       console.log('xmlresponse:', xmlhttp.responseText);
        //       // document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        //     }
        //   }
        //   xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded", true);

        //   xmlhttp.send("secret=" + this.secret);
        //Login to firebase

        // this.mainRef.authWithPassword()
      } else {
        console.log('Missing app info.');
        if(argPyroData.hasOwnProperty('name')) {
          errorCb({message:'Please enter the name of your firebase instance.'});
        } else {
          errorCb({message:'Please enter your firebase secret'})
        }
      }
    }
  };
  function loadUsersList(argRef, callback){
    argRef.child('users').on('value', function(usersListSnap){
        callback(usersListSnap);
      });
  }
  //------------ Instance action functions -----------------//
  function createNewInstance(argPyro, successCb, errorCb) {
    checkForInstance(argPyro, function(returnedInstance){
      if(returnedInstance == null) {
        instanceList.child(argPyro.name).set(instanceData, function(){
          argPyro.pyroRef = instanceList.child(argPyro.name);
          if(successCb) {
            successCb(argPyro.pyroRef);
          }
        });
      } else {
        var err = {message:'App already exists'}
        console.warn(err.message);
        errorCb(err);
      }
    });
  }

    function checkForInstance(argPyro, argName, callback) {
      // [TODO] Add user's id to author object?
      //check for app existance on pyroBase
      console.log('checkForInstance:', argPyro);
      var instanceList = argPyro.pyroRef.child("instances");
      var instanceName = argPyro.currentInstance.name;
      instanceList.orderByChild("name").equalTo(instanceName).once('value', function(usersSnap){
        console.log('usersSnap:', usersSnap);
        if(usersSnap.val() == null) {
          console.log('App does not already exist');
          // Add instance to instance list under the instance name
          callback(null);
        }
        else {
          console.log('app already exists');
          if(callback) {
            callback(usersSnap.child(instanceName));
          }
        }
      });
   }
   //------------- User ---------------//
   function User(argUserData, argMainRef) {
    console.log('NEW User');
    if(argUserData.hasOwnProperty('email')) {
      this.email = argUserData.email
    } else {
      throw Error('Email needed to create user');
    }
    this.account = checkForUser(argUserData.email, argMainRef, function(returnedAccount){
      return returnedAccount;
    })
    return this;
   }
   function getAccountOrSignup(){
    return checkForUser(argUserData, argMainRef, function(userAccount){
      if(userAccount != null) {
        return userAccount;
      } else {
        return new User(argUserData, this);
        emailSignup(argUserData, function(returnedUser){

        }, function(){

        });
      }
    })
   }

  function emailSignup(argSignupData, successCb, errorCb) {
    this.mainRef.createUser(argSignupData, function(error) {
      if (error === null) {
        console.log("User created successfully");
        // Login with new account and create profile
          currentThis.login(argSignupData, function(authData){
            createUserProfile(authData, currentThis.mainRef, function(userAccount){
              var newUser = new User(authData);
                successCb(newUser);
            });
          });
      } else {
        console.error("Error creating user:", error.message);
        errorCb(error.message);
      }
    });
  }
  function authWithPassword(argLoginData, argRef, successCb, errorCb) {
    console.log('authWithPassword',argLoginData, argRef, successCb, errorCb);
    if(argLoginData.hasOwnProperty('email') && argLoginData.hasOwnProperty('password')) {
      argRef.authWithPassword(argLoginData, function(error, authData) {
        if (error === null) {
          // user authenticated with Firebase
          console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
          // Manage presense
          setupPresence(authData.uid, argRef);
          // Add account if it doesn't already exist
          userById(authData.uid, argRef.child('users'), function(userAccount){
            successCb(userAccount);
          });
        } else {
          console.error("Error authenticating user:", error);
          errorCb(error);
        }
      });
    } else {
      // [TODO] Use error handling from Firbase.authWithPassword()
      console.error('Incorrect login info', argLoginData);
      var err = {message:'Incorrect login info'}
      errorCb('Incorrect login info:', argLoginData);
    }
  }
  function createUserProfile(argAuthData, argRef, callback) {
    console.log('createUserAccount called');
    var userRef = argRef.child('users').child(argAuthData.uid);
    var userObj = {role:10, provider: argAuthData.provider};
    if(argAuthData.provider == 'password') {
      userObj.email = argAuthData.password.email;
    }
    userRef.on('value', function(userSnap){
      if(userSnap.val() == null) {
        userObj.createdAt = Firebase.ServerValue.TIMESTAMP
        userRef.setWithPriority(userObj, userEmail, function(){
          console.log('New user account created:', userSnap.val());
          callback(userSnap.val());
        });
      } else {
        console.error('User account already exists');
        throw Error('User account already exists');
      }
    });
  }
   function setupPresence(argUserId, argMainRef) {
    console.log('setupPresence:', arguments);
    var amOnline = argMainRef.child('.info/connected');
    var onlineRef = argMainRef.child('presense').child(argUserId);
    var sessionsRef = argMainRef.child('sessions');
    var userRef = argMainRef.child('users').child(argUserId);
    var userSessionRef = argMainRef.child('users').child(argUserId).child('sessions');
    var pastSessionsRef = userSessionRef.child('past');
    amOnline.on('value', function(snapShot){
      if(snapShot.val()) {
        //user is online
        var onDisconnectRef = argMainRef.onDisconnect();
        // add session and set disconnect
        var session = sessionsRef.push({began: Firebase.ServerValue.TIMESTAMP, user:argUserId});
        session.child('ended').onDisconnect().set(Firebase.ServerValue.TIMESTAMP);
        //add correct session id to user
        // adding session id to current list under user's session
        var currentSesh = userSessionRef.child('current').push(session.name());
        // Remove session id from users current session folder
        currentSesh.onDisconnect().remove();
        // remove from presense list
        onlineRef.set(true);
        onlineRef.onDisconnect().remove();
        // Add session id to past sessions on disconnect
        // pastSessionsRef.onDisconnect().push(session.name());
      }
    });
   }
   function userById(argUserId, argUsersRef, callback) {
    console.log('userById run with id:', argUserId);
    argUsersRef.child(argUserId).on('value', function(userSnap){
      callback(userSnap.val());
    });
   }
          // Single Checking function for all user types (should be in one folder)
       // [TODO] Fix repative code within if statements
    function checkForUser(argUserData, argUsersRef, callback) {
      console.log('CheckForUser:', argUserData);
      var userEmail = 't@t.com';
      // [TODO] Change to switch statement
      // [TODO] Change to using provider folder (password if for email/password)
      if(argUserData.hasOwnProperty('email') || argUserData.hasOwnProperty('password')) {
        if (argUserData.hasOwnProperty('password')){
          userEmail = argUserData.password.email;
        }
        else if(argUserData.hasOwnProperty('email')) {
          // object contains email
          userEmail = argUserData.email;
        }
        argUsersRef.orderByChild('email').startAt(userEmail).endAt(userEmail).on("value", function(querySnapshot) {
            console.log('check for user returned:', querySnapshot.val());
            querySnapshot.forEach(function(){

            });
            callback(querySnapshot.val());
          if(querySnapshot.val() != null) {
            console.log('Usersnap:', querySnapshot.val());
          }
        });
      }
      else {
        console.error('Incorrect user info');
      }

    }<commit_msg>General Object count function added.<commit_after>/* Pyro for Firebase*/
  // Pyro Platform Firebase:
  var pyroRef = new Firebase('http://pyro.firebaseio.com');
  // Constructor:
  function Pyro (argPyroData, errorCb) {
    //Check for existance of Firebase
    if(typeof Firebase != 'undefined' && typeof argPyroData != 'undefined') {
      if(argPyroData.hasOwnProperty('url')){
        // [TODO] Check that url is firebase
        this.url = argPyroData.url;
        this.mainRef = new Firebase(argPyroData.url);
        this.pyroRef = pyroRef;
        // Not Required variables
        if(argPyroData.hasOwnProperty('secret')) {
          this.secret = argPyroData.secret;
        }
        if(argPyroData.hasOwnProperty('name')) {
          this.name = argPyroData.name;
        } else {
          //Regex name from url
          // this.name =
        }
      } else {
        console.error('Missing firebase url.');
        if(errorCb) {
          errorCb({message:'Please provide your when running new Pyro() firebase URL'});
        }
      }
      return this;
    } else if(typeof argPyroData == 'undefined') {
      console.error('New pyro object does not include nessesary information.');
    }
    else throw Error('Firebase library does not exist. Check that firebase.js is included in your index.html file.');
    //for incorrect scope
    // if (window === this) {
    //     return new _(id);
    //  }
  }
  Pyro.prototype = {
    userSignup: function(argSignupData, successCb, errorCb) {
      var self = this;
      emailSignup(argSignupData, self, successCb, errorCb);
    },
    authAnonymously: function(){
      //check for auth info
      var auth = this.mainRef.getAuth();
      console.log('authAnonymously', auth);
      var currentThis = this;
      if(auth != null) {
        this.mainRef.authAnonymously(function(error, authData){
          if (error) {
            console.log('Login Failed!', error);
          } else {
            console.log('Authenticated successfully with payload:', authData);
            var anon = {uid: authData.uid, provider:authData.provider};
            currentThis.mainRef.child('users').child(authData.uid).set(anon);
          }
        });
      } else {
        //auth exists
      }
    },
    login: function(argLoginData, successCb, errorCb) {
      console.log('Pyro login:', arguments);
      var self = this;
      // check for existnace of main ref
      authWithPassword(argLoginData, self.mainRef, successCb, errorCb);
    },
    logout:function(callback){
      this.mainRef.unauth();
      if(callback){
        callback();
      }
    },
    getAuth: function() {
      console.log('getAuth called');
      var authData = this.mainRef.getAuth();
      if (authData) {
        return authData;
      } else {
        console.warn('Not Authenticated');
        return null;
      }
    },
    getListByAuthor: function(argListName, callback) {
      var auth = this.getAuth();
      if(auth != null) {
        this.mainRef.child(argListName).orderByChild('author').equalTo(auth.uid).on('value', function(listSnap){
          callback(listSnap.val());
        });
      } else {
        console.warn('listByAuthor cannot load list without current user');
      }
    },
    createObject: function(argListName, argObject, callback) {
      var auth = this.getAuth();
      if(auth) {
        argObject.author = auth.uid;
      }
      var newObj = this.mainRef.child(argListName).push(argObject, function(){
        callback(newObj);
      });
    },
    getUser: function(callback) {
      if (this.getAuth() != null) {
        var self = this;
        userById(this.getAuth().uid, self.mainRef.child('users'), function(returnedAccount){
          callback(returnedAccount);
        });
      } else {
        callback(null);
      }
    },
    loadObject:function(argListName, argObjectId, callback){
      var listRef = this.mainRef.child(argListName);
      listRef.child(argObjectId).on('value', function(objectSnap){
        callback(objectSnap.val());
      });
    },
    instanceRef: function(argInstanceData, successCb, errorCb) {
      console.log('loadInstance:', argInstanceData);
      this.currentInstance = {name:argInstanceData.name}
      checkForInstance(this, successCb, errorCb);
    },
    getObjectCount: function(argListName, callback){
      var self = this;
      this.mainRef.child(argListName).on('value', function(usersListSnap){
        callback(usersListSnap.numChildren());
      });
    },
    getUserCount: function(callback){
      var self = this;
      this.mainRef.child('users').on('value', function(usersListSnap){
        callback(usersListSnap.numChildren());
      });
    },
    getUserList: function(callback){
      this.mainRef.child('users').on('value', function(usersListSnap){
        callback(usersListSnap.val());
      });
    },
    createInstance: function (argPyroData, successCb, errorCb) {
      var self = this;
      if(argPyroData.hasOwnProperty('name') && argPyroData.hasOwnProperty('secret')){
        // [TODO] Check that url is firebase
        this.mainRef = new Firebase(self.url);
        checkForInstance(this, function(returnedInstance){
          successCb(returnedInstance);
        });
        //request admin auth token

        // var xmlhttp = new XMLHttpRequest();
        //   xmlhttp.open("POST", "http://pyro-server.herokuapp.com/auth");
        //   xmlhttp.onreadystatechange = function() {
        //     if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        //       console.log('xmlresponse:', xmlhttp.responseText);
        //       // document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        //     }
        //   }
        //   xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded", true);

        //   xmlhttp.send("secret=" + this.secret);
        //Login to firebase

        // this.mainRef.authWithPassword()
      } else {
        console.log('Missing app info.');
        if(argPyroData.hasOwnProperty('name')) {
          errorCb({message:'Please enter the name of your firebase instance.'});
        } else {
          errorCb({message:'Please enter your firebase secret'})
        }
      }
    }
  };
  function loadUsersList(argRef, callback){
    argRef.child('users').on('value', function(usersListSnap){
        callback(usersListSnap);
      });
  }
  //------------ Instance action functions -----------------//
  function createNewInstance(argPyro, successCb, errorCb) {
    checkForInstance(argPyro, function(returnedInstance){
      if(returnedInstance == null) {
        instanceList.child(argPyro.name).set(instanceData, function(){
          argPyro.pyroRef = instanceList.child(argPyro.name);
          if(successCb) {
            successCb(argPyro.pyroRef);
          }
        });
      } else {
        var err = {message:'App already exists'}
        console.warn(err.message);
        errorCb(err);
      }
    });
  }

    function checkForInstance(argPyro, argName, callback) {
      // [TODO] Add user's id to author object?
      //check for app existance on pyroBase
      console.log('checkForInstance:', argPyro);
      var instanceList = argPyro.pyroRef.child("instances");
      var instanceName = argPyro.currentInstance.name;
      instanceList.orderByChild("name").equalTo(instanceName).once('value', function(usersSnap){
        console.log('usersSnap:', usersSnap);
        if(usersSnap.val() == null) {
          console.log('App does not already exist');
          // Add instance to instance list under the instance name
          callback(null);
        }
        else {
          console.log('app already exists');
          if(callback) {
            callback(usersSnap.child(instanceName));
          }
        }
      });
   }
   //------------- User ---------------//
   function User(argUserData, argMainRef) {
    console.log('NEW User');
    if(argUserData.hasOwnProperty('email')) {
      this.email = argUserData.email
    } else {
      throw Error('Email needed to create user');
    }
    this.account = checkForUser(argUserData.email, argMainRef, function(returnedAccount){
      return returnedAccount;
    })
    return this;
   }
   function getAccountOrSignup(){
    return checkForUser(argUserData, argMainRef, function(userAccount){
      if(userAccount != null) {
        return userAccount;
      } else {
        return new User(argUserData, this);
        emailSignup(argUserData, function(returnedUser){

        }, function(){

        });
      }
    })
   }

  function emailSignup(argSignupData, argThis, successCb, errorCb) {
    argThis.mainRef.createUser(argSignupData, function(error) {
      if (error === null) {
        console.log("User created successfully");
        // Login with new account and create profile
          argThis.login(argSignupData, function(authData){
            createUserProfile(authData, argThis.mainRef, function(userAccount){
              var newUser = new User(authData);
              successCb(newUser);
            });
          });
      } else {
        console.error("Error creating user:", error.message);
        errorCb(error);
      }
    });
  }
  function authWithPassword(argLoginData, argRef, successCb, errorCb) {
    console.log('authWithPassword',argLoginData, argRef, successCb, errorCb);
    if(argLoginData.hasOwnProperty('email') && argLoginData.hasOwnProperty('password')) {
      argRef.authWithPassword(argLoginData, function(error, authData) {
        if (error === null) {
          // user authenticated with Firebase
          console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
          // Manage presense
          setupPresence(authData.uid, argRef);
          // Add account if it doesn't already exist
          userById(authData.uid, argRef.child('users'), function(userAccount){
            successCb(userAccount);
          });
        } else {
          console.error("Error authenticating user:", error);
          errorCb(error);
        }
      });
    } else {
      // [TODO] Use error handling from Firbase.authWithPassword()
      console.error('Incorrect login info', argLoginData);
      var err = {message:'Incorrect login info'}
      errorCb('Incorrect login info:', argLoginData);
    }
  }
  function createUserProfile(argAuthData, argRef, callback) {
    console.log('createUserAccount called');
    var userRef = argRef.child('users').child(argAuthData.uid);
    var userObj = {role:10, provider: argAuthData.provider};
    if(argAuthData.provider == 'password') {
      userObj.email = argAuthData.password.email;
    }
    userRef.on('value', function(userSnap){
      if(userSnap.val() == null) {
        userObj.createdAt = Firebase.ServerValue.TIMESTAMP
        userRef.setWithPriority(userObj, userEmail, function(){
          console.log('New user account created:', userSnap.val());
          callback(userSnap.val());
        });
      } else {
        console.error('User account already exists');
        throw Error('User account already exists');
      }
    });
  }
   function setupPresence(argUserId, argMainRef) {
    console.log('setupPresence:', arguments);
    var amOnline = argMainRef.child('.info/connected');
    var onlineRef = argMainRef.child('presense').child(argUserId);
    var sessionsRef = argMainRef.child('sessions');
    var userRef = argMainRef.child('users').child(argUserId);
    var userSessionRef = argMainRef.child('users').child(argUserId).child('sessions');
    var pastSessionsRef = userSessionRef.child('past');
    amOnline.on('value', function(snapShot){
      if(snapShot.val()) {
        //user is online
        var onDisconnectRef = argMainRef.onDisconnect();
        // add session and set disconnect
        var session = sessionsRef.push({began: Firebase.ServerValue.TIMESTAMP, user:argUserId});
        session.child('ended').onDisconnect().set(Firebase.ServerValue.TIMESTAMP);
        //add correct session id to user
        // adding session id to current list under user's session
        var currentSesh = userSessionRef.child('current').push(session.name());
        // Remove session id from users current session folder
        currentSesh.onDisconnect().remove();
        // remove from presense list
        onlineRef.set(true);
        onlineRef.onDisconnect().remove();
        // Add session id to past sessions on disconnect
        // pastSessionsRef.onDisconnect().push(session.name());
      }
    });
   }
   function userById(argUserId, argUsersRef, callback) {
    console.log('userById run with id:', argUserId);
    argUsersRef.child(argUserId).on('value', function(userSnap){
      callback(userSnap.val());
    });
   }
          // Single Checking function for all user types (should be in one folder)
       // [TODO] Fix repative code within if statements
    function checkForUser(argUserData, argUsersRef, callback) {
      console.log('CheckForUser:', argUserData);
      var userEmail = 't@t.com';
      // [TODO] Change to switch statement
      // [TODO] Change to using provider folder (password if for email/password)
      if(argUserData.hasOwnProperty('email') || argUserData.hasOwnProperty('password')) {
        if (argUserData.hasOwnProperty('password')){
          userEmail = argUserData.password.email;
        }
        else if(argUserData.hasOwnProperty('email')) {
          // object contains email
          userEmail = argUserData.email;
        }
        argUsersRef.orderByChild('email').startAt(userEmail).endAt(userEmail).on("value", function(querySnapshot) {
            console.log('check for user returned:', querySnapshot.val());
            querySnapshot.forEach(function(){

            });
            callback(querySnapshot.val());
          if(querySnapshot.val() != null) {
            console.log('Usersnap:', querySnapshot.val());
          }
        });
      }
      else {
        console.error('Incorrect user info');
      }

    }<|endoftext|>


<commit_before>
// for template rendering in the views below
_.templateSettings = {
  interpolate : /\{\{(.+?)\}\}/g
};

var Response = Backbone.Model.extend({ });

var ResponseView = Backbone.View.extend({
  model: Response,

  tagName: "div",

  template: _.template( $('#response-template').html() ),

  initialize: function() {
    _.bindAll(this, 'render');
    this.model.bind('change', this.render);
    this.model.view = this;
  },

  render: function() {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
  }
});

var ResponseCollection = Backbone.Collection.extend({
  model: Response
})

// ----------------------------------------------------------------------
// Comments.
//
// Comments are children of a Wish.
// Each comment can have a collection of Responses to it

var Comment = Backbone.Model.extend({ });

var CommentCollection = Backbone.Collection.extend({
  model: Comment
});

var CommentView = Backbone.View.extend({
  model: Comment,

  tagName: "div",

  template: _.template( $('#comment-template').html() ),

  initialize: function() {
    _.bindAll(this, 'render');
    this.model.bind('change', this.render);
    this.model.view = this;
  },

  render: function() {
    var self = this;
    $(this.el).html(this.template(this.model.toJSON()));

    var responses = new ResponseCollection;
    responses.refresh(this.model.get('responses'));

    responses.each( function(response) {
      var responseView = new ResponseView({model: response});
      self.$('.responses').append(responseView.render().el);
    });
    return this;
  }
});

// ----------------------------------------------------------------------

var Wish = Backbone.Model.extend({
  url: function() {
    if (this.id.match(/random.json.*/)) {
      return '/wish/' + this.id;
    } else if (this.isNew) {
      return '/wish';
    } else {
      return '/wish/' + this.get('_id');
    }
  },

  initialize: function() {
    if (! this.get('created') ) {
      this.set({created: new Date});
    }
  },

  voteFor: function() {
    now.voteForId(this.get('_id');
  }

});

var WishView = Backbone.View.extend({
  model: Wish,

  tagName: "div",

  template: _.template( $('#wish-template').html() ),

  initialize: function() {
    _.bindAll(this, 'render');
    this.model.bind('change', this.render);
    this.model.view = this;
  },

  edit: function() {
    $(this.el).addClass("editing");
    // noodly oodly oodly
    this.input.focus();
  },

  render: function() {
    var self = this;
    $(this.el).html(this.template(this.model.toJSON()));

    var comments = new CommentCollection;
    comments.refresh(this.model.get('comments'));

    comments.each( function(comment) {
      commentView = new CommentView({model: comment});
      self.$('.comments').append(commentView.render().el);
    });

    return this;
  }
});

var WishCollection = Backbone.Collection.extend({ model: Wish });

// ----------------------------------------------------------------------
// the view for the vote page - the main application view

var NewWishApplication = Backbone.Model.extend({});

var NewWishApplicationView = Backbone.View.extend({
  model: Wish,

  el: $('#application'),

  events: {
    'click .submit': 'commit'
  },

  commit: function(event) {
    //var wish = new Wish();
    var comment = new Comment;
    var commentCollection = new CommentCollection;

    comment.set({
        text: this.$('.newWishComment textarea').val(),
        whose: this.model.get('whose')});
    commentCollection.add(comment);

    this.model.set({
        text: this.$('.newWish textarea').val(),
        comments: commentCollection});

    this.model.save();
    this.el.fadeOut(200);
    location.replace('/vote/'+this.model.get('_id'))
  }
});

var ListApplication = Backbone.Model.extend({});
var ListApplicationView = Backbone.View.extend({
  model: ListApplication,

  el: $("#application"),

  initialize: function() {
    _.bindAll(this, 'addOne', 'render');
  },

  addOne: function(wish) {
    var view = new WishView({model: wish});
    $(this.el).append(view.render().el);
  }
});

// ----------------------------------------------------------------------
// voting for one wish over another

var VoteApplication = Backbone.Model.extend({});

var VoteApplicationView = Backbone.View.extend({
  model: VoteApplication,

  el: $("#application"),

  events: {
    'click .vote': 'vote',
    'click .more': 'more',
    'click .flag': 'flag',
  },

  initialize: function() {
    this.views = [];
    _.bindAll(this, 'addOne', 'render');
    // we would fetch() here, except that the stuff's already in the dom
    // via the server template.
  },

  vote: function(event) {
    var self = this;
    var notIds = _.map(self.views, function(view) { return view.model.get('_id')} ).join(',');

    var toRemove = [];
    _.each(this.views, function(view) {
      if (!view.el.contains(event.currentTarget)) {
        // mark me for removal
        toRemove.unshift(view);
      } else {
        // vote for me!
        view.model.voteFor();
      }
    });

    // remove views that weren't voted for
    _.each(toRemove, function(r) { self.removeView(r)});

    var wish = new Wish({id: 'random.json/not/'+notIds});
    wish.fetch({
      error: function(resp) {
        console.error(resp);
      },
      success: function(model, resp) {
        self.addOne(wish);
      }
    });
  },

  more: function(e) { console.log("more: ") },
  flag: function(e) { console.log("flag: " + e) },

  removeView: function(view) {
    this.views.splice(this.views.indexOf(view), 1);
    view.remove();
  },

  addOne: function(wish) {
    var view = new WishView({model: wish});
    $(this.el).append(view.render().el);
    this.views.unshift(view);
  },
});

<commit_msg>oops typo<commit_after>
// for template rendering in the views below
_.templateSettings = {
  interpolate : /\{\{(.+?)\}\}/g
};

var Response = Backbone.Model.extend({ });

var ResponseView = Backbone.View.extend({
  model: Response,

  tagName: "div",

  template: _.template( $('#response-template').html() ),

  initialize: function() {
    _.bindAll(this, 'render');
    this.model.bind('change', this.render);
    this.model.view = this;
  },

  render: function() {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
  }
});

var ResponseCollection = Backbone.Collection.extend({
  model: Response
})

// ----------------------------------------------------------------------
// Comments.
//
// Comments are children of a Wish.
// Each comment can have a collection of Responses to it

var Comment = Backbone.Model.extend({ });

var CommentCollection = Backbone.Collection.extend({
  model: Comment
});

var CommentView = Backbone.View.extend({
  model: Comment,

  tagName: "div",

  template: _.template( $('#comment-template').html() ),

  initialize: function() {
    _.bindAll(this, 'render');
    this.model.bind('change', this.render);
    this.model.view = this;
  },

  render: function() {
    var self = this;
    $(this.el).html(this.template(this.model.toJSON()));

    var responses = new ResponseCollection;
    responses.refresh(this.model.get('responses'));

    responses.each( function(response) {
      var responseView = new ResponseView({model: response});
      self.$('.responses').append(responseView.render().el);
    });
    return this;
  }
});

// ----------------------------------------------------------------------

var Wish = Backbone.Model.extend({
  url: function() {
    if (this.id.match(/random.json.*/)) {
      return '/wish/' + this.id;
    } else if (this.isNew) {
      return '/wish';
    } else {
      return '/wish/' + this.get('_id');
    }
  },

  initialize: function() {
    if (! this.get('created') ) {
      this.set({created: new Date});
    }
  },

  voteFor: function() {
    now.voteForId(this.get('_id'));
  }

});

var WishView = Backbone.View.extend({
  model: Wish,

  tagName: "div",

  template: _.template( $('#wish-template').html() ),

  initialize: function() {
    _.bindAll(this, 'render');
    this.model.bind('change', this.render);
    this.model.view = this;
  },

  edit: function() {
    $(this.el).addClass("editing");
    // noodly oodly oodly
    this.input.focus();
  },

  render: function() {
    var self = this;
    $(this.el).html(this.template(this.model.toJSON()));

    var comments = new CommentCollection;
    comments.refresh(this.model.get('comments'));

    comments.each( function(comment) {
      commentView = new CommentView({model: comment});
      self.$('.comments').append(commentView.render().el);
    });

    return this;
  }
});

var WishCollection = Backbone.Collection.extend({ model: Wish });

// ----------------------------------------------------------------------
// the view for the vote page - the main application view

var NewWishApplication = Backbone.Model.extend({});

var NewWishApplicationView = Backbone.View.extend({
  model: Wish,

  el: $('#application'),

  events: {
    'click .submit': 'commit'
  },

  commit: function(event) {
    //var wish = new Wish();
    var comment = new Comment;
    var commentCollection = new CommentCollection;

    comment.set({
        text: this.$('.newWishComment textarea').val(),
        whose: this.model.get('whose')});
    commentCollection.add(comment);

    this.model.set({
        text: this.$('.newWish textarea').val(),
        comments: commentCollection});

    this.model.save();
    this.el.fadeOut(200);
    location.replace('/vote/'+this.model.get('_id'))
  }
});

var ListApplication = Backbone.Model.extend({});
var ListApplicationView = Backbone.View.extend({
  model: ListApplication,

  el: $("#application"),

  initialize: function() {
    _.bindAll(this, 'addOne', 'render');
  },

  addOne: function(wish) {
    var view = new WishView({model: wish});
    $(this.el).append(view.render().el);
  }
});

// ----------------------------------------------------------------------
// voting for one wish over another

var VoteApplication = Backbone.Model.extend({});

var VoteApplicationView = Backbone.View.extend({
  model: VoteApplication,

  el: $("#application"),

  events: {
    'click .vote': 'vote',
    'click .more': 'more',
    'click .flag': 'flag',
  },

  initialize: function() {
    this.views = [];
    _.bindAll(this, 'addOne', 'render');
    // we would fetch() here, except that the stuff's already in the dom
    // via the server template.
  },

  vote: function(event) {
    var self = this;
    var notIds = _.map(self.views, function(view) { return view.model.get('_id')} ).join(',');

    var toRemove = [];
    _.each(this.views, function(view) {
      if (!view.el.contains(event.currentTarget)) {
        // mark me for removal
        toRemove.unshift(view);
      } else {
        // vote for me!
        view.model.voteFor();
      }
    });

    // remove views that weren't voted for
    _.each(toRemove, function(r) { self.removeView(r)});

    var wish = new Wish({id: 'random.json/not/'+notIds});
    wish.fetch({
      error: function(resp) {
        console.error(resp);
      },
      success: function(model, resp) {
        self.addOne(wish);
      }
    });
  },

  more: function(e) { console.log("more: ") },
  flag: function(e) { console.log("flag: " + e) },

  removeView: function(view) {
    this.views.splice(this.views.indexOf(view), 1);
    view.remove();
  },

  addOne: function(wish) {
    var view = new WishView({model: wish});
    $(this.el).append(view.render().el);
    this.views.unshift(view);
  },
});

<|endoftext|>


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

}); //page loaded
<commit_msg>05_03end<commit_after>$(function() {
  'use strict';

  var dropNode = document.querySelector('.app');
  var files;

  dropNode.addEventListener('dragenter', function(e) {
    e.preventDefault();
  });

  dropNode.addEventListener('dragover', function(e) {
    e.preventDefault();
  });

  dropNode.addEventListener('drop', function(e) {
    e.preventDefault();
    files = e.dataTransfer.files; //get the files from the drop event.
    console.log(files);
  });

}); //page loaded
<|endoftext|>


<commit_before>angular.module('loc8rApp', []);

var locationListController = ['$scope', function($scope) {
    $scope.data = {
        locations: [{
            name: 'Burguer Queen',
            address: '125 High Street, Reading, RG6 1PS',
            rating: 3,
            facilities: ['Hot drinks', 'Food', 'Premium wifi'],
            distance: '0.296543',
            _id: '5370a35f2536f6785f8dfb6a'
        }, {
            name: 'Costy',
            address: '125 High Street, Reading, RG6 1PS',
            rating: 4,
            facilities: ['Hot drinks', 'Food', 'Alcoholic drinks'],
            distance: '0.7485142',
            _id: '5370a35f2536f6785f8dfb6a'
        }]
    }
}];

var _isNumeric = function(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
};

var formatDistance = function() {
    return function(distance) {
        var numDistance, unit;
        if (distance && _isNumeric(distance)) {
            if (distance > 1) {
                numDistance = parseFloat(distance).toFixed(1);
                unit = 'km';
            } else {
                numDistance = parseInt(distance * 1000, 10);
                unit = 'm';
            }
            return numDistance + unit;
        } else {
            return "?";
        }
    };
};

var ratingStars = function() {
    return {
        scope: {
            thisRating: '=rating'
        },
        templateUrl: '/javascripts/ng/views/rating-stars.html'
    };
};

angular.module('loc8rApp')
    .controller('locationListController', locationListController)
    .filter('formatDistance', formatDistance)
    .directive('ratingStars', ratingStars);
<commit_msg>Add loc8rData service<commit_after>angular.module('loc8rApp', []);

var locationListController = ['$scope', 'loc8rData', function($scope, loc8rData) {
    $scope.data = {
        locations: loc8rData
    }
}];

var _isNumeric = function(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
};

var formatDistance = function() {
    return function(distance) {
        var numDistance, unit;
        if (distance && _isNumeric(distance)) {
            if (distance > 1) {
                numDistance = parseFloat(distance).toFixed(1);
                unit = 'km';
            } else {
                numDistance = parseInt(distance * 1000, 10);
                unit = 'm';
            }
            return numDistance + unit;
        } else {
            return "?";
        }
    };
};

var ratingStars = function() {
    return {
        scope: {
            thisRating: '=rating'
        },
        templateUrl: '/javascripts/ng/views/rating-stars.html'
    };
};

var loc8rData = function() {
    return [{
        name: 'Burguer Queen',
        address: '125 High Street, Reading, RG6 1PS',
        rating: 3,
        facilities: ['Hot drinks', 'Food', 'Premium wifi'],
        distance: '0.296543',
        _id: '5370a35f2536f6785f8dfb6a'
    }, {
        name: 'Costy',
        address: '250 Low Avenue, Writing',
        rating: 4,
        facilities: ['Hot drinks', 'Food', 'Alcoholic drinks'],
        distance: '0.7485142',
        _id: '5370a35f2536f6785f8dfb6a'
    }];
}

angular.module('loc8rApp')
    .controller('locationListController', locationListController)
    .filter('formatDistance', formatDistance)
    .directive('ratingStars', ratingStars)
    .service('loc8rData', loc8rData);
<|endoftext|>


<commit_before>// Filename: router.js
define([
    'Backbone',
    'models/expense',
    'views/home'
], function(Backbone, Expense, homeview){

    var AppRouter = Backbone.Router.extend({
        routes: {
            // Define some URL routes
            "home": "home",
            "expense/new":"new_expense",
            "expense/:id":"edit_expense",
            // Default
            "":"home",
            "*other"    : "home"
        },

        home: function(){
            homeview.refresh();
        },

        edit_expense: function(id){
            require(['views/expense-details'],function(ExpenseDetailsView){
                var expense = homeview.model.get(id);
                expense.fetch({success:function() {
                    new ExpenseDetailsView({model:expense}).render();
                }})
            });
        },

        new_expense: function(id){
            require(['views/expense-details'],function(ExpenseDetailsView){
                new ExpenseDetailsView({model:new Expense()}).render();
            });
        }
    });

    var initialize = function(){
        var app_router = new AppRouter;
        Backbone.history.start();
    };
    return {
        initialize: initialize
    };
});<commit_msg>Router cleanup<commit_after>// Filename: router.js
define([
    'Backbone',
    'models/expense',
    'views/home'
], function(Backbone, Expense, homeview){

    var AppRouter = Backbone.Router.extend({
        routes: {
            // Define some URL routes
            "expense/new":"new_expense",
            "expense/:id":"edit_expense",
            // Default
            "*other"    : "home"
        },

        home: function(){
            homeview.refresh();
        },

        edit_expense: function(id){
            require(['views/expense-details'],function(ExpenseDetailsView){
                var expense = homeview.model.get(id);
                new ExpenseDetailsView({model:expense}).render();
            });
        },

        new_expense: function(){
            require(['views/expense-details'],function(ExpenseDetailsView){
                new ExpenseDetailsView({model:new Expense()}).render();
            });
        }
    });

    var initialize = function(){
        var app_router = new AppRouter;
        Backbone.history.start();
    };
    return {
        initialize: initialize
    };
});<|endoftext|>


<commit_before>function fadeGenotypeRow(id,action) {
    try {
        var genotype_row_id = 'genotype_row_'.concat(id.toString());
        var genotype_id =  'genotype_'.concat(id.toString());
        if (action == 'edit') {
            $(genotype_id).value = 1;
        }
        //Dont remove the row coz it messes up the row id
        Effect.Fade(genotype_row_id, { duration: 0.25 });
        while ($(genotype_row_id).firstChild) {
                   $(genotype_row_id).removeChild($(genotype_row_id).firstChild);
        }
    } catch(e) {
        alert(e);
    }
}

function addGenotypeRow(tableID,parent_name,action) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    row.id = 'genotype_row_'.concat(rowCount);
    var object_name = typeof(parent_name) == "undefined" ? "" : parent_name ;
    var cell1 = row.insertCell(0);
    var element1 = document.createElement("input");
    element1.type = "text";
    element1.size = 10;
    var new_id = new Date().getTime();
    element1.name = object_name.concat("[genotypes_attributes][").concat(new_id).concat("][gene_attributes][title]");
    //element1.name =  object_name.concat("[genotypes_attributes][][gene_attributes][title]");
    element1.id = object_name.replace("[","_").replace("]","").concat("_genotypes_attributes_").concat(new_id).concat("_gene_attributes_title");
    cell1.appendChild(element1);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("input");
    element2.type = "text";
    element2.size = 10;
    element2.name = object_name.concat("[genotypes_attributes][").concat(new_id).concat("][modification_attributes][title]");
    //element2.name = object_name.concat("[genotypes_attributes][][modification_attributes][title]");
    element2.id = object_name.replace("[","_").replace("]","").concat("_genotypes_attributes_").concat(new_id).concat("_modification_attributes_title");
    cell2.appendChild(element2);

    var cell3 = row.insertCell(2);
    var element3 = document.createElement("img");
    element3.src = "../images/famfamfam_silk/cross.png";
    element3.alt = "Delete"
    element3.id = "delete_genotype_".concat(rowCount.toString());
    element3.title = "Delete this entry"
    cell3.appendChild(element3);
    cell3.children[0].onclick = function() {
        fadeGenotypeRow(rowCount,action);
    }
}

function fadePhenotypeRow(id,action) {
    try {
        var phenotype_row_id = 'phenotype_row_'.concat(id.toString());
        var phenotype_id = 'phenotype_'.concat(id.toString());
        if (action == 'edit') {
            $(phenotype_id).value = 1;
        }

        //Dont remove the row coz it messes up the row id
        Effect.Fade(phenotype_row_id, { duration: 0.25 });
        while ($(phenotype_row_id).firstChild) {
            $(phenotype_row_id).removeChild($(phenotype_row_id).firstChild);
        }
    } catch(e) {
        alert(e);
    }
}

function addPhenotypeRow(tableID,parent_name,action) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    row.id = 'phenotype_row_'.concat(rowCount);
    var object_name = typeof(parent_name) == "undefined" ? "" : parent_name ;
    var cell1 = row.insertCell(0);
    var element1 = document.createElement("input");
    element1.type = "text";
    element1.size = 25;

    var new_id = new Date().getTime();
    element1.name = object_name.concat("[phenotypes_attributes][").concat(new_id).concat("][description]") ;
    //element1.name =   object_name.concat("[phenotypes_attributes][][description]") ;
    element1.id = object_name.replace("[","_").replace("]","").concat("_phenotypes_attributes_").concat(new_id).concat("_description");
    cell1.appendChild(element1);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("img");
    element2.src = "../images/famfamfam_silk/cross.png";
    element2.alt = "Delete"
    element2.id = "delete_phenotype_".concat(rowCount.toString());
    element2.title = "Delete this entry"
    cell2 .appendChild(element2);
    cell2 .children[0].onclick = function() {
        fadePhenotypeRow(rowCount,action)
    }
}

function fadeCreateStrain() {
    Effect.Fade('strain_form', { duration: 0.25 });
    Effect.Fade('existing_strains', { duration: 0.25 });
}

<commit_msg>fix bug: cannot delete empty genotypes/phenotyes of existing specimen/strain<commit_after>function fadeGenotypeRow(id,action) {
    try {
        var genotype_row_id = 'genotype_row_'.concat(id.toString());
        var genotype_id =  'genotype_'.concat(id.toString());
        if ($(genotype_id) && action == 'edit') {
            $(genotype_id).value = 1;
        }
        //Dont remove the row coz it messes up the row id
        Effect.Fade(genotype_row_id, { duration: 0.25 });
        while ($(genotype_row_id).firstChild) {
                   $(genotype_row_id).removeChild($(genotype_row_id).firstChild);
        }
    } catch(e) {
        alert(e);
    }
}

function addGenotypeRow(tableID,parent_name,action) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    row.id = 'genotype_row_'.concat(rowCount);
    var object_name = typeof(parent_name) == "undefined" ? "" : parent_name ;
    var cell1 = row.insertCell(0);
    var element1 = document.createElement("input");
    element1.type = "text";
    element1.size = 10;
    var new_id = new Date().getTime();
    element1.name = object_name.concat("[genotypes_attributes][").concat(new_id).concat("][gene_attributes][title]");
    //element1.name =  object_name.concat("[genotypes_attributes][][gene_attributes][title]");
    element1.id = object_name.replace("[","_").replace("]","").concat("_genotypes_attributes_").concat(new_id).concat("_gene_attributes_title");
    cell1.appendChild(element1);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("input");
    element2.type = "text";
    element2.size = 10;
    element2.name = object_name.concat("[genotypes_attributes][").concat(new_id).concat("][modification_attributes][title]");
    //element2.name = object_name.concat("[genotypes_attributes][][modification_attributes][title]");
    element2.id = object_name.replace("[","_").replace("]","").concat("_genotypes_attributes_").concat(new_id).concat("_modification_attributes_title");
    cell2.appendChild(element2);

    var cell3 = row.insertCell(2);
    var element3 = document.createElement("img");
    element3.src = "/images/famfamfam_silk/cross.png";
    element3.alt = "Delete"
    element3.id = "delete_genotype_".concat(rowCount.toString());
    element3.title = "Delete this entry"
    cell3.appendChild(element3);
    cell3.children[0].onclick = function() {
        fadeGenotypeRow(rowCount,action);
    }
}

function fadePhenotypeRow(id,action) {
    try {
        var phenotype_row_id = 'phenotype_row_'.concat(id.toString());
        var phenotype_id = 'phenotype_'.concat(id.toString());
        if ($(phenotype_id) && action == 'edit') {
            $(phenotype_id).value = 1;
        }

        //Dont remove the row coz it messes up the row id
        Effect.Fade(phenotype_row_id, { duration: 0.25 });
        while ($(phenotype_row_id).firstChild) {
            $(phenotype_row_id).removeChild($(phenotype_row_id).firstChild);
        }
    } catch(e) {
        alert(e);
    }
}

function addPhenotypeRow(tableID,parent_name,action) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    row.id = 'phenotype_row_'.concat(rowCount);
    var object_name = typeof(parent_name) == "undefined" ? "" : parent_name ;
    var cell1 = row.insertCell(0);
    var element1 = document.createElement("input");
    element1.type = "text";
    element1.size = 25;

    var new_id = new Date().getTime();
    element1.name = object_name.concat("[phenotypes_attributes][").concat(new_id).concat("][description]") ;
    //element1.name =   object_name.concat("[phenotypes_attributes][][description]") ;
    element1.id = object_name.replace("[","_").replace("]","").concat("_phenotypes_attributes_").concat(new_id).concat("_description");
    cell1.appendChild(element1);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("img");
    element2.src = "/images/famfamfam_silk/cross.png";
    element2.alt = "Delete"
    element2.id = "delete_phenotype_".concat(rowCount.toString());
    element2.title = "Delete this entry"
    cell2 .appendChild(element2);
    cell2 .children[0].onclick = function() {
        fadePhenotypeRow(rowCount,action)
    }
}

function fadeCreateStrain() {
    Effect.Fade('strain_form', { duration: 0.25 });
    Effect.Fade('existing_strains', { duration: 0.25 });
}

<|endoftext|>


<commit_before>/*global $:true, editors:true, libraries:true, analytics:true */
// 'use strict'; // this causes bigger issues :-\

var $library = $('#library'),
    groups = {};

$library.bind('init', function () {
  var i = 0,
    j = 0,
    k = 0,
    library = {},
    groupOrder = [],
    group = {},
    groupLabel = '',
    lcGroup = '';

  // reset
  groups = {};
  $library.empty();

  for (i = 0; i < libraries.length; i++) {
    library = libraries[i];
    groupLabel = library.group || 'Other';
    lcGroup = groupLabel.toLowerCase().replace(/[^a-z0-9]/ig, '');
    if (groupOrder.indexOf(lcGroup) === -1) {
      group = { label: groupLabel, libraries: [], key: lcGroup };
      groups[lcGroup] = group;
      groupOrder.push(lcGroup);
    } else {
      group = groups[lcGroup];
    }

    group.libraries.push(library);
  }

  var html = ['<option value="none">None</option>'];

  for (i = 0; i < groupOrder.length; i++) {
    group = groups[groupOrder[i]];
    html.push('<option value="" data-group="' + group.label + '" class="heading">-------------</option>');

    for (j = 0; j < group.libraries.length; j++) {
      library = group.libraries[j];
      html.push('<option value="' + group.key + ':' + j + '">' + library.label + '</option>');
    }
  }

  $library.html( html.join('') );
}).trigger('init');

$library.bind('change', function () {
  if (!this.value) { return; }

  var selected = this.value.split(':'),
      group = groups[selected[0]],
      library = group.libraries[selected[1]];

  analytics.library('select', group.libraries[selected[1]].label);
  insertResources(library.url);
  if (library.snippet) {
    insertSnippet(library.snippet);
  }
}).on('click', function () {
  analytics.library('open');
});

function insertResources(urls) {
  if (!$.isArray(urls)) {
    urls = [urls];
  }

  var i = 0,
      length = urls.length,
      url = '',
      code = editors.html.getCode(),
      state = { line: editors.html.editor.currentLine(),
        character: editors.html.editor.getCursor().ch,
        add: 0
      },
      html = [],
      file = '',
      resource,
      attrList,
      attrs,
      scriptDefaultAttrs = {},
      cssDefaultAttrs = { 'rel': 'stylesheet', 'type': 'text/css' };

  for (i = 0; i < length; i++) {
    url = urls[i];

    // URLs can be objects carrying desired attributes
    // The main resource (src, href) property is always 'url'
    if ($.isPlainObject(url)) {
      attrs = url;
      url = url.url;
      delete attrs.url;
    } else {
      attrs = {};
    }

    file = url.split('/').pop();

    // Introduce any default attrs and flatten into a list for insertion
    attrs = $.extend({}, (isCssFile(file) ? cssDefaultAttrs : scriptDefaultAttrs), attrs);
    attrList = '';
    for (var attr in attrs) {
      attrList += ' ' + attr + '="' + attrs[attr] + '"';
    }

    if (file && code.indexOf(file + '"')) {
      // attempt to lift out similar scripts
      if (isCssFile(file)) {
        code = code.replace(new RegExp('<link.*href=".*?/' + file + '".*?/>\n?'), '');
      } else {
        code = code.replace(new RegExp('


<commit_before>/**
* Created by cdimitzas on 16/3/2016.
*/
// -------------------------------------------------------------------------------------------------------- //
// -------- REPORT: Benefiters vs education (script) -------------------------------------------------------//
var educationData = [];

function fetchEducationDataReport(){
    $.ajax({
        url: $('body').attr('data-url') + "/benefites-VS-education-Report-get-data",
        success:function(response){
            educationData = response;
        }
    }).done(function(){
        var chart = AmCharts.makeChart("benefiter_vs_education", {
            "type": "pie",
            // "groupPercent": 10,
            "startDuration": 0,
            "theme": "light",
            "addClassNames": true,
            "legend":{
                "position":"right",
                "marginRight":100,
                "autoMargins":false,
                "fontSize": 16
            },
            "innerRadius": "30%",
            "defs": {
                "filter": [{
                    "id": "shadow",
                    "width": "200%",
                    "height": "200%",
                    "feOffset": {
                        "result": "offOut",
                        "in": "SourceAlpha",
                        "dx": 0,
                        "dy": 0
                    },
                    "feGaussianBlur": {
                        "result": "blurOut",
                        "in": "offOut",
                        "stdDeviation": 5
                    },
                    "feBlend": {
                        "in": "SourceGraphic",
                        "in2": "blurOut",
                        "mode": "normal"
                    }
                }]
            },
            "dataProvider":educationData,
            "valueField": "benefiters_count_with_this_education_title",
            "titleField": "education_title",
            "outlineAlpha": 0.4,
            "balloonText": "[[title]]
[[value]] ([[percents]]%)",
            "fontSize": 16,
            "export": {
                "enabled": true
            }
        });

        chart.addListener("init", handleInit);

        chart.addListener("rollOverSlice", function(e) {
            handleRollOver(e);
        });

        function handleInit(){
            chart.legend.addListener("rollOverItem", handleRollOver);
        }

        function handleRollOver(e){
            var wedge = e.dataItem.wedge.node;
            wedge.parentNode.appendChild(wedge);
        }
    });
}
fetchEducationDataReport();

// -------------------------------------------------------------------------------------------------------- //
// -------- REPORT: Benefiters vs doctor type needed (script) ----------------------------------------------//
var doctorData = [];

function fetchPerDoctorDataReport(){
    $.ajax({
        url: $('body').attr('data-url') + "/benefites-VS-doctor-Report-get-data",
        success:function(response){
            doctorData = response;
        }
    }).done(function(){
        var chart = AmCharts.makeChart("benefiter_vs_doctor_type", {
            "type": "serial",
            "theme": "light",
            "fontSize": 20,
            "fontFamily": "Arial",
            "marginRight": 70,
            "dataProvider": doctorData,
            "valueAxes": [{
                "axisAlpha": 0,
                "position": "left",
                //"title": Lang.get('reports.benefiters-Vs-doctors-tile'),
                "title": Lang.get('reports.benefiters-Vs-doctors-tile'),
                "fontSize": 16
            }],
            "startDuration": 1,
            "graphs": [{
                "balloonText": "[[category]]: [[value]]",
                "fillColorsField": "color",
                "fillAlphas": 0.9,
                "lineAlpha": 0.2,
                "type": "column",
                "valueField": "count_benefiters_with_same_doctor"
            }],
            "chartCursor": {
                "categoryBalloonEnabled": false,
                "cursorAlpha": 0,
                "zoomable": false
            },
            "categoryField": "doctor",
            "categoryAxis": {
                "gridPosition": "start",
                "labelRotation": 0,
                "fontSize": 16
            },
            "export": {
                "enabled": true
            }

        });
    });
}
fetchPerDoctorDataReport();

// -------------------------------------------------------------------------------------------------------- //
// -------- REPORT: Benefiters vs clinical condition type (script) -----------------------------------------//
var clinicalConditionsData = [];

function fetchClinicalConditionsDataReport() {
    $.ajax({
        url: $('body').attr('data-url') + "/benefites-VS-ClinicalConditions-Report-get-data",
        success: function (response) {
            clinicalConditionsData = response;
        }
    }).done(function () {
        var chart = AmCharts.makeChart( "benefiter_vs_clinical_conditions", {
            "type": "serial",
            "theme": "dark",
            "fontSize": 14,
            fontFamily: "Helvetica Neue",
            "dataProvider": clinicalConditionsData,
            "gridAboveGraphs": true,
            "startDuration": 1,
            "graphs": [ {
                "balloonText": "[[category]]: [[value]]",
                "fillAlphas": 0.8,
                "lineAlpha": 0.2,
                "type": "column",
                "valueField": "clinical_condition_count"
            } ],
            "chartCursor": {
                "categoryBalloonEnabled": false,
                "cursorAlpha": 0,
                "zoomable": false
            },
            "rotate": true,
            "categoryField": "clinical_condition_name",
            "categoryAxis": {
                "gridPosition": "start",
                "gridAlpha": 0,
                "tickPosition": "start",
                "tickLength": 20,
                "fontSize": 14
            },
            "valueAxes": [{
                "axisAlpha": 0,
                "position": "left",
                "title": "Αριθμός ωφελουμένων"
            }],
            "export": {
                "enabled": true
            }
        } );
    });
}
fetchClinicalConditionsDataReport();

// -------------------------------------------------------------------------------------------------------- //
// -------- REPORT: Number of visits per month (script) ----------------------------------------------------//
var medicalVisitsPerMonth = [];

function fetchmedicalVisitsPerMonthDataReport() {
    $.ajax({
        url: $('body').attr('data-url') + "/medical_visits-PER-month-Report-get-data",
        success: function (response) {
            medicalVisitsPerMonth = response;
        }
    }).done(function () {
        var chart = AmCharts.makeChart( "medical_visits_per_month", {

            type: "stock",
            "theme": "light",

            dataSets: [ {
                color: "#b0de09",
                fieldMappings: [ {
                    fromField: "visits_per_month",
                    toField: "visits_per_month"
                } ],
                dataProvider: medicalVisitsPerMonth,
                categoryField: "per_month_date"
            } ],

            panels: [ {
                showCategoryAxis: true,
                title: "Αριθμός Ιατρικών Επισκέψεων",
                eraseAll: false,
                allLabels: [ {
                    x: 0,
                    y: 115,
                    //text: "Click on the pencil icon on top-right to start drawing",
                    text: "",
                    align: "center",
                    size: 16
                } ],

                stockGraphs: [ {
                    id: "g1",
                    valueField: "visits_per_month",
                    useDataSetColors: false,
                    "bullet": "round"
                } ],

                stockLegend: {
                    valueTextRegular: " ",
                    markerType: "none"
                },

                drawingIconsEnabled: true
            } ],

            chartScrollbarSettings: {
                graph: "g1"
            },
            chartCursorSettings: {
                valueBalloonsEnabled: true
            },
            periodSelector: {
                position: "bottom",
                periods: [ {
                    period: "DD",
                    count: 10,
                    label: "10 days"
                }, {
                    period: "MM",
                    count: 1,
                    label: "1 month"
                }, {
                    period: "YYYY",
                    count: 1,
                    label: "1 year"
                }, {
                    period: "MAX",
                    label: "MAX"
                } ]
            }
        } );
    });
}
fetchmedicalVisitsPerMonthDataReport();

// -------------------------------------------------------------------------------------------------------- //
// -------- REPORT: Benefiters vs phycological support ---------------------------------------------------- //
var phycologicalSupportType = [];

function fetchBenefitersVSphycologicalSupportType(){
    $.ajax({
        url: $('body').attr('data-url') + "/benefites-VS-phycological-support-type",
        success: function (response) {
            phycologicalSupportType = response;
        }
    }).done(function () {
        var chart = AmCharts.makeChart( "benefiter_vs_phycological_support", {
            "type": "serial",
            "theme": "light",
            "dataProvider": phycologicalSupportType,
            "fontSize": 16,
            "valueAxes": [ {
                "gridColor": "#FFFFFF",
                "gridAlpha": 0.2,
                "dashLength": 0,
                //"fontSize": 16,
                "position": "left",
                "title": "Αριθμός ωφελουμένων"

            } ],
            "gridAboveGraphs": true,
            "startDuration": 1,
            "graphs": [ {
                "balloonText": "[[category]]: [[value]]",
                "fillAlphas": 0.8,
                "lineAlpha": 0.2,
                "type": "column",
                "valueField": "type_count"
            } ],
            "chartCursor": {
                "categoryBalloonEnabled": false,
                "cursorAlpha": 0,
                "zoomable": false
            },
            "rotate": true,
            "categoryField": "$phycological_support_type",
            "categoryAxis": {
                "gridPosition": "start",
                "gridAlpha": 0,
                "tickPosition": "start",
                "tickLength": 20,
                "fontSize": 16
            },
            "export": {
                "enabled": true
            }

        } );
    });
}
fetchBenefitersVSphycologicalSupportType();

// -------------------------------------------------------------------------------------------------------- //
// -------- REPORT: Registrations per month ---------------------------------------------------- //
var benefitersRegistrationsPerMonth = [];

function fetchBenefitersRegistrationsPerMonthDataReport() {
    $.ajax({
        url: $('body').attr('data-url') + "/registrations-PER-month-Report-get-data",
        success: function (response) {
            benefitersRegistrationsPerMonth = response;
        }
    }).done(function () {
        var chart = AmCharts.makeChart( "registrations_per_month", {

            type: "stock",
            "theme": "light",
            "fontSize": 16,
            dataSets: [ {
                color: "#b0de09",
                fieldMappings: [ {
                    fromField: "registrations_per_month",
                    toField: "registrations_per_month"
                } ],
                dataProvider: benefitersRegistrationsPerMonth,
                categoryField: "per_month_date"
            } ],

            panels: [ {
                showCategoryAxis: true,
                title: "Αριθμός Εγγραφών",
                eraseAll: false,
                allLabels: [ {
                    x: 0,
                    y: 115,
                    //text: "Click on the pencil icon on top-right to start drawing",
                    text: "",
                    align: "center",
                    size: 16
                } ],

                stockGraphs: [ {
                    id: "g1",
                    valueField: "registrations_per_month",
                    useDataSetColors: false,
                    "bullet": "round"
                } ],

                stockLegend: {
                    valueTextRegular: " ",
                    markerType: "none"
                },

                drawingIconsEnabled: true
            } ],

            chartScrollbarSettings: {
                graph: "g1"
            },
            chartCursorSettings: {
                valueBalloonsEnabled: true
            },
            periodSelector: {
                position: "bottom",
                periods: [ {
                    period: "DD",
                    count: 10,
                    label: "10 days"
                }, {
                    period: "MM",
                    count: 1,
                    label: "1 month"
                }, {
                    period: "YYYY",
                    count: 1,
                    label: "1 year"
                }, {
                    period: "MAX",
                    label: "MAX"
                } ]
            }
        } );
    });
}
fetchBenefitersRegistrationsPerMonthDataReport();
<commit_msg>BEN-351 removed panel icons from registrations per month stock chart<commit_after>/**
* Created by cdimitzas on 16/3/2016.
*/
// -------------------------------------------------------------------------------------------------------- //
// -------- REPORT: Benefiters vs education (script) -------------------------------------------------------//
var educationData = [];

function fetchEducationDataReport(){
    $.ajax({
        url: $('body').attr('data-url') + "/benefites-VS-education-Report-get-data",
        success:function(response){
            educationData = response;
        }
    }).done(function(){
        var chart = AmCharts.makeChart("benefiter_vs_education", {
            "type": "pie",
            // "groupPercent": 10,
            "startDuration": 0,
            "theme": "light",
            "addClassNames": true,
            "legend":{
                "position":"right",
                "marginRight":100,
                "autoMargins":false,
                "fontSize": 16
            },
            "innerRadius": "30%",
            "defs": {
                "filter": [{
                    "id": "shadow",
                    "width": "200%",
                    "height": "200%",
                    "feOffset": {
                        "result": "offOut",
                        "in": "SourceAlpha",
                        "dx": 0,
                        "dy": 0
                    },
                    "feGaussianBlur": {
                        "result": "blurOut",
                        "in": "offOut",
                        "stdDeviation": 5
                    },
                    "feBlend": {
                        "in": "SourceGraphic",
                        "in2": "blurOut",
                        "mode": "normal"
                    }
                }]
            },
            "dataProvider":educationData,
            "valueField": "benefiters_count_with_this_education_title",
            "titleField": "education_title",
            "outlineAlpha": 0.4,
            "balloonText": "[[title]]
[[value]] ([[percents]]%)",
            "fontSize": 16,
            "export": {
                "enabled": true
            }
        });

        chart.addListener("init", handleInit);

        chart.addListener("rollOverSlice", function(e) {
            handleRollOver(e);
        });

        function handleInit(){
            chart.legend.addListener("rollOverItem", handleRollOver);
        }

        function handleRollOver(e){
            var wedge = e.dataItem.wedge.node;
            wedge.parentNode.appendChild(wedge);
        }
    });
}
fetchEducationDataReport();

// -------------------------------------------------------------------------------------------------------- //
// -------- REPORT: Benefiters vs doctor type needed (script) ----------------------------------------------//
var doctorData = [];

function fetchPerDoctorDataReport(){
    $.ajax({
        url: $('body').attr('data-url') + "/benefites-VS-doctor-Report-get-data",
        success:function(response){
            doctorData = response;
        }
    }).done(function(){
        var chart = AmCharts.makeChart("benefiter_vs_doctor_type", {
            "type": "serial",
            "theme": "light",
            "fontSize": 20,
            "fontFamily": "Arial",
            "marginRight": 70,
            "dataProvider": doctorData,
            "valueAxes": [{
                "axisAlpha": 0,
                "position": "left",
                //"title": Lang.get('reports.benefiters-Vs-doctors-tile'),
                "title": Lang.get('reports.benefiters-Vs-doctors-tile'),
                "fontSize": 16
            }],
            "startDuration": 1,
            "graphs": [{
                "balloonText": "[[category]]: [[value]]",
                "fillColorsField": "color",
                "fillAlphas": 0.9,
                "lineAlpha": 0.2,
                "type": "column",
                "valueField": "count_benefiters_with_same_doctor"
            }],
            "chartCursor": {
                "categoryBalloonEnabled": false,
                "cursorAlpha": 0,
                "zoomable": false
            },
            "categoryField": "doctor",
            "categoryAxis": {
                "gridPosition": "start",
                "labelRotation": 0,
                "fontSize": 16
            },
            "export": {
                "enabled": true
            }

        });
    });
}
fetchPerDoctorDataReport();

// -------------------------------------------------------------------------------------------------------- //
// -------- REPORT: Benefiters vs clinical condition type (script) -----------------------------------------//
var clinicalConditionsData = [];

function fetchClinicalConditionsDataReport() {
    $.ajax({
        url: $('body').attr('data-url') + "/benefites-VS-ClinicalConditions-Report-get-data",
        success: function (response) {
            clinicalConditionsData = response;
        }
    }).done(function () {
        var chart = AmCharts.makeChart( "benefiter_vs_clinical_conditions", {
            "type": "serial",
            "theme": "dark",
            "fontSize": 14,
            fontFamily: "Helvetica Neue",
            "dataProvider": clinicalConditionsData,
            "gridAboveGraphs": true,
            "startDuration": 1,
            "graphs": [ {
                "balloonText": "[[category]]: [[value]]",
                "fillAlphas": 0.8,
                "lineAlpha": 0.2,
                "type": "column",
                "valueField": "clinical_condition_count"
            } ],
            "chartCursor": {
                "categoryBalloonEnabled": false,
                "cursorAlpha": 0,
                "zoomable": false
            },
            "rotate": true,
            "categoryField": "clinical_condition_name",
            "categoryAxis": {
                "gridPosition": "start",
                "gridAlpha": 0,
                "tickPosition": "start",
                "tickLength": 20,
                "fontSize": 14
            },
            "valueAxes": [{
                "axisAlpha": 0,
                "position": "left",
                "title": "Αριθμός ωφελουμένων"
            }],
            "export": {
                "enabled": true
            }
        } );
    });
}
fetchClinicalConditionsDataReport();

// -------------------------------------------------------------------------------------------------------- //
// -------- REPORT: Number of visits per month (script) ----------------------------------------------------//
var medicalVisitsPerMonth = [];

function fetchmedicalVisitsPerMonthDataReport() {
    $.ajax({
        url: $('body').attr('data-url') + "/medical_visits-PER-month-Report-get-data",
        success: function (response) {
            medicalVisitsPerMonth = response;
        }
    }).done(function () {
        var chart = AmCharts.makeChart( "medical_visits_per_month", {

            type: "stock",
            "theme": "light",

            dataSets: [ {
                color: "#b0de09",
                fieldMappings: [ {
                    fromField: "visits_per_month",
                    toField: "visits_per_month"
                } ],
                dataProvider: medicalVisitsPerMonth,
                categoryField: "per_month_date"
            } ],

            panels: [ {
                showCategoryAxis: true,
                title: "Αριθμός Ιατρικών Επισκέψεων",
                eraseAll: false,
                allLabels: [ {
                    x: 0,
                    y: 115,
                    //text: "Click on the pencil icon on top-right to start drawing",
                    text: "",
                    align: "center",
                    size: 16
                } ],

                stockGraphs: [ {
                    id: "g1",
                    valueField: "visits_per_month",
                    useDataSetColors: false,
                    "bullet": "round"
                } ],

                stockLegend: {
                    valueTextRegular: " ",
                    markerType: "none"
                },

                drawingIconsEnabled: true
            } ],

            chartScrollbarSettings: {
                graph: "g1"
            },
            chartCursorSettings: {
                valueBalloonsEnabled: true
            },
            periodSelector: {
                position: "bottom",
                periods: [ {
                    period: "DD",
                    count: 10,
                    label: "10 days"
                }, {
                    period: "MM",
                    count: 1,
                    label: "1 month"
                }, {
                    period: "YYYY",
                    count: 1,
                    label: "1 year"
                }, {
                    period: "MAX",
                    label: "MAX"
                } ]
            }
        } );
    });
}
fetchmedicalVisitsPerMonthDataReport();

// -------------------------------------------------------------------------------------------------------- //
// -------- REPORT: Benefiters vs phycological support ---------------------------------------------------- //
var phycologicalSupportType = [];

function fetchBenefitersVSphycologicalSupportType(){
    $.ajax({
        url: $('body').attr('data-url') + "/benefites-VS-phycological-support-type",
        success: function (response) {
            phycologicalSupportType = response;
        }
    }).done(function () {
        var chart = AmCharts.makeChart( "benefiter_vs_phycological_support", {
            "type": "serial",
            "theme": "light",
            "dataProvider": phycologicalSupportType,
            "fontSize": 16,
            "valueAxes": [ {
                "gridColor": "#FFFFFF",
                "gridAlpha": 0.2,
                "dashLength": 0,
                //"fontSize": 16,
                "position": "left",
                "title": "Αριθμός ωφελουμένων"

            } ],
            "gridAboveGraphs": true,
            "startDuration": 1,
            "graphs": [ {
                "balloonText": "[[category]]: [[value]]",
                "fillAlphas": 0.8,
                "lineAlpha": 0.2,
                "type": "column",
                "valueField": "type_count"
            } ],
            "chartCursor": {
                "categoryBalloonEnabled": false,
                "cursorAlpha": 0,
                "zoomable": false
            },
            "rotate": true,
            "categoryField": "$phycological_support_type",
            "categoryAxis": {
                "gridPosition": "start",
                "gridAlpha": 0,
                "tickPosition": "start",
                "tickLength": 20,
                "fontSize": 16
            },
            "export": {
                "enabled": true
            }

        } );
    });
}
fetchBenefitersVSphycologicalSupportType();

// -------------------------------------------------------------------------------------------------------- //
// -------- REPORT: Registrations per month ---------------------------------------------------- //
var benefitersRegistrationsPerMonth = [];

function fetchBenefitersRegistrationsPerMonthDataReport() {
    $.ajax({
        url: $('body').attr('data-url') + "/registrations-PER-month-Report-get-data",
        success: function (response) {
            benefitersRegistrationsPerMonth = response;
        }
    }).done(function () {
        var chart = AmCharts.makeChart( "registrations_per_month", {

            type: "stock",
            "theme": "light",
            "fontSize": 16,
            dataSets: [ {
                color: "#b0de09",
                fieldMappings: [ {
                    fromField: "registrations_per_month",
                    toField: "registrations_per_month"
                } ],
                dataProvider: benefitersRegistrationsPerMonth,
                categoryField: "per_month_date"
            } ],

            panels: [ {
                showCategoryAxis: true,
                title: "Αριθμός Εγγραφών",
                eraseAll: false,
                allLabels: [ {
                    x: 0,
                    y: 115,
                    //text: "Click on the pencil icon on top-right to start drawing",
                    text: "",
                    align: "center",
                    size: 16
                } ],

                stockGraphs: [ {
                    id: "g1",
                    valueField: "registrations_per_month",
                    useDataSetColors: false,
                    "bullet": "round"
                } ],

                stockLegend: {
                    valueTextRegular: " ",
                    markerType: "none"
                },

                drawingIconsEnabled: false
            } ],

            chartScrollbarSettings: {
                graph: "g1"
            },
            chartCursorSettings: {
                valueBalloonsEnabled: true
            },
            periodSelector: {
                position: "bottom",
                periods: [ {
                    period: "DD",
                    count: 10,
                    label: "10 days"
                }, {
                    period: "MM",
                    count: 1,
                    label: "1 month"
                }, {
                    period: "YYYY",
                    count: 1,
                    label: "1 year"
                }, {
                    period: "MAX",
                    label: "MAX"
                } ]
            }
        } );
    });
}
fetchBenefitersRegistrationsPerMonthDataReport();
<|endoftext|>


<commit_before>window.MediaListView = function(options){
    var self = this;

    var collection = null;

    var model = options['model'];
    this.model = model;

    var el = options['el'] || $('#content');
    this.el = el;

    this.has_dummy_row = false;
    var allow_drop = false;

    var default_pagination = 'endless';
    var pagination = 'pagination' in options ? options['pagination'] : default_pagination;

    var config = 0;
    var default_facets = appCollection.at(config).get('Search').Medias.facets;
    var facets = 'facets' in options ? options['facets'] : default_facets;

    var default_search_type = 'server';
    var search_type = 'search_type' in options ? options['search_type'] : default_search_type;
    var type = 'type' in options ? options['type'] : 'medialist-searchable-fixed';

    if (type.match(/playlist/)) {
        collection = model.get('pieces');
    } else {
        collection = model;
    }

    if (type.match(/sortable/)){
        allow_drop = true;
        search_type = 'client';
    }

    el.removeClass("trans Pov").addClass("container-fluid no-Pov");
    el.html(template.medialist({type: type}));
    console.log('ML2');

    var MediaListViewModel = kb.ViewModel.extend({
        constructor: function(model) {
            kb.ViewModel.prototype.constructor.apply(this, arguments);
            var self = this;
            this.editingName = ko.observable(false);
            this.nameClick = function () {
                this.editingName(true);
            }

            this.changeFocus = function () {
                if(self.name().length<=0)
                  return false;
                self.editingName(false);
            }

            this.removeItem = function (item) {
                self.collection.remove(item);
            }

            this.filter = ko.observable('');
            this.collection =  kb.collectionObservable(collection, {
                view_model: kb.ViewModel,
                filters: function(model) {
                    var filter;
                    filter = self.filter();
                    if (!filter) return false;
                    var re = new RegExp(filter,"i");
                    return ( model.get('file').search(re) < 0 &&
                             model.get('name').search(re) < 0
                    );
                },
            });

            this.total_time = ko.computed(function(){
//XXX: keep this, it tells KO to update total_time when something happens to the collection
                var x = self.collection();
                return model.pretty_duration();
            }, model);
        },

        allowDrop: allow_drop,

        dragHandler: function(item, event, ui){
            var attrs = _.clone(item.model().attributes);
            var piece = new Media.Piece(attrs);
            piece.set('checksum', attrs['_id']);
            //HACK to create piece on collection  and keep checksum
            piece.unset('_id');
            pieceList.create(piece);
            return kb.viewModel(piece)
        },
    });

    new SearchView({
        el: $('#media-search',el),
        collection: collection,
        type: search_type,
        pagination: pagination,
        facets: facets
    });

    this.view_model = new MediaListViewModel(model);

    this.editListName = function () {
        this.view_model.editingName(true);
    };

    this.destroy = function () {
        kb.release(this.view_model);
        var pieces = this.model.get('pieces');
        for( i=pieces.length-1; i>=0; i--) {
            pieces.at(i).destroy();
        }
        this.model.destroy();
        ko.cleanNode(this.el);
        this.el.html('');
    };

    this.save = function (newmodel) {
        if (newmodel) {
            this.view_model.model(newmodel);
            this.model = newmodel;
        }
        this.model.save();
    };

    this.addDummyRow = function () {
        if (this.has_dummy_row) {
            return;
        }

        $("#media-view", this.el).append('

');
        this.has_dummy_row = true;
    };

    this.onCollectionChange = function (value) {
        if (0 == value.length){
            this.addDummyRow();
        }
    };

    _.bindAll(this, 'onCollectionChange', 'addDummyRow', 'destroy', 'save', 'editListName');
    this.view_model.collection.subscribe(this.onCollectionChange);

    ko.applyBindings(this.view_model, el[0]);

    if (0 == collection.length){
        this.addDummyRow();
    }
}

<commit_msg>MediaList: fetchRelated (lazy load) pieces when displaying playlist.<commit_after>window.MediaListView = function(options){
    var self = this;

    var collection = null;

    var model = options['model'];
    this.model = model;

    var el = options['el'] || $('#content');
    this.el = el;

    this.has_dummy_row = false;
    var allow_drop = false;

    var default_pagination = 'endless';
    var pagination = 'pagination' in options ? options['pagination'] : default_pagination;

    var config = 0;
    var default_facets = appCollection.at(config).get('Search').Medias.facets;
    var facets = 'facets' in options ? options['facets'] : default_facets;

    var default_search_type = 'server';
    var search_type = 'search_type' in options ? options['search_type'] : default_search_type;
    var type = 'type' in options ? options['type'] : 'medialist-searchable-fixed';

    if (type.match(/playlist/)) {
        // In case of playlist, fetch related
        model.fetchRelated("pieces");
        collection = model.get('pieces');
    } else {
        collection = model;
    }

    if (type.match(/sortable/)){
        allow_drop = true;
        search_type = 'client';
    }

    el.removeClass("trans Pov").addClass("container-fluid no-Pov");
    el.html(template.medialist({type: type}));
    console.log('ML2');

    var MediaListViewModel = kb.ViewModel.extend({
        constructor: function(model) {
            kb.ViewModel.prototype.constructor.apply(this, arguments);
            var self = this;
            this.editingName = ko.observable(false);
            this.nameClick = function () {
                this.editingName(true);
            }

            this.changeFocus = function () {
                if(self.name().length<=0)
                  return false;
                self.editingName(false);
            }

            this.removeItem = function (item) {
                self.collection.remove(item);
            }

            this.filter = ko.observable('');
            this.collection =  kb.collectionObservable(collection, {
                view_model: kb.ViewModel,
                filters: function(model) {
                    var filter;
                    filter = self.filter();
                    if (!filter) return false;
                    var re = new RegExp(filter,"i");
                    return ( model.get('file').search(re) < 0 &&
                             model.get('name').search(re) < 0
                    );
                },
            });

            this.total_time = ko.computed(function(){
//XXX: keep this, it tells KO to update total_time when something happens to the collection
                var x = self.collection();
                return model.pretty_duration();
            }, model);
        },

        allowDrop: allow_drop,

        dragHandler: function(item, event, ui){
            var attrs = _.clone(item.model().attributes);
            var piece = new Media.Piece(attrs);
            piece.set('checksum', attrs['_id']);
            //HACK to create piece on collection  and keep checksum
            piece.unset('_id');
            pieceList.create(piece);
            return kb.viewModel(piece)
        },
    });

    new SearchView({
        el: $('#media-search',el),
        collection: collection,
        type: search_type,
        pagination: pagination,
        facets: facets
    });

    this.view_model = new MediaListViewModel(model);

    this.editListName = function () {
        this.view_model.editingName(true);
    };

    this.destroy = function () {
        kb.release(this.view_model);
        var pieces = this.model.get('pieces');
        for( i=pieces.length-1; i>=0; i--) {
            pieces.at(i).destroy();
        }
        this.model.destroy();
        ko.cleanNode(this.el);
        this.el.html('');
    };

    this.save = function (newmodel) {
        if (newmodel) {
            this.view_model.model(newmodel);
            this.model = newmodel;
        }
        this.model.save();
    };

    this.addDummyRow = function () {
        if (this.has_dummy_row) {
            return;
        }

        $("#media-view", this.el).append('

');
        this.has_dummy_row = true;
    };

    this.onCollectionChange = function (value) {
        if (0 == value.length){
            this.addDummyRow();
        }
    };

    _.bindAll(this, 'onCollectionChange', 'addDummyRow', 'destroy', 'save', 'editListName');
    this.view_model.collection.subscribe(this.onCollectionChange);

    ko.applyBindings(this.view_model, el[0]);

    if (0 == collection.length){
        this.addDummyRow();
    }
}

<|endoftext|>


<commit_before>import test from 'ava'
// import fs from 'fs' //does not work with babel + brfs
const fs = require('fs')

// these two are needed by the parser
// import Rx from 'rx'
// let Rx = require('rx')
import assign from 'fast.js/object/assign'
import makeStlStream from '../src/index'
// import parse, {outputs}'../lib/stl-parser'

test.cb('STL parser tests: can parse ascii stl files', t => {
  // this.timeout(5000)
  fs.createReadStream('./data/slotted_disk_ascii.stl', { encoding: null, highWaterMark: 512 * 1024 }) // 'binary'
    .pipe(makeStlStream())
    .on('data', function (parsedSTL) {
      t.deepEqual(parsedSTL.positions.length / 3, 864) // we divide by three because each entry is 3 long
      t.end()
    })
})

test.cb('STL parser tests: can parse binary stl files', t => {
   fs.createReadStream('./data/pr2_head_pan_bin.stl')
    .pipe(makeStlStream()) // we get a stream back
    .on('data', function (parsedSTL) {
      t.deepEqual(parsedSTL.positions.length / 3, 3000) // we divide by three because each entry is 3 long
      t.end()
    })
})

/*test.cb('STL parser tests: should handle errors gracefully', t => {
  let data = {foo: '42'}
  let stlObs = parse(data) // we get an observable back

  stlObs.forEach(undefined, function (error) {
    t.deepEqual(error.message, 'First argument to DataView constructor must be an ArrayBuffer')
    t.end()
  })
})*/
<commit_msg>feat(tests): update tests to correctly use new api<commit_after>import test from 'ava'
// import fs from 'fs' //does not work with babel + brfs
const fs = require('fs')

// these two are needed by the parser
// import Rx from 'rx'
// let Rx = require('rx')
import assign from 'fast.js/object/assign'
import makeStlStream from '../src/index'
import concat from 'concat-stream'

test.cb('STL parser tests: can parse ascii stl files', t => {
  // this.timeout(5000)
  fs.createReadStream('./data/slotted_disk_ascii.stl', { encoding: null, highWaterMark: 512 * 1024 }) // 'binary'
    .pipe(makeStlStream())
    .pipe(concat(function (data) {
      let positions = data.slice(0, data.length / 2)
      let normals = data.slice(data.length / 2)

      positions = new Float32Array(positions.buffer.slice(positions.byteOffset, positions.byteOffset + positions.byteLength)) //
      normals = new Float32Array(normals.buffer.slice(normals.byteOffset, normals.byteOffset + normals.byteLength))
      const parsedSTL = {
        positions: positions,
        normals: normals
      }
    //.on('data', function (parsedSTL) {
      t.deepEqual(parsedSTL.positions.length / 3, 864) // we divide by three because each entry is 3 long
      t.end()
    }))
})

test.cb('STL parser tests: can parse binary stl files', t => {
   fs.createReadStream('./data/pr2_head_pan_bin.stl')
    .pipe(makeStlStream()) // we get a stream back
    .pipe(concat(function (data) {
      let positions = data.slice(0, data.length / 2)
      let normals = data.slice(data.length / 2)

      positions = new Float32Array(positions.buffer.slice(positions.byteOffset, positions.byteOffset + positions.byteLength)) //
      normals = new Float32Array(normals.buffer.slice(normals.byteOffset, normals.byteOffset + normals.byteLength))
      const parsedSTL = {
        positions: positions,
        normals: normals
      }
      t.deepEqual(parsedSTL.positions.length / 3, 3000) // we divide by three because each entry is 3 long
      t.end()
    }))
    /*.on('data', function (parsedSTL) {
      t.deepEqual(parsedSTL.positions.length / 3, 3000) // we divide by three because each entry is 3 long
      t.end()
    })*/
})

/*test.cb('STL parser tests: should handle errors gracefully', t => {
  let data = {foo: '42'}
  let stlObs = parse(data) // we get an observable back

  stlObs.forEach(undefined, function (error) {
    t.deepEqual(error.message, 'First argument to DataView constructor must be an ArrayBuffer')
    t.end()
  })
})*/
<|endoftext|>