<commit_before>/**
 * entry_SHARING.js
 *
 * Module for loading styles and scripts related to single posts only
 *
 */

var $ = require( "jquery" ), // require jQuery
    q = require( "Q" ); // require the Q Promise library

require("./posts.scss");

// Set a reference for the copy blog post's title currently on the page
var getPostTitle = document.getElementById( "blog-post-title" ).innerHTML,

    // Set a reference for the URL currently in the address bar
    getPostLink = window.location.href,

    /*
     * Remove any characters that come after the URL's last slash
     * UTM code, in-page anchor links, etc.
     */
    cleanLink = getPostLink.replace( /[^/]*$/g, "" );

/*
 * "getSharingElements()"
 * LOAD/CONFIGURE SOCIAL SHARING ELEMENT FOR SINGLE POSTS
 * ====================================================================
 *
 * Load the social sharing element loads via an AJAX call wrapped in a
 * Q Promise. Once the Promise resolves, the element is placed above
 * the "more posts like this" section (the $( ".rp4wp-related-posts" )
 * element) and sharing elements are constructed on the page from
 * there.
 */
function getSharingElements() {
  // Set a reference for the sharing element
  var getSharingModule = "/wp-content/themes/kaidez-swiss/js/sharing-code.html";

  /*
   * kaidez.com uses jQuery 2.1.4, which use Promises that don't
   * conform to the Promises/A+ spec. wrap it in a Q return makes
   * jQuery spec-complaint. Note that Promises in jQuery 3.x are
   * Promises/A+ compliant.
   */
  return q( $.ajax({
    // Load in the sharing module
    url: getSharingModule,
    type: "GET"

  // Do things after the Promise resolves
  })).then( function ( data ) {

    loadSharingAd();

    // Load sharing element above the "more posts like this" section
    $( ".rp4wp-related-posts" ).before( data );

    // Reference the Twitter link that's on the web page by this point
    var linkElement = document.getElementById( "tweet-this-post" );

    // Set the Twitter links href attribute to be the cleaned up URL
    linkElement.setAttribute( "href", cleanLink );

    /*
     * Object that contains properties for the Facebook & Google+ links
     * These links are already on the web page at this point
     * "getLink" is the id of the link already on the page
     */
    var socialSiteLinks = {
      "facebook" : {
        "getLink": "facebook-share-link",
        "linkHandle": "http://www.facebook.com/sharer.php?u="
      },
      "googlePlus": {
        "getLink": "googleplus-share-link",
        "linkHandle": "https://plus.google.com/share?url="
      }
    };

    // Loop through object with the ES5 {}.getOwnPropertyNames() method
    Object.getOwnPropertyNames( socialSiteLinks ).forEach( function( value ) {

      /*
       * Do the following on each loop iteration:
       *
       * -get object's "getLink" property & store it in linkId var
       * -get object's "linkHandle" property & store it in pageLink var
       * -let the "getLink" property be the id of the button
       */
      var linkId = socialSiteLinks[value].getLink,
          pageLink = socialSiteLinks[value].linkHandle,
          pageElement = document.getElementById( linkId );

      // Set the "title" property of the link to be the blog post title
      pageElement.setAttribute( "title", getPostTitle );

      // Let the href property look one way for FB and another for G+
      if( linkId === "facebook-share-link" ) {
        pageElement.setAttribute( "href", pageLink + getPostLink + "&t=" + getPostTitle );
      } else {
        pageElement.setAttribute( "href", pageLink + getPostLink );
      }

    });
  }, function ( xhr ) {
    // If the Promise fails, send a certain console message
    console.log( "The social sharing links failed to load...you may needs refresh the page." );
  });
} // end "getSharingElements()"

// Wait for the DOM to be ready before loading content
document.addEventListener( "DOMContentLoaded", function( event ) {

  "use strict";

  var

      // jQuery reference to the window object
      $window = $( window ),

      // The sharing element's top position...has value
      sharingElementTopPosition = $( ".rp4wp-related-posts" ).offset().top,

      // How much to subtract from the sharing element's top position
      reduceSharingElementTopPosition = 500;

  /*
   * Use jQuery.scroll() to do stuff as the browser window's top
   * position changes
   */
  $window.scroll( function(){
    // Start doing stuff...

    // Get the browser window's top position with jQuery.scrollTop()
    var windowTopPosition = $window.scrollTop();

    /*
     * Check if the window's current top position is greater than or
     * equal to 500 pixels LESS of whatever the sharing element's
     * current top position is.
     */
    if( windowTopPosition >= sharingElementTopPosition - reduceSharingElementTopPosition ) {

      /*
       * If it is, AJAX in the sharing element using the
       * getSharingElements() function
       */
      getSharingElements();

      /*
       * We're still watching window scrolling at this point, so the
       * sharing element will load in again and again if we keep
       * scrolling. Stop watching window scrolling with jQuery.off().
       */
      $window.off( "scroll" );
    }
  });

}); // end "document.addEventListener()"

// END LOAD & CONFIGURE SOCIAL SHARING ELEMENT FOR SINGLE POSTS

// Start loading the big WP ad by the sharing code
// Need an enquire function...can I start making a reusable one?
function loadSharingAd() {
  var sharingAdCode = $( "#sharing-ad" );
}

/*
 * START CLICK-TO-TWEET CODE
 * ====================================================================
 *
 * If the "click-to-tweet" link is clicked, create a pop-up interface
 * for Tweeting out the link.
 */

/*
 * The "click-to-tweet" link is not on the page on initial page load,
 * so $.click() wont work on it. Instead, use $.delegate() to bind a
 * click event to the link.
 * Based on cool-ass code at:
 * http://gpiot.com/blog/elegant-twitter-share-button-and-dialog-with-jquery/
 * Cool Regex code:
 * http://stackoverflow.com/questions/4058923/get-all-characters-after-character
 * http://stackoverflow.com/questions/3780696/javascript-string-replace-with-regex-to-strip-off-illegal-characters
 */
$( "body" ).delegate( "#tweet-this-post", "click", function( event ){

  // Don't load the link in the address bar when clicked.
  event.preventDefault();

  // Grab the "click-to-tweet" link's "href" attribute when clicked.
  var tweetedLink = this.getAttribute( "href" );

  /*
   * Open the popup window and setup the Tweet-out interface. A link
   * needs to be built out that contains both the "click-to-tweet"
   * link's "href" attribute and the title of the blog post. The
   * latter is stored in the "getPostTitle" variable.
   */
  window.open( "http://twitter.com/intent/tweet?url=" + tweetedLink + "&text=" + getPostTitle + "&via=kaidez&", "twitterwindow", "height=450, width=550, toolbar=0, location=0, menubar=0, directories=0, scrollbars=0" );

});
// END CLICK-TO-TWEET CODE<commit_msg>add whitespace<commit_after>/**
 * entry_SHARING.js
 *
 * Module for loading styles and scripts related to single posts only
 *
 */

var $ = require( "jquery" ), // require jQuery
    q = require( "Q" ); // require the Q Promise library

require("./posts.scss");

// Set a reference for the copy blog post's title currently on the page
var getPostTitle = document.getElementById( "blog-post-title" ).innerHTML,

    // Set a reference for the URL currently in the address bar
    getPostLink = window.location.href,

    /*
     * Remove any characters that come after the URL's last slash
     * UTM code, in-page anchor links, etc.
     */
    cleanLink = getPostLink.replace( /[^/]*$/g, "" );

/*
 * "getSharingElements()"
 * LOAD/CONFIGURE SOCIAL SHARING ELEMENT FOR SINGLE POSTS
 * ====================================================================
 *
 * Load the social sharing element loads via an AJAX call wrapped in a
 * Q Promise. Once the Promise resolves, the element is placed above
 * the "more posts like this" section (the $( ".rp4wp-related-posts" )
 * element) and sharing elements are constructed on the page from
 * there.
 */
function getSharingElements() {

  // Set a reference for the sharing element
  var getSharingModule = "/wp-content/themes/kaidez-swiss/js/sharing-code.html";

  /*
   * kaidez.com uses jQuery 2.1.4, which use Promises that don't
   * conform to the Promises/A+ spec. wrap it in a Q return makes
   * jQuery spec-complaint. Note that Promises in jQuery 3.x are
   * Promises/A+ compliant.
   */
  return q( $.ajax({
    // Load in the sharing module
    url: getSharingModule,
    type: "GET"

  // Do things after the Promise resolves
  })).then( function ( data ) {

    loadSharingAd();

    // Load sharing element above the "more posts like this" section
    $( ".rp4wp-related-posts" ).before( data );

    // Reference the Twitter link that's on the web page by this point
    var linkElement = document.getElementById( "tweet-this-post" );

    // Set the Twitter links href attribute to be the cleaned up URL
    linkElement.setAttribute( "href", cleanLink );

    /*
     * Object that contains properties for the Facebook & Google+ links
     * These links are already on the web page at this point
     * "getLink" is the id of the link already on the page
     */
    var socialSiteLinks = {
      "facebook" : {
        "getLink": "facebook-share-link",
        "linkHandle": "http://www.facebook.com/sharer.php?u="
      },
      "googlePlus": {
        "getLink": "googleplus-share-link",
        "linkHandle": "https://plus.google.com/share?url="
      }
    };

    // Loop through object with the ES5 {}.getOwnPropertyNames() method
    Object.getOwnPropertyNames( socialSiteLinks ).forEach( function( value ) {

      /*
       * Do the following on each loop iteration:
       *
       * -get object's "getLink" property & store it in linkId var
       * -get object's "linkHandle" property & store it in pageLink var
       * -let the "getLink" property be the id of the button
       */
      var linkId = socialSiteLinks[value].getLink,
          pageLink = socialSiteLinks[value].linkHandle,
          pageElement = document.getElementById( linkId );

      // Set the "title" property of the link to be the blog post title
      pageElement.setAttribute( "title", getPostTitle );

      // Let the href property look one way for FB and another for G+
      if( linkId === "facebook-share-link" ) {
        pageElement.setAttribute( "href", pageLink + getPostLink + "&t=" + getPostTitle );
      } else {
        pageElement.setAttribute( "href", pageLink + getPostLink );
      }

    });
  }, function ( xhr ) {
    // If the Promise fails, send a certain console message
    console.log( "The social sharing links failed to load...you may needs refresh the page." );
  });
} // end "getSharingElements()"

// Wait for the DOM to be ready before loading content
document.addEventListener( "DOMContentLoaded", function( event ) {

  "use strict";

  var

      // jQuery reference to the window object
      $window = $( window ),

      // The sharing element's top position...has value
      sharingElementTopPosition = $( ".rp4wp-related-posts" ).offset().top,

      // How much to subtract from the sharing element's top position
      reduceSharingElementTopPosition = 500;

  /*
   * Use jQuery.scroll() to do stuff as the browser window's top
   * position changes
   */
  $window.scroll( function(){
    // Start doing stuff...

    // Get the browser window's top position with jQuery.scrollTop()
    var windowTopPosition = $window.scrollTop();

    /*
     * Check if the window's current top position is greater than or
     * equal to 500 pixels LESS of whatever the sharing element's
     * current top position is.
     */
    if( windowTopPosition >= sharingElementTopPosition - reduceSharingElementTopPosition ) {

      /*
       * If it is, AJAX in the sharing element using the
       * getSharingElements() function
       */
      getSharingElements();

      /*
       * We're still watching window scrolling at this point, so the
       * sharing element will load in again and again if we keep
       * scrolling. Stop watching window scrolling with jQuery.off().
       */
      $window.off( "scroll" );
    }
  });

}); // end "document.addEventListener()"

// END LOAD & CONFIGURE SOCIAL SHARING ELEMENT FOR SINGLE POSTS

// Start loading the big WP ad by the sharing code
// Need an enquire function...can I start making a reusable one?
function loadSharingAd() {
  var sharingAdCode = $( "#sharing-ad" );
}

/*
 * START CLICK-TO-TWEET CODE
 * ====================================================================
 *
 * If the "click-to-tweet" link is clicked, create a pop-up interface
 * for Tweeting out the link.
 */

/*
 * The "click-to-tweet" link is not on the page on initial page load,
 * so $.click() wont work on it. Instead, use $.delegate() to bind a
 * click event to the link.
 * Based on cool-ass code at:
 * http://gpiot.com/blog/elegant-twitter-share-button-and-dialog-with-jquery/
 * Cool Regex code:
 * http://stackoverflow.com/questions/4058923/get-all-characters-after-character
 * http://stackoverflow.com/questions/3780696/javascript-string-replace-with-regex-to-strip-off-illegal-characters
 */
$( "body" ).delegate( "#tweet-this-post", "click", function( event ){

  // Don't load the link in the address bar when clicked.
  event.preventDefault();

  // Grab the "click-to-tweet" link's "href" attribute when clicked.
  var tweetedLink = this.getAttribute( "href" );

  /*
   * Open the popup window and setup the Tweet-out interface. A link
   * needs to be built out that contains both the "click-to-tweet"
   * link's "href" attribute and the title of the blog post. The
   * latter is stored in the "getPostTitle" variable.
   */
  window.open( "http://twitter.com/intent/tweet?url=" + tweetedLink + "&text=" + getPostTitle + "&via=kaidez&", "twitterwindow", "height=450, width=550, toolbar=0, location=0, menubar=0, directories=0, scrollbars=0" );

});
// END CLICK-TO-TWEET CODE<|endoftext|>


<commit_before>/**
 * entry_SHARING.js
 *
 * Module for loading styles and scripts related to single posts only
 *
 */

 var $ = require( "jquery" ), // require jQuery
     Q = require( "Q" ); // require the Q Promise library

// Load in asynchronous code for Facebook and Google+ sharing
require("./config/async-sharing");

/* Load in styles related to single posts only
 * "posts.less" contains styles for all posts
 * "prism-styles.css" is only for posts with code samples
 *
 * TODO: see if there's away to distinguish posts without code samples,
 * then have "prism-styles.css" just load onto those pages
 */
require( "./posts.less" );
require("./config/prism-styles.css");

// Set a
var getPostTitle = document.getElementById( "blog-post-title" ).innerHTML,
    getPostLink = window.location.href,
    cleanLink = getPostLink.replace( /[^/]*$/g, "" );

// START FACEBOOK & GOOGLE+ SHARING CODE

document.addEventListener("DOMContentLoaded", function(event) {

  var getData = "/wp-content/themes/kaidez-swiss/js/sharing-code.html";

  return Q($.ajax({
    url: getData,
    type: "GET"
   })).then(function (data) {

    $(".rp4wp-related-posts").before( data );

    var linkElement = document.getElementById( "tweet-this-post" ),
        socialSiteLinks;

    linkElement.setAttribute( "href", cleanLink );

    socialSiteLinks = {
      "facebook" : {
        "getLink": "facebook-share-link",
        "linkHandle": "http://www.facebook.com/sharer.php?u="
      },
      "googlePlus": {
        "getLink": "googleplus-share-link",
        "linkHandle": "https://plus.google.com/share?url="
      }
    };

    Object.getOwnPropertyNames( socialSiteLinks ).forEach(function( value ) {
      var linkId = socialSiteLinks[value].getLink,
          pageLink = socialSiteLinks[value].linkHandle,
          pageElement = document.getElementById( linkId );

      pageElement.setAttribute( "title", getPostTitle );

      if( linkId === "facebook-share-link" ) {
        pageElement.setAttribute( "href", pageLink + getPostLink + "&t=" + getPostTitle );
      } else {
        pageElement.setAttribute( "href", pageLink + getPostLink );
      }
    });
  }, function (xhr) {
   console.log("The social sharing links failed to load...you may needs refresh the page.");
  });

});
// END FACEBOOK & GOOGLE+ SHARING CODE

// START "CLICK-TO-TWEET" CODE
// Bind jQuery.click() to the Tweet link
$( "body" ).delegate( "#tweet-this-post", "click", function( event ){
  event.preventDefault();

  var tweetedLink = this.getAttribute( "href" );

  window.open( "http://twitter.com/intent/tweet?url=" + tweetedLink + "&text=" + getPostTitle + "&via=kaidez&", "twitterwindow", "height=450, width=550, toolbar=0, location=0, menubar=0, directories=0, scrollbars=0" );

});
// END "CLICK-TO-TWEET" CODE<commit_msg>add whitespace<commit_after>/**
 * entry_SHARING.js
 *
 * Module for loading styles and scripts related to single posts only
 *
 */

 var $ = require( "jquery" ), // require jQuery
     Q = require( "Q" ); // require the Q Promise library

// Load in asynchronous code for Facebook and Google+ sharing
require("./config/async-sharing");

/* Load in styles related to single posts only
 * "posts.less" contains styles for all posts
 * "prism-styles.css" is only for posts with code samples
 *
 * TODO: see if there's away to distinguish posts without code samples,
 * then have "prism-styles.css" just load onto those pages
 */
require( "./posts.less" );
require( "./config/prism-styles.css" );

// Set a
var getPostTitle = document.getElementById( "blog-post-title" ).innerHTML,
    getPostLink = window.location.href,
    cleanLink = getPostLink.replace( /[^/]*$/g, "" );

// START FACEBOOK & GOOGLE+ SHARING CODE

document.addEventListener( "DOMContentLoaded", function( event ) {

  var getData = "/wp-content/themes/kaidez-swiss/js/sharing-code.html";

  return Q( $.ajax({
    url: getData,
    type: "GET"
   })).then(function ( data ) {

    $( ".rp4wp-related-posts" ).before( data );

    var linkElement = document.getElementById( "tweet-this-post" ),
        socialSiteLinks;

    linkElement.setAttribute( "href", cleanLink );

    socialSiteLinks = {
      "facebook" : {
        "getLink": "facebook-share-link",
        "linkHandle": "http://www.facebook.com/sharer.php?u="
      },
      "googlePlus": {
        "getLink": "googleplus-share-link",
        "linkHandle": "https://plus.google.com/share?url="
      }
    };

    Object.getOwnPropertyNames( socialSiteLinks ).forEach( function( value ) {
      var linkId = socialSiteLinks[value].getLink,
          pageLink = socialSiteLinks[value].linkHandle,
          pageElement = document.getElementById( linkId );

      pageElement.setAttribute( "title", getPostTitle );

      if( linkId === "facebook-share-link" ) {
        pageElement.setAttribute( "href", pageLink + getPostLink + "&t=" + getPostTitle );
      } else {
        pageElement.setAttribute( "href", pageLink + getPostLink );
      }
    });
  }, function ( xhr ) {
   console.log("The social sharing links failed to load...you may needs refresh the page.");
  });

});
// END FACEBOOK & GOOGLE+ SHARING CODE

// START "CLICK-TO-TWEET" CODE
// Bind jQuery.click() to the Tweet link
$( "body" ).delegate( "#tweet-this-post", "click", function( event ){
  event.preventDefault();

  var tweetedLink = this.getAttribute( "href" );

  window.open( "http://twitter.com/intent/tweet?url=" + tweetedLink + "&text=" + getPostTitle + "&via=kaidez&", "twitterwindow", "height=450, width=550, toolbar=0, location=0, menubar=0, directories=0, scrollbars=0" );

});
// END "CLICK-TO-TWEET" CODE<|endoftext|>


<commit_before>var _ = require('lodash')
var Chance = require('chance')
var random_name = require('node-random-name');
var Firebase = require('firebase');
var ref_Group = new Firebase("https://wetravel.firebaseio.com/Groups")
var ref_User = new Firebase("https://wetravel.firebaseio.com/Users")
//get the current time for message useage
var d = new Date()
var hour = d.getHours()
var minute = d.getMinutes()
var time = hour+':'+minute

// simualate a random person entering, staying for a duration, and leaving
function simulate(){
  // random user name
  var chance = new Chance()
  var name = random_name()
  var duration = 1 + 5 * Math.random()
  var user = {
    name: name,
    status: 'online'
  }
   login(user)
   joinGroup(user, 'CS_Grad_Trip')

  // random message
  var message = chance.word() + " " + chance.word() + " " +chance.word()
  // random schedule
  var Day = "Day" + Math.floor(duration).toString()
  var budget = Math.random()*50+1
  var place = chance.word() + " " + chance.word()
  var startTime  = Math.floor(Math.random()*22)+1
  var endTime  = startTime+2
  var time = startTime.toString() + ':' + endTime.toString()
  var traffic = ['Rent car', 'Taxi', 'Bus', 'Metro', 'Bike', 'Walk']
  var transportation = traffic[Math.floor(Math.random()*traffic.length)]
  var schedule = {
    Day: Day,
    budget: budget,
    place: place,
    time: time,
    transportation: transportation
  }
  setTimeout(function(){
    chat('CS_Grad_Trip',user, message, time)
    addSchedule('CS_Grad_Trip', schedule)

    canvas('CS_Grad_Trip')
    //clickonMap()
  }, duration * 1000)

  // simulate this person login
  // simulate this person logout after 'duration' seconds
  setTimeout(function(){
    //clickonMap()
   }, duration * 1000)

  // simulate this person login
  // simulate this person logout after 'duration' seconds
   setTimeout(function(){
    logout(user)
  }, duration * 1000)

}
function login(user){
  console.log('login', user)
  ref_User.once('value', function(snapshot){
    var users = snapshot.val()
    users = Object.keys(users)
    if (user in users){
      ref_User.child(user.name).update({status:online})
    }
    else{
      ref_User.child(user.name).set({
        name: user.name,
        status: user.status
      })
    }
  })

}

function logout(user){
  console.log('logout', user)
  ref_User.child(user.name).update({status: 'offline'});
}

function joinGroup(user, group){
  console.log('join',user.name, group)
  ref_Group.child(group).child('member').child(user.name).set({
    name: user.name,
    status: user.status
  })
}

function chat(group,user, message, time){
  console.log('chat', group,user,message,time)
  var chance = new Chance()
  ref_Group.child(group).child('Message').child(chance.word()).set({
  message: message,
  time: time,
  username:user.name
  })
}

function canvas(group){
  var x = Math.floor(Math.random() * (120 + 1));
  var y = Math.floor(Math.random() * (105 + 1));
  var curColor = randColor();
  var curSize = randSize();
  var curTool = randTool();
  if(curTool == 'Eraser'){
    curColor = 'fff';
    ref_Group.child(group).child('drawing').child(x+':'+y).set({
      curColor: curColor,
      curSize : curSize,
      curTool : curTool
    })
  }else if(curTool == 'Refresh'){
    ref_Group.child(group).child('drawing').remove();
  }else{
    ref_Group.child(group).child('drawing').child(x+':'+y).set({
      curColor: curColor,
      curSize : curSize,
      curTool : curTool
    })
  }
  console.log('canvas', x, ':', y, 'color:', curColor, 'size:', curSize, 'tool:', curTool)
}

function randSize(){
  var size = [
    'Small',
    'Medium',
    'Large'
  ];
  var rand = Math.floor(Math.random()*size.length);
  return size[rand]
}

function randTool(){
  var tool = [
    'Eraser',
    'Marker',
    'Refresh'
  ];
  var rand = Math.floor(Math.random()*tool.length);
  return tool[rand]
}

function randColor(){
  var colors = ["fff","000","f00","0f0","00f","88f","f8d","f88","f05","f80","0f8","cf0","08f","408","ff8","8ff", "aed081", "eee"];

  var rand = Math.floor(Math.random()*colors.length);
  return colors[rand]
}

function addSchedule(group, schedule){
  console.log('schedule', schedule)
  ref_Group.child(group).child('Schedule').once('value', function(snapshot){
    var D = snapshot.val()
    var key = Object.keys(D)
    if (key.indexOf(schedule.Day)>-1){
      ref_Group.child(group).child('Schedule').child(schedule.Day).child(schedule.time).set({
        budget: schedule.budget,
        place: schedule.place,
        transportation: schedule.transportation
      })
    }
    else{
      ref_Group.child(group).child('Schedule').child(schedule.Day).set(
        schedule.time)
      ref_Group.child(group).child('Schedule').child(schedule.Day).child(schedule.time).set({
          budget: schedule.budget,
          place: schedule.place,
          transportation: schedule.transportation
        })
    }
  })
}
// function clickonMap()
///-----------------------------------------------------------------------
// function Make_Group(groupName, key, userName){

//   ref_Group.child(groupName).set({
//     GroupName: groupName
//     Activation_key: key
//     Message: {
//       time: "Welcome to "+groupName
//     }
//     member: {
//       userName: userName
//       current_status: online
//     }
//   })
// }
// function Join_Group(groupName, key, userName){
//   ref_Group.child(groupName).child(Activation_key).once('value',function(snapshot){
//     var gold_answer = snapshot.value()
//   })
//   if(key != gold_answer){
//     alert('wrong password')
//   }
//   else{
//     ref_Group.child(groupName).child(member).child(userName).set({
//       userName: userName
//       current_status: online
//     })
//     if (ref_User.child(userName).child('groups')!=null){
//       ref_User.child(userName).child('groups').once('value',function(snapshot){
//         var key = snapshot.val()
//         key.push(groupName)
//         ref_User.child(userName).child('groups').set(key)
//       })
//     }
//     else{
//       ref_User.child(userName).child('groups').set([groupName])
//     }

// }

// run each second
setInterval(simulate, 2000)<commit_msg>milestone<commit_after>var _ = require('lodash')
var Chance = require('chance')
var random_name = require('node-random-name');
var Firebase = require('firebase');
var ref_Group = new Firebase("https://wetravel.firebaseio.com/Groups")
var ref_User = new Firebase("https://wetravel.firebaseio.com/Users")
//get the current time for message useage
var d = new Date()
var hour = d.getHours()
var minute = d.getMinutes()
var time = hour+':'+minute

var radius = 0.03

var city_location = {
  lat: 35.74,
  lon: 40.65
}

// simualate a random person entering, staying for a duration, and leaving
function simulate(){
  // random user name
  var chance = new Chance()
  var name = random_name()
  var duration = 1 + 5 * Math.random()
  var user = {
    name: name,
    status: 'online'
  }
   login(user)
   joinGroup(user, 'CS_Grad_Trip')

  // random message
  var message = chance.word() + " " + chance.word() + " " +chance.word()
  // random schedule
  var Day = "Day" + Math.floor(duration).toString()
  var budget = Math.random()*50+1
  var place = chance.word() + " " + chance.word()
  var startTime  = Math.floor(Math.random()*22)+1
  var endTime  = startTime+2
  var time = startTime.toString() + ':' + endTime.toString()
  var traffic = ['Rent car', 'Taxi', 'Bus', 'Metro', 'Bike', 'Walk']
  var transportation = traffic[Math.floor(Math.random()*traffic.length)]
  var schedule = {
    Day: Day,
    budget: budget,
    place: place,
    time: time,
    transportation: transportation
  }
  var map_point = {
    name: chance.word() + " " + chance.word(),
  lat: city_location.lat + radius * (Math.random() - 0.5) * 2,
    lon: city_location.lon + radius * (Math.random() - 0.5) * 2,
    message: chance.word() + " " + chance.word()
  }
  setTimeout(function(){
    chat('CS_Grad_Trip',user, message, time)
    addSchedule('CS_Grad_Trip', schedule)

    canvas('CS_Grad_Trip')
    clickOnMap('CS_Grad_Trip', map_point)
  }, duration * 1000)

  // simulate this person login
  // simulate this person logout after 'duration' seconds
  setTimeout(function(){
    removeFromMap('CS_Grad_Trip', map_point)
   }, duration * 1000)

  // simulate this person login
  // simulate this person logout after 'duration' seconds
   setTimeout(function(){
    logout(user)
  }, duration * 1000)

}
function login(user){
  console.log('login', user)
  ref_User.once('value', function(snapshot){
    var users = snapshot.val()
    users = Object.keys(users)
    if (user in users){
      ref_User.child(user.name).update({status:online})
    }
    else{
      ref_User.child(user.name).set({
        name: user.name,
        status: user.status
      })
    }
  })

}

function logout(user){
  console.log('logout', user)
  ref_User.child(user.name).update({status: 'offline'});
}

function joinGroup(user, group){
  ref_Group.child(group).child('member').child(user.name).set({
    name: user.name,
    status: user.status
  })
}

function chat(group,user, message, time){
  console.log('chat', group,user,message,time)
  var chance = new Chance()
  ref_Group.child(group).child('Message').child(chance.word()).set({
  message: message,
  time: time,
  username:user.name
  })
}

function canvas(group){
  var x = Math.floor(Math.random() * (120 + 1));
  var y = Math.floor(Math.random() * (105 + 1));
  var curColor = randColor();
  var curSize = randSize();
  var curTool = randTool();
  if(curTool == 'Eraser'){
    curColor = 'fff';
    ref_Group.child(group).child('drawing').child(x+':'+y).set({
      curColor: curColor,
      curSize : curSize,
      curTool : curTool
    })
  }else if(curTool == 'Refresh'){
    ref_Group.child(group).child('drawing').remove();
  }else{
    ref_Group.child(group).child('drawing').child(x+':'+y).set({
      curColor: curColor,
      curSize : curSize,
      curTool : curTool
    })
  }
  console.log('canvas', x, ':', y, 'color:', curColor, 'size:', curSize, 'tool:', curTool)
}

function randSize(){
  var size = [
    'Small',
    'Medium',
    'Large'
  ];
  var rand = Math.floor(Math.random()*size.length);
  return size[rand]
}

function randTool(){
  var tool = [
    'Eraser',
    'Marker',
    'Refresh'
  ];
  var rand = Math.floor(Math.random()*tool.length);
  return tool[rand]
}

function randColor(){
  var colors = ["fff","000","f00","0f0","00f","88f","f8d","f88","f05","f80","0f8","cf0","08f","408","ff8","8ff", "aed081", "eee"];

  var rand = Math.floor(Math.random()*colors.length);
  return colors[rand]
}

function addSchedule(group, schedule){
  console.log('schedule', schedule)
  ref_Group.child(group).child('Schedule').once('value', function(snapshot){
    var D = snapshot.val()
    var key = Object.keys(D)
    if (key.indexOf(schedule.Day)>-1){
      ref_Group.child(group).child('Schedule').child(schedule.Day).child(schedule.time).set({
        budget: schedule.budget,
        place: schedule.place,
        transportation: schedule.transportation
      })
    }
    else{
      ref_Group.child(group).child('Schedule').child(schedule.Day).set(
        schedule.time)
      ref_Group.child(group).child('Schedule').child(schedule.Day).child(schedule.time).set({
          budget: schedule.budget,
          place: schedule.place,
          transportation: schedule.transportation
        })
    }
  })
}

function clickOnMap(group, map_point){
  ref_Group.child(group).child('map_markers').child(map_point.name).set({
    name: map_point.name,
    lat: map_point.lat,
    lon: map_point.lon,
    message: map_point.message
  })
}

function removeFromMap(group, map_point){
  ref_Group.child(group).child('map_markers').child(map_point.name).remove()
}
// function clickonMap()
///-------------------------------------------------------------------------
// function Make_Group(groupName, key, userName){

//   ref_Group.child(groupName).set({
//     GroupName: groupName
//     Activation_key: key
//     Message: {
//       time: "Welcome to "+groupName
//     }
//     member: {
//       userName: userName
//       current_status: online
//     }
//   })
// }
// function Join_Group(groupName, key, userName){
//   ref_Group.child(groupName).child(Activation_key).once('value',function(snapshot){
//     var gold_answer = snapshot.value()
//   })
//   if(key != gold_answer){
//     alert('wrong password')
//   }
//   else{
//     ref_Group.child(groupName).child(member).child(userName).set({
//       userName: userName
//       current_status: online
//     })
//     if (ref_User.child(userName).child('groups')!=null){
//       ref_User.child(userName).child('groups').once('value',function(snapshot){
//         var key = snapshot.val()
//         key.push(groupName)
//         ref_User.child(userName).child('groups').set(key)
//       })
//     }
//     else{
//       ref_User.child(userName).child('groups').set([groupName])
//     }

// }

// run each second
setInterval(simulate, 2000)<|endoftext|>


<commit_before>$(function() {
  $('input[name=shippingdate]').datepicker({ dateFormat: "dd-mm-yy" });
  $('input[name=deliverydate]').datepicker({ dateFormat: "dd-mm-yy" });

  $('#add_shipment').validate({
    errorElement: 'span',
    validClass: 'fvalid', errorClass: 'ferror',
    rules: {
        shippingname: {
            wwsdash: true,
        },
        dewars: {
            number: true,
        },
        deliverydate: {
            edate: true
        },
        shippingdate: {
            edate: true
        }
    }
  })

  function _get_lc(lid) {
    $.ajax({
      url: '/shipment/ajax/lcd/lcid/'+lid,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(j){
        $('input[name=couriername]').val(j['DEFAULTCOURRIERCOMPANY'])
        $('input[name=courierno]').val(j['COURIERACCOUNT'])
      }
    })
  }

  $('select[name=lcret]').change(function() { _get_lc($(this).val()) })
  _get_lc($('select[name=lcret]').val())

  $('input[name=dewars]').change(function() { _update_fcodes() })

  function _update_fcodes() {
    var d = $('input[name=dewars]').val()
    var l = $('span.fcodes span').length

    d > 0 ? $('li.d').fadeIn() : $('li.d').fadeOut()

    if (d > l) {
      for (var i = l; i < d; i++) {
        $('<input type="text" name=fcodes[] value="" placeholder="DLS-XX-000'+(i+1)+'" /> ').hide().appendTo($('span.fcodes')).fadeIn()
      }

    } else if (d < l) {
      for (var i = (l-1); i >= d; i--) {
        $('span.fcodes span').eq(i).fadeOut().remove()
      }
    }

    $('input[name^=fcodes]').unbind('change').change(function() {
      $(this).val($(this).val().toUpperCase())
      _check_shipping()
    })
  }

  $('input[name=shippingname]').change(function() {
    _check_shipping()
  })

  function _check_shipping() {
    valid_fc = false
    $('input[name^=fcodes]').each(function(i,e) {
      if ($(this).val().match(/DLS-MX-\d\d\d\d/i)) valid_fc = true
    })

    if (valid_fc && $('input[name=shippingname]').val()) $('button[name="dls"]').fadeIn()
    else $('button[name="dls"]').hide()
  }

  _update_fcodes()

  function _get_exps() {
    $.ajax({
        url: '/shipment/ajax/vis',
        type: 'GET',
        dataType: 'json',
        timeout: 5000,
        success: function(json){

            var vals = '<option value=""></option>'
            $.each(json, function(k,e) {
               vals += '<option value="'+k+'">'+e+'</option>'
            })

            $('select[name=exp]').html(vals)
        }
    })
  }

  _get_exps()

  var accepted = false
  $('.terms').dialog({ title: 'Terms & Conditions', autoOpen: false, height: 'auto', width: 'auto', buttons: { 'Accept': function() {
      $.ajax({
        url: '/shipment/ajax/termsaccept/',
        data: { title: $('input[name=shippingname]').val() },
        type: 'GET',
        dataType: 'json',
        timeout: 5000,
        success: function(json){
          accepted = true;
          $('input[name="couriername"]').val('DHL')
          $('input[name="courierno"]').val(json[2])
          $('.terms').html('
Pin Code: '+json[1]+'
'+json[0])
          $('.terms').dialog('option', 'buttons', {'Close': function() { $(this).dialog('close') }})
          $('.terms').dialog('option', 'title', 'Instructions')
        }

      })
    }, 'Close': function() { $(this).dialog('close') }}

  });

  $('button[name="dls"]').button({ icons: { primary: 'ui-icon-contact' } }).hide().click(function() {
    $.ajax({
        url: '/shipment/ajax/terms',
        type: 'GET',
        dataType: 'json',
        timeout: 5000,
        success: function(json){
          if (!accepted) $('.terms').html(json)
          $('.terms').dialog('open')
        }
    })

    return false
  })

})
<commit_msg>Hmm, pressing enter shows t&cs?<commit_after>$(function() {
  $('input[name=shippingdate]').datepicker({ dateFormat: "dd-mm-yy" });
  $('input[name=deliverydate]').datepicker({ dateFormat: "dd-mm-yy" });

  $('#add_shipment').validate({
    errorElement: 'span',
    validClass: 'fvalid', errorClass: 'ferror',
    rules: {
        shippingname: {
            wwsdash: true,
        },
        dewars: {
            number: true,
        },
        deliverydate: {
            edate: true
        },
        shippingdate: {
            edate: true
        }
    }
  })

  function _get_lc(lid) {
    $.ajax({
      url: '/shipment/ajax/lcd/lcid/'+lid,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(j){
        $('input[name=couriername]').val(j['DEFAULTCOURRIERCOMPANY'])
        $('input[name=courierno]').val(j['COURIERACCOUNT'])
      }
    })
  }

  $('select[name=lcret]').change(function() { _get_lc($(this).val()) })
  _get_lc($('select[name=lcret]').val())

  $('input[name=dewars]').change(function() { _update_fcodes() })

  function _update_fcodes() {
    var d = $('input[name=dewars]').val()
    var l = $('span.fcodes span').length

    d > 0 ? $('li.d').fadeIn() : $('li.d').fadeOut()

    if (d > l) {
      for (var i = l; i < d; i++) {
        $('<input type="text" name=fcodes[] value="" placeholder="DLS-XX-000'+(i+1)+'" /> ').hide().appendTo($('span.fcodes')).fadeIn()
      }

    } else if (d < l) {
      for (var i = (l-1); i >= d; i--) {
        $('span.fcodes span').eq(i).fadeOut().remove()
      }
    }

    $('input[name^=fcodes]').unbind('change').change(function() {
      $(this).val($(this).val().toUpperCase())
      _check_shipping()
      return false
    })
  }

  $('input[name=shippingname]').change(function() {
    _check_shipping()
    return false
  })

  function _check_shipping() {
    valid_fc = false
    $('input[name^=fcodes]').each(function(i,e) {
      if ($(this).val().match(/DLS-MX-\d\d\d\d/i)) valid_fc = true
    })

    if (valid_fc && $('input[name=shippingname]').val()) $('button[name="dls"]').fadeIn()
    else $('button[name="dls"]').hide()
  }

  _update_fcodes()

  function _get_exps() {
    $.ajax({
        url: '/shipment/ajax/vis',
        type: 'GET',
        dataType: 'json',
        timeout: 5000,
        success: function(json){

            var vals = '<option value=""></option>'
            $.each(json, function(k,e) {
               vals += '<option value="'+k+'">'+e+'</option>'
            })

            $('select[name=exp]').html(vals)
        }
    })
  }

  _get_exps()

  var accepted = false
  $('.terms').dialog({ title: 'Terms & Conditions', autoOpen: false, height: 'auto', width: 'auto', buttons: { 'Accept': function() {
      $.ajax({
        url: '/shipment/ajax/termsaccept/',
        data: { title: $('input[name=shippingname]').val() },
        type: 'GET',
        dataType: 'json',
        timeout: 5000,
        success: function(json){
          accepted = true;
          $('input[name="couriername"]').val('DHL')
          $('input[name="courierno"]').val(json[2])
          $('.terms').html('
Pin Code: '+json[1]+'
'+json[0])
          $('.terms').dialog('option', 'buttons', {'Close': function() { $(this).dialog('close') }})
          $('.terms').dialog('option', 'title', 'Instructions')
        }

      })
    }, 'Close': function() { $(this).dialog('close') }}

  });

  $('button[name="dls"]').button({ icons: { primary: 'ui-icon-contact' } }).hide().click(function() {
    $.ajax({
        url: '/shipment/ajax/terms',
        type: 'GET',
        dataType: 'json',
        timeout: 5000,
        success: function(json){
          if (!accepted) $('.terms').html(json)
          $('.terms').dialog('open')
        }
    })

    return false
  })

})
<|endoftext|>


<commit_before>/*
 * # LivelyHaloGrabItem
 * The GrabHaloItem removes the selected node from its parent element
 * drags it to a new position and places it relative or aboslute
 * (distance or holding shift pressed) into another node.
 */

import HaloItem from './HaloItem.js';
import * as nodes from 'src/client/morphic/node-helpers.js';
import * as events from 'src/client/morphic/event-helpers.js';
import {pt} from 'src/client/graphics.js';
import Preferences from 'src/client/preferences.js';
import {Grid} from 'src/client/morphic/snapping.js';

export default class HaloGrabItem extends HaloItem {

 static get droppingBlacklist() {
      return {"*":
        ["button", "input", "lively-halo", "html",  "lively-selection", "lively-connector"]
      }
  };

  initialize() {
    this.registerMouseEvents()
    this.startCustomDragging();

  }

  // DRAG API

  start(evt) {
    if (this.isDragging) {
      console.log("isDragging " + this.isDragging)
      return;
    }
    this.grabTarget = window.that;
    if (this.grabTarget) {
      this.grabStartEventPosition = events.globalPosition(evt);
      this.grabOffset =  events.globalPosition(evt).subPt(lively.getGlobalPosition(this.grabTarget));

      evt.preventDefault();
    }
  }

  move(evt) {
    if (this.grabTarget && !this.isDragging &&
      events.noticableDistanceTo(evt, this.grabStartEventPosition)) {
      // drag detected
        if (this.grabTarget.haloGrabStart) {
          this.grabTarget.haloGrabStart(evt, this)
        } else {
          this.initGrabShadow();
          this.prepareGrabTarget();
        }
        this.isDragging = true;
    }
    if (this.isDragging && this.grabTarget) {
      if (this.grabTarget.haloGrabMove) {
        this.grabTarget.haloGrabMove(evt, this)
      } else {
        this.moveGrabbedNodeToEvent(evt);
      }
    }
  }

  stop(evt) {
    try {
    if (this.isDragging && this.grabTarget) {
      if (this.grabTarget.haloGrabStop) {
        this.grabTarget.haloGrabStop(evt, this)
      } else {
        this.stopGrabbingAtEvent(evt);
      }
    }
    } finally {
      this.isDragging = false;
      this.grabTarget = null;
      this.grabStartEventPosition = null;
      this.grabShadow = null;
    }
  }

  // HELPERS

  prepareGrabTarget() {
    document.body.appendChild(this.grabTarget);
    this.grabTarget.classList.add("lively4-grabbed")
    this.grabTarget.style.position = 'absolute';
    this.grabTarget.style.removeProperty('top');
    this.grabTarget.style.removeProperty('left');
  }

  initGrabShadow() {
    this.grabShadow = this.grabTarget.cloneNode(true);
    this.grabShadow.style.opacity = '0.5';
    this.grabShadow.style.position = 'relative';
    this.grabShadow.style.removeProperty('top');
    this.grabShadow.style.removeProperty('left');
  }

  moveGrabbedNodeToEvent(evt) {
    var eventPosition = pt(evt.clientX, evt.clientY);
    var pos = eventPosition.subPt(this.grabOffset)

    this.dropAtEvent(this.grabShadow, evt);
    lively.setGlobalPosition(this.grabTarget, Grid.optSnapPosition(pos, evt))
    evt.preventDefault();
  }

  stopGrabbingAtEvent(evt) {
    if (this.dropIndicator) this.dropIndicator.remove()
    if (this.dropTargetIndicator) this.dropTargetIndicator.remove()

    this.grabTarget.classList.remove("lively4-grabbed")
    if (this.grabShadow.style.position == 'absolute') {
        lively.notify("absolute...")
        this.insertGrabTargetBeforeShadow();
        this.removeGrabShadow();
        lively.setPosition(this.grabTarget, lively.getPosition(this.grabShadow))
    } else {
      this.insertGrabTargetBeforeShadow();
      this.removeGrabShadow();

      this.grabTarget.style.position = 'relative';
      this.grabTarget.style.removeProperty('top');
      this.grabTarget.style.removeProperty('left');
    }
    evt.preventDefault();
    this.isDragging = false;
  }

  removeGrabShadow() {
    this.grabShadow.parentNode.removeChild(this.grabShadow);
  }

  dropAtEvent(grabShadow, evt) {
    var droptarget = this.droptargetAtEvent(grabShadow, evt);
    if (droptarget) {

      this.moveGrabShadowToTargetAtEvent(droptarget, evt);
      if (this.dropIndicator) this.dropIndicator.remove()
      this.dropIndicator = lively.showElement(droptarget)
      this.dropIndicator.style.border = "3px solid green"
      this.dropIndicator.querySelector("pre").style.color = "green"

      if (this.dropTargetIndicator) this.dropTargetIndicator.remove()
      this.dropTargetIndicator = lively.showElement(grabShadow)
      this.dropTargetIndicator.style.border = "1px solid blue"
      this.dropTargetIndicator.querySelector("pre").style.color = "blue"
      this.dropTargetIndicator.querySelector("pre").textContent = "drop x"
      // lively.showPoint(lively.getGlobalPosition(grabShadow))
      lively.setGlobalPosition(this.dropTargetIndicator,
        lively.getGlobalPosition(grabShadow))
    }
  }

  insertGrabTargetBeforeShadow() {
    if (this.grabShadow && this.grabTarget) {
      this.grabShadow.parentNode.insertBefore(this.grabTarget, this.grabShadow);
    }
  }

  droptargetAtEvent(node, evt) {
    var elementsUnderCursor = Array.from(events.elementsUnder(evt)).filter( (elementUnder) => {
      return elementUnder !== this.grabTarget && elementUnder !== this.grabShadow;
    });
    for (var i = 0; i < elementsUnderCursor.length; i++) {
      var targetNode = elementsUnderCursor[i];
      if (HaloGrabItem.canDropInto(node, targetNode) ) {
        return targetNode;
      }
    }
    return document.body;
  }

  moveGrabShadowToTargetAtEvent(targetNode, evt) {
    var pos = pt(evt.clientX, evt.clientY)

    var children = targetNode.childNodes;
    var nextChild = Array.from(children).find(child => {
      return child !== this.grabShadow && child !== this.grabTarget &&
        child.nodeType === 1 && this.nodeComesBehind(child, pos);
    });

    targetNode.insertBefore(this.grabShadow, nextChild);
    this.grabShadow.style.position = 'relative';
    this.grabShadow.style.removeProperty('top');
    this.grabShadow.style.removeProperty('left');

    if (evt.shiftKey ||
      lively.getGlobalPosition(this.grabShadow).dist(lively.getGlobalPosition(this.grabTarget)) > 100) {
      this.grabShadow.parentElement.appendChild(this.grabShadow)
      this.grabShadow.style.opacity = 0;
      lively.setPosition(this.grabShadow, pt(0,0))

      var pos = lively.getGlobalPosition(this.grabTarget);
      // lively.showPoint(pos)
      // lively.showElement(this.grabTarget)

      console.log("set global position: " + pos)
      lively.setGlobalPosition(this.grabShadow, pos); // localize
      // lively.setGlobalPosition(this.grabShadow, pos); // localize

      // var mysteriousOffset = pos.subPt(lively.getGlobalPosition(this.grabShadow))
      // lively.moveBy(this.grabShadow,mysteriousOffset )

      // lively.showPoint(lively.getGlobalPosition(this.grabShadow))
    } else {
      // drag position is near enough to relative position, so SNAP
      this.grabShadow.style.opacity = 0.5;
    }
  }

  static canDropInto(node, targetNode) {
    if (!targetNode || !node) return false
    var targetTag = targetNode.tagName.toLowerCase();
    return node !== targetNode &&
      !Array.from(node.getElementsByTagName('*')).includes(targetNode) &&
      !(this.droppingBlacklist[node.tagName.toLowerCase()] || []).includes(targetTag) &&
      !(this.droppingBlacklist['*'] || []).includes(targetTag) &&
      (!targetNode.livelyAcceptsDrop || targetNode.livelyAcceptsDrop(node))
  }

  nodeComesBehind(node, pos) {
    var bounds = node.getBoundingClientRect()
    var toTheRight =
      (bounds.top <= pos.y <= bounds.bottom) && (bounds.left > pos.x);
    var below = bounds.top > pos.y;
    return toTheRight || below;
  }
}<commit_msg>fixed #132<commit_after>/*
 * # LivelyHaloGrabItem
 * The GrabHaloItem removes the selected node from its parent element
 * drags it to a new position and places it relative or aboslute
 * (distance or holding shift pressed) into another node.
 */

import HaloItem from './HaloItem.js';
import * as nodes from 'src/client/morphic/node-helpers.js';
import * as events from 'src/client/morphic/event-helpers.js';
import {pt} from 'src/client/graphics.js';
import Preferences from 'src/client/preferences.js';
import {Grid} from 'src/client/morphic/snapping.js';

export default class HaloGrabItem extends HaloItem {

 static get droppingBlacklist() {
      return {"*":
        ["button", "input", "lively-halo", "html",  "lively-selection", "lively-connector"]
      }
  };

  initialize() {
    this.registerMouseEvents()
    this.startCustomDragging();

  }

  // DRAG API

  start(evt) {
    if (this.isDragging) {
      console.log("isDragging " + this.isDragging)
      return;
    }
    this.grabTarget = window.that;
    if (this.grabTarget) {
      this.grabStartEventPosition = events.globalPosition(evt);
      this.grabOffset =  events.globalPosition(evt).subPt(lively.getGlobalPosition(this.grabTarget));

      evt.preventDefault();
    }
  }

  move(evt) {
    if (this.grabTarget && !this.isDragging &&
      events.noticableDistanceTo(evt, this.grabStartEventPosition)) {
      // drag detected
        if (this.grabTarget.haloGrabStart) {
          this.grabTarget.haloGrabStart(evt, this)
        } else {
          this.initGrabShadow();
          this.prepareGrabTarget();
        }
        this.isDragging = true;
    }
    if (this.isDragging && this.grabTarget) {
      if (this.grabTarget.haloGrabMove) {
        this.grabTarget.haloGrabMove(evt, this)
      } else {
        this.moveGrabbedNodeToEvent(evt);
      }
    }
  }

  stop(evt) {
    try {
    if (this.isDragging && this.grabTarget) {
      if (this.grabTarget.haloGrabStop) {
        this.grabTarget.haloGrabStop(evt, this)
      } else {
        this.stopGrabbingAtEvent(evt);
      }
    }
    } finally {
      this.isDragging = false;
      this.grabTarget = null;
      this.grabStartEventPosition = null;
      this.grabShadow = null;
    }
  }

  // HELPERS

  prepareGrabTarget() {
    document.body.appendChild(this.grabTarget);
    this.grabTarget.classList.add("lively4-grabbed")
    this.grabTarget.style.position = 'absolute';
    this.grabTarget.style.removeProperty('top');
    this.grabTarget.style.removeProperty('left');
  }

  initGrabShadow() {
    this.grabShadow = this.grabTarget.cloneNode(true);
    this.grabShadow.style.opacity = '0.5';
    this.grabShadow.style.position = 'relative';
    this.grabShadow.style.removeProperty('top');
    this.grabShadow.style.removeProperty('left');
  }

  moveGrabbedNodeToEvent(evt) {
    var eventPosition = pt(evt.clientX, evt.clientY);
    var pos = eventPosition.subPt(this.grabOffset)

    this.dropAtEvent(this.grabShadow, evt);
    lively.setGlobalPosition(this.grabTarget, Grid.optSnapPosition(pos, evt))
    evt.preventDefault();
  }

  stopGrabbingAtEvent(evt) {
    if (this.dropIndicator) this.dropIndicator.remove()
    if (this.dropTargetIndicator) this.dropTargetIndicator.remove()

    this.grabTarget.classList.remove("lively4-grabbed")
    if (this.grabShadow.style.position == 'absolute') {
        lively.notify("absolute...")
        this.insertGrabTargetBeforeShadow();
        this.removeGrabShadow();
        lively.setPosition(this.grabTarget, lively.getPosition(this.grabShadow))
    } else {
      this.insertGrabTargetBeforeShadow();
      this.removeGrabShadow();

      this.grabTarget.style.position = 'relative';
      this.grabTarget.style.removeProperty('top');
      this.grabTarget.style.removeProperty('left');
    }
    evt.preventDefault();
    this.isDragging = false;

    if (this.grabTarget.parentElement == document.body) {
      this.grabTarget.classList.add("lively-content"); // "desktop content will be preserved"
    }

  }

  removeGrabShadow() {
    this.grabShadow.parentNode.removeChild(this.grabShadow);
  }

  dropAtEvent(grabShadow, evt) {
    var droptarget = this.droptargetAtEvent(grabShadow, evt);
    if (droptarget) {

      this.moveGrabShadowToTargetAtEvent(droptarget, evt);
      if (this.dropIndicator) this.dropIndicator.remove()
      this.dropIndicator = lively.showElement(droptarget)
      this.dropIndicator.style.border = "3px solid green"
      this.dropIndicator.querySelector("pre").style.color = "green"

      if (this.dropTargetIndicator) this.dropTargetIndicator.remove()
      this.dropTargetIndicator = lively.showElement(grabShadow)
      this.dropTargetIndicator.style.border = "1px solid blue"
      this.dropTargetIndicator.querySelector("pre").style.color = "blue"
      this.dropTargetIndicator.querySelector("pre").textContent = "drop x"
      // lively.showPoint(lively.getGlobalPosition(grabShadow))
      lively.setGlobalPosition(this.dropTargetIndicator,
        lively.getGlobalPosition(grabShadow))
    }
  }

  insertGrabTargetBeforeShadow() {
    if (this.grabShadow && this.grabTarget) {
      this.grabShadow.parentNode.insertBefore(this.grabTarget, this.grabShadow);
    }
  }

  droptargetAtEvent(node, evt) {
    var elementsUnderCursor = Array.from(events.elementsUnder(evt)).filter( (elementUnder) => {
      return elementUnder !== this.grabTarget && elementUnder !== this.grabShadow;
    });
    for (var i = 0; i < elementsUnderCursor.length; i++) {
      var targetNode = elementsUnderCursor[i];
      if (HaloGrabItem.canDropInto(node, targetNode) ) {
        return targetNode;
      }
    }
    return document.body;
  }

  moveGrabShadowToTargetAtEvent(targetNode, evt) {
    var pos = pt(evt.clientX, evt.clientY)

    var children = targetNode.childNodes;
    var nextChild = Array.from(children).find(child => {
      return child !== this.grabShadow && child !== this.grabTarget &&
        child.nodeType === 1 && this.nodeComesBehind(child, pos);
    });

    targetNode.insertBefore(this.grabShadow, nextChild);
    this.grabShadow.style.position = 'relative';
    this.grabShadow.style.removeProperty('top');
    this.grabShadow.style.removeProperty('left');

    if (evt.shiftKey ||
      lively.getGlobalPosition(this.grabShadow).dist(lively.getGlobalPosition(this.grabTarget)) > 100) {
      this.grabShadow.parentElement.appendChild(this.grabShadow)
      this.grabShadow.style.opacity = 0;
      lively.setPosition(this.grabShadow, pt(0,0))

      var pos = lively.getGlobalPosition(this.grabTarget);
      // lively.showPoint(pos)
      // lively.showElement(this.grabTarget)

      console.log("set global position: " + pos)
      lively.setGlobalPosition(this.grabShadow, pos); // localize
      // lively.setGlobalPosition(this.grabShadow, pos); // localize

      // var mysteriousOffset = pos.subPt(lively.getGlobalPosition(this.grabShadow))
      // lively.moveBy(this.grabShadow,mysteriousOffset )

      // lively.showPoint(lively.getGlobalPosition(this.grabShadow))
    } else {
      // drag position is near enough to relative position, so SNAP
      this.grabShadow.style.opacity = 0.5;
    }
  }

  static canDropInto(node, targetNode) {
    if (!targetNode || !node) return false
    var targetTag = targetNode.tagName.toLowerCase();
    return node !== targetNode &&
      !Array.from(node.getElementsByTagName('*')).includes(targetNode) &&
      !(this.droppingBlacklist[node.tagName.toLowerCase()] || []).includes(targetTag) &&
      !(this.droppingBlacklist['*'] || []).includes(targetTag) &&
      (!targetNode.livelyAcceptsDrop || targetNode.livelyAcceptsDrop(node))
  }

  nodeComesBehind(node, pos) {
    var bounds = node.getBoundingClientRect()
    var toTheRight =
      (bounds.top <= pos.y <= bounds.bottom) && (bounds.left > pos.x);
    var below = bounds.top > pos.y;
    return toTheRight || below;
  }
}<|endoftext|>


<commit_before>$(document).ready(function(){
	if($('#content .container').hasClass('home'))
		twitterIni();
	$.cookie.defaults.path = '/';
	$('.jscrollpane').jScrollPane();
	$('.custom-select').customSelect();
	$('.calificacion-form').validate();
	$('.reporte-form').validate();
	$('.petition-form').validate();
	$('.contacto-form').validate();
	$('form.newsletter').validate();

	$('#ver-en-mapa').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action',$(this).attr('href'));
		$('#general-search').submit();
	});

	$('.compara-tabs a').click(function(e){
		e.preventDefault();
		var index = $(this).index();
		$('.compara-tabs a.on').removeClass('on');
		$(this).addClass('on');
		$('.compara-tab-container .tab.on').removeClass('on');
		$('.compara-tab-container .tab').eq(index).addClass('on');
	})

	$('.compara-escuela').on('click',function(e){
		e.preventDefault();
		var tr = $(this).parent().parent().toggleClass('on');
		var cct = $(this).attr('href');
		toggle_escuela(cct);
	});

	$('#content .perfil .tabs li a').click(function(e){
		e.preventDefault();
		var index = 4 - $(this).parent().index();
		$('#content .perfil .tabs li.on').removeClass('on');
		$(this).parent().addClass('on');
		$('#content .perfil .tab-container .tab.on').removeClass('on');
		$('#content .perfil .tab-container .tab').eq(index).addClass('on').jScrollPane();
		if($(this).html() == 'Resultados Educativos' ) drawCharts();
	})
	$('#rank-bar').mousemove(function(e){
		set_rank_bar(e.pageX - $(this).offset().left);
	});
	$('#rank-bar').click(function(e){
		var rank = set_rank_bar(e.pageX - $(this).offset().left);
		$('#rank-value').val(rank);
	});
	$('#rank-bar').mouseout(function(e){
		var max = $('.container').hasClass('B')?173:336;
		var x = e.pageX - $(this).offset().left;
		var y = e.pageY - $(this).offset().top;
		if((y >= 10 || y < 0) || (x < 0 || x > max)){
			var val = $('#rank-value').val();
			if(val != ''){
				set_rank_bar(Math.round(val/100*max));
			}else{
				$('#rank-bar .bar').hide();
				$('#rank-label').hide();
			}
		}
	});

	if($("#name-input") .length)
	$( "#name-input" ).autocomplete({
  		source: function(request,response){
  			$.post("/main/get_escuelas/",{
  				term : request.term,
  				entidad : $("#state-input").val(),
  				municipio : $("#municipio-input").val(),
  				localidad : $("#localidad-input").val(),
  				nivel : $("#nivel-input").val(),
  				json : true
  			},response,'json');
  		},
  		minLength: 3,
		select: function( event, ui ) {
			window.location = "/escuelas/index/"+ui.item.cct;
			return false;
		}
	}).data( "ui-autocomplete" )._renderItem = function( ul, item ){
      return $("
").append(""+item.label+""+item.address+"").appendTo(ul);
    };

	$('#map-button').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action','/mapa/');
		$('#general-search').submit();

	});
	$('#state-input').change(function(e){
		$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
		load_location_options(
			$("#municipio-input"),
			'load_municipios',
			{entidad:$(this).val(),json:true},
			"Municipio"
		);
	});

	$('#municipio-input').change(function(){
		if($(this).val() != "" || ($("#state-input option:selected").val() != "" && $("#state-input option:selected").val() != 7 && $("#state-input option:selected").val() != 20 && $("#state-input option:selected").val() != 30)){
			load_location_options(
				$("#localidad-input"),
				'load_localidades',
				{municipio:$(this).val(),entidad:$("#state-input option:selected").val(),json:true},
				"Localidad"
			);
		}else{
			$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
			$("#localidad-input").html('<option value="">Localidad</option>');
		}
	});

	$('#content .home .circle a.line').hover(function(){
		var x=[27,23,19];
		var i=$(this).index();
		var xP=$(this).position().left;
		$(this).parent().find('.line1').css({'left':xP+x[i-1] + 'px','display':'block'});
		$(this).parent().find('.line2').css({'left':89+xP+x[i-1]+'px','display':'block'});
	},function(){
			$(this).parent().find('.line1').css('display','none');
			$(this).parent().find('.line2').css('display','none');
	});

	$('#content .share-bt a.button-frame').click(function(e){
		e.preventDefault();
		$('#content .share-bt .social').toggleClass('on');
	});

	$('.wrap_cal span').mouseenter(function(){
		var span =  $(this).parent().find('span');
		if($(this).hasClass('on') && $(this).index()==0){
			span.removeClass('on');
		}else{
			span.removeClass('on');
			for(var i=0;i<=$(this).index();i++){
				$(span[i]).addClass('on');
			}
		}
	});

	$('.califica .button-frame').click(function(e){
		e.preventDefault();
		var promedio = $('.wrap_cal span.on').size() / $('.wrap_cal').size();
		promedio = promedio.toString().length>3?promedio.toFixed(1):promedio;
		$('.promedio span').html(promedio);
		$('#rank-value').val(promedio);
	});

	$('.menu a.logo + a + a').click(function(e){
		e.preventDefault();
		var cookie = $.cookie('escuelas'),
		    url = '/compara/escuelas/'+ (cookie != undefined ? cookie:'');
		location.href = url;
	});

	$('.search-estado select.custom-select').change(function(){
		var id;
		if((id = $(this).val())!=''){
			location.href = '/resultados-nacionales/entidad/'+id;
		}
	});

	$('.peticion h1').click(function(){
		$('.wrap_peticion, .social.on').removeClass('on');
		$(this).next().addClass('on');
	});

	if($('#content .container').hasClass('perfil')){
		$('.menu a.logo + a + a + a').click(function(e){
			e.preventDefault();
			location.href = $('.califica a:first-child').attr('href');
		});

		$('.tabs a.result').click(function(){
		var texts = $('text[text-anchor="start"]'),
		    text;
		for(var i=0;i<texts.length;i++){
			text = $(texts[i]);
			text.text(text.text()+' grado');
		}
		});

	}

	$('td.school').hover(function(){
		$('.tooltip').css({top:$(this).position().top,display:'block'});
	},
	function(){
		$('.tooltip').css('display','none');
	});

});

function load_location_options(input,directive,options,name){
	input.prop('disabled', true);
	input.next().addClass('customSelectDisabled');
	$.post('/main/'+directive,options,function(data){
		input.html('<option value="">'+name+'</option>');
		for(x in data){
			var item = data[x];
			input.append('<option value="'+item.id+'">'+item.nombre+'</option>');
		}
		input.prop('disabled', false);
		input.next().removeClass('customSelectDisabled');
		input.trigger('change');
	},'json');
}
function set_rank_bar(x){
	var max = $('.container').hasClass('B')?173:336;
	var rank = Math.round(x/max * 100);
	var offset = x - 12;
	$('#rank-bar .bar').css('width',x+'px').show();
	$('#rank-label').html(rank+'%').css('left',offset+'px').show();
	return rank;
}
function toggle_escuela(cct){
	if(typeof($.cookie('escuelas')) == 'undefined'){
		$.cookie('escuelas',[cct]);
	}else{
		var escuelas = $.cookie('escuelas').split('-');
		var index = escuelas.indexOf(cct);
		if(index != -1){
			escuelas.pop(index);
		}else{
			escuelas.push(cct);
		}
		escuelas.sort();
		$.cookie('escuelas',escuelas.join('-'));
		$('#compara-main-button').attr('href','/compara/escuelas/'+escuelas.join('-'));
		if( $('.container.resultados').hasClass('comparar')){
			var url=document.URL.replace(new RegExp('-*'+cct),'');
			location.href = url;
		}
	}
}
function twitterIni(){
    var username =  "mejoratuescuela",
	page_proxy = '/home/twitter';
	$("#tweets .tweet p").html("cargando tweets...");
	$.getJSON(page_proxy, function(data){
		$("#tweets .tweet").css('display','none');
		$("#tweets").append('

');
		for(d in data){
			var x = data[d];
			$("#tweets ul").append('

@'+username+' '+x.text+'

');
	    	}
	    })
}
<commit_msg>url de califica en perfil<commit_after>$(document).ready(function(){
	if($('#content .container').hasClass('home'))
		twitterIni();
	$.cookie.defaults.path = '/';
	$('.jscrollpane').jScrollPane();
	$('.custom-select').customSelect();
	$('.calificacion-form').validate();
	$('.reporte-form').validate();
	$('.petition-form').validate();
	$('.contacto-form').validate();
	$('form.newsletter').validate();

	$('#ver-en-mapa').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action',$(this).attr('href'));
		$('#general-search').submit();
	});

	$('.compara-tabs a').click(function(e){
		e.preventDefault();
		var index = $(this).index();
		$('.compara-tabs a.on').removeClass('on');
		$(this).addClass('on');
		$('.compara-tab-container .tab.on').removeClass('on');
		$('.compara-tab-container .tab').eq(index).addClass('on');
	})

	$('.compara-escuela').on('click',function(e){
		e.preventDefault();
		var tr = $(this).parent().parent().toggleClass('on');
		var cct = $(this).attr('href');
		toggle_escuela(cct);
	});

	$('#content .perfil .tabs li a').click(function(e){
		e.preventDefault();
		var index = 4 - $(this).parent().index();
		$('#content .perfil .tabs li.on').removeClass('on');
		$(this).parent().addClass('on');
		$('#content .perfil .tab-container .tab.on').removeClass('on');
		$('#content .perfil .tab-container .tab').eq(index).addClass('on').jScrollPane();
		if($(this).html() == 'Resultados Educativos' ) drawCharts();
	})
	$('#rank-bar').mousemove(function(e){
		set_rank_bar(e.pageX - $(this).offset().left);
	});
	$('#rank-bar').click(function(e){
		var rank = set_rank_bar(e.pageX - $(this).offset().left);
		$('#rank-value').val(rank);
	});
	$('#rank-bar').mouseout(function(e){
		var max = $('.container').hasClass('B')?173:336;
		var x = e.pageX - $(this).offset().left;
		var y = e.pageY - $(this).offset().top;
		if((y >= 10 || y < 0) || (x < 0 || x > max)){
			var val = $('#rank-value').val();
			if(val != ''){
				set_rank_bar(Math.round(val/100*max));
			}else{
				$('#rank-bar .bar').hide();
				$('#rank-label').hide();
			}
		}
	});

	if($("#name-input") .length)
	$( "#name-input" ).autocomplete({
  		source: function(request,response){
  			$.post("/main/get_escuelas/",{
  				term : request.term,
  				entidad : $("#state-input").val(),
  				municipio : $("#municipio-input").val(),
  				localidad : $("#localidad-input").val(),
  				nivel : $("#nivel-input").val(),
  				json : true
  			},response,'json');
  		},
  		minLength: 3,
		select: function( event, ui ) {
			window.location = "/escuelas/index/"+ui.item.cct;
			return false;
		}
	}).data( "ui-autocomplete" )._renderItem = function( ul, item ){
      return $("
").append(""+item.label+""+item.address+"").appendTo(ul);
    };

	$('#map-button').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action','/mapa/');
		$('#general-search').submit();

	});
	$('#state-input').change(function(e){
		$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
		load_location_options(
			$("#municipio-input"),
			'load_municipios',
			{entidad:$(this).val(),json:true},
			"Municipio"
		);
	});

	$('#municipio-input').change(function(){
		if($(this).val() != "" || ($("#state-input option:selected").val() != "" && $("#state-input option:selected").val() != 7 && $("#state-input option:selected").val() != 20 && $("#state-input option:selected").val() != 30)){
			load_location_options(
				$("#localidad-input"),
				'load_localidades',
				{municipio:$(this).val(),entidad:$("#state-input option:selected").val(),json:true},
				"Localidad"
			);
		}else{
			$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
			$("#localidad-input").html('<option value="">Localidad</option>');
		}
	});

	$('#content .home .circle a.line').hover(function(){
		var x=[27,23,19];
		var i=$(this).index();
		var xP=$(this).position().left;
		$(this).parent().find('.line1').css({'left':xP+x[i-1] + 'px','display':'block'});
		$(this).parent().find('.line2').css({'left':89+xP+x[i-1]+'px','display':'block'});
	},function(){
			$(this).parent().find('.line1').css('display','none');
			$(this).parent().find('.line2').css('display','none');
	});

	$('#content .share-bt a.button-frame').click(function(e){
		e.preventDefault();
		$('#content .share-bt .social').toggleClass('on');
	});

	$('.wrap_cal span').mouseenter(function(){
		var span =  $(this).parent().find('span');
		if($(this).hasClass('on') && $(this).index()==0){
			span.removeClass('on');
		}else{
			span.removeClass('on');
			for(var i=0;i<=$(this).index();i++){
				$(span[i]).addClass('on');
			}
		}
	});

	$('.califica .button-frame').click(function(e){
		e.preventDefault();
		var promedio = $('.wrap_cal span.on').size() / $('.wrap_cal').size();
		promedio = promedio.toString().length>3?promedio.toFixed(1):promedio;
		$('.promedio span').html(promedio);
		$('#rank-value').val(promedio);
	});

	$('.menu a.logo + a + a').click(function(e){
		e.preventDefault();
		var cookie = $.cookie('escuelas'),
		    url = '/compara/escuelas/'+ (cookie != undefined ? cookie:'');
		location.href = url;
	});

	$('.search-estado select.custom-select').change(function(){
		var id;
		if((id = $(this).val())!=''){
			location.href = '/resultados-nacionales/entidad/'+id;
		}
	});

	$('.peticion h1').click(function(){
		$('.wrap_peticion, .social.on').removeClass('on');
		$(this).next().addClass('on');
	});

	if($('#content .container').hasClass('perfil')){
		$('.menu a.logo + a + a + a').click(function(e){
			e.preventDefault();
			location.href = $('.califica a.title').attr('href');
		});

		$('.tabs a.result').click(function(){
		var texts = $('text[text-anchor="start"]'),
		    text;
		for(var i=0;i<texts.length;i++){
			text = $(texts[i]);
			text.text(text.text()+' grado');
		}
		});

	}

	$('td.school').hover(function(){
		$('.tooltip').css({top:$(this).position().top,display:'block'});
	},
	function(){
		$('.tooltip').css('display','none');
	});

});

function load_location_options(input,directive,options,name){
	input.prop('disabled', true);
	input.next().addClass('customSelectDisabled');
	$.post('/main/'+directive,options,function(data){
		input.html('<option value="">'+name+'</option>');
		for(x in data){
			var item = data[x];
			input.append('<option value="'+item.id+'">'+item.nombre+'</option>');
		}
		input.prop('disabled', false);
		input.next().removeClass('customSelectDisabled');
		input.trigger('change');
	},'json');
}
function set_rank_bar(x){
	var max = $('.container').hasClass('B')?173:336;
	var rank = Math.round(x/max * 100);
	var offset = x - 12;
	$('#rank-bar .bar').css('width',x+'px').show();
	$('#rank-label').html(rank+'%').css('left',offset+'px').show();
	return rank;
}
function toggle_escuela(cct){
	if(typeof($.cookie('escuelas')) == 'undefined'){
		$.cookie('escuelas',[cct]);
	}else{
		var escuelas = $.cookie('escuelas').split('-');
		var index = escuelas.indexOf(cct);
		if(index != -1){
			escuelas.pop(index);
		}else{
			escuelas.push(cct);
		}
		escuelas.sort();
		$.cookie('escuelas',escuelas.join('-'));
		$('#compara-main-button').attr('href','/compara/escuelas/'+escuelas.join('-'));
		if( $('.container.resultados').hasClass('comparar')){
			var url=document.URL.replace(new RegExp('-*'+cct),'');
			location.href = url;
		}
	}
}
function twitterIni(){
    var username =  "mejoratuescuela",
	page_proxy = '/home/twitter';
	$("#tweets .tweet p").html("cargando tweets...");
	$.getJSON(page_proxy, function(data){
		$("#tweets .tweet").css('display','none');
		$("#tweets").append('

');
		for(d in data){
			var x = data[d];
			$("#tweets ul").append('

@'+username+' '+x.text+'

');
	    	}
	    })
}
<|endoftext|>


<commit_before>$(document).ready(function(){
	if($('#content .container').hasClass('home'))
		twitterIni();
	$.cookie.defaults.path = '/';
	$('.jscrollpane').jScrollPane();
	$('.custom-select').customSelect();
	$('.calificacion-form').validate();
	$('.reporte-form').validate();
	$('.petition-form').validate();
	$('.contacto-form').validate();
	$('form.newsletter').validate();

	$('#ver-en-mapa').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action',$(this).attr('href'));
		$('#general-search').submit();
	});

	$('.compara-tabs a').click(function(e){
		e.preventDefault();
		var index = $(this).index();
		$('.compara-tabs a.on').removeClass('on');
		$(this).addClass('on');
		$('.compara-tab-container .tab.on').removeClass('on');
		$('.compara-tab-container .tab').eq(index).addClass('on');
	})

	$('.compara-escuela').on('click',function(e){
		e.preventDefault();
		var tr = $(this).parent().parent().toggleClass('on');
		var cct = $(this).attr('href');
		toggle_escuela(cct);
	});

	$('#content .perfil .tabs li a').click(function(e){
		e.preventDefault();
		var index = 4 - $(this).parent().index();
		$('#content .perfil .tabs li.on').removeClass('on');
		$(this).parent().addClass('on');
		$('#content .perfil .tab-container .tab.on').removeClass('on');
		$('#content .perfil .tab-container .tab').eq(index).addClass('on').jScrollPane();
		if($(this).html() == 'Resultados Educativos' ) drawCharts();
	})
	$('#rank-bar').mousemove(function(e){
		set_rank_bar(e.pageX - $(this).offset().left);
	});
	$('#rank-bar').click(function(e){
		var rank = set_rank_bar(e.pageX - $(this).offset().left);
		$('#rank-value').val(rank);
	});
	$('#rank-bar').mouseout(function(e){
		var max = $('.container').hasClass('B')?173:336;
		var x = e.pageX - $(this).offset().left;
		var y = e.pageY - $(this).offset().top;
		if((y >= 10 || y < 0) || (x < 0 || x > max)){
			var val = $('#rank-value').val();
			if(val != ''){
				set_rank_bar(Math.round(val/100*max));
			}else{
				$('#rank-bar .bar').hide();
				$('#rank-label').hide();
			}
		}
	});

	if($("#name-input") .length)
	$( "#name-input" ).autocomplete({
  		source: function(request,response){
  			$.post("/main/get_escuelas/",{
  				term : request.term,
  				entidad : $("#state-input").val(),
  				municipio : $("#municipio-input").val(),
  				localidad : $("#localidad-input").val(),
  				nivel : $("#nivel-input").val(),
  				json : true
  			},response,'json');
  		},
  		minLength: 3,
		select: function( event, ui ) {
			window.location = "/escuelas/index/"+ui.item.cct;
			return false;
		}
	}).data( "ui-autocomplete" )._renderItem = function( ul, item ){
      return $("
").append(""+item.label+""+item.address+"").appendTo(ul);
    };

	$('#map-button').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action','/mapa/');
		$('#general-search').submit();

	});
	$('#state-input').change(function(e){
		$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
		load_location_options(
			$("#municipio-input"),
			'load_municipios',
			{entidad:$(this).val(),json:true},
			"Municipio"
		);
	});

	$('#municipio-input').change(function(){
		if($(this).val() != "" || ($("#state-input option:selected").val() != "" && $("#state-input option:selected").val() != 7 && $("#state-input option:selected").val() != 20 && $("#state-input option:selected").val() != 30)){
			load_location_options(
				$("#localidad-input"),
				'load_localidades',
				{municipio:$(this).val(),entidad:$("#state-input option:selected").val(),json:true},
				"Localidad"
			);
		}else{
			$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
			$("#localidad-input").html('<option value="">Localidad</option>');
		}
	});

	$('#content .home .circle a.line').hover(function(){
		var x=[27,23,19];
		var i=$(this).index();
		var xP=$(this).position().left;
		$(this).parent().find('.line1').css({'left':xP+x[i-1] + 'px','display':'block'});
		$(this).parent().find('.line2').css({'left':89+xP+x[i-1]+'px','display':'block'});
	},function(){
			$(this).parent().find('.line1').css('display','none');
			$(this).parent().find('.line2').css('display','none');
	});

	$('#content .share-bt a.button-frame').click(function(e){
		e.preventDefault();
		$('#content .share-bt .social').toggleClass('on');
	});

	$('.wrap_cal span').click(function(){
		var span =  $(this).parent().find('span');
		if($(this).hasClass('on') && $(this).index()==0){
			span.removeClass('on');
		}else{
			span.removeClass('on');
			for(var i=0;i<=$(this).index();i++){
				$(span[i]).addClass('on');
			}
		}
		var promedio = $('.wrap_cal span.on').size() / $('.wrap_cal').size();
		promedio = promedio.toString().length>3?promedio.toFixed(1):promedio;
		$('.promedio span').html(promedio);
		$('#rank-value').val(promedio);
	});

	/*
	$('.califica .button-frame').click(function(e){
		e.preventDefault();
		var promedio = $('.wrap_cal span.on').size() / $('.wrap_cal').size();
		promedio = promedio.toString().length>3?promedio.toFixed(1):promedio;
		$('.promedio span').html(promedio);
		$('#rank-value').val(promedio);
	});
	*/

	$('.menu a.logo + a + a').click(function(e){
		e.preventDefault();
		var cookie = $.cookie('escuelas'),
		    url = '/compara/escuelas/'+ (cookie != undefined ? cookie:'');
		location.href = url;
	});

	$('.search-estado select.custom-select').change(function(){
		var id;
		if((id = $(this).val())!=''){
			location.href = '/resultados-nacionales/entidad/'+id;
		}
	});

	$('.peticion h1').click(function(){
		$('.wrap_peticion, .social.on').removeClass('on');
		$(this).next().addClass('on');
	});

	if($('#content .container').hasClass('perfil')){
		$('.menu a.logo + a + a + a').click(function(e){
			e.preventDefault();
			location.href = $('.califica a.title').attr('href');
		});

		$('.tabs a.result').click(function(){
		var texts = $('text[text-anchor="start"]'),
		    text;
		for(var i=0;i<texts.length;i++){
			text = $(texts[i]);
			text.text(text.text()+' grado');
		}
		});

	}

	$('td.school').hover(function(){
		$('.tooltip').css({top:$(this).position().top,display:'block'});
	},
	function(){
		$('.tooltip').css('display','none');
	});

	if($('.container').hasClass('perfil')){
		var cct = $('span.CCT').html();
		if(!($.cookie('escuelas')) || $.cookie('escuelas').split('-').indexOf(cct)==-1){
			$('a[href="'+cct+'"]').trigger('click');
			if(!$('a[href="'+cct+'"]').size()){
				toggle_escuela(cct);
			}
		}

	}

	if($('.container').hasClass('comparar')){
		console.log(false);
		$('#general-search').submit(function(e){
			e.preventDefault();
			var url='';
			$(this).find('[name]').each(function(i,val){
				url +='&'+$(val).attr('name')+'='+$(val).val();
			});
			window.location = $(this).attr('action')+url;
		});
	}

});

function load_location_options(input,directive,options,name){
	input.prop('disabled', true);
	input.next().addClass('customSelectDisabled');
	$.post('/main/'+directive,options,function(data){
		input.html('<option value="">'+name+'</option>');
		for(x in data){
			var item = data[x];
			input.append('<option value="'+item.id+'">'+item.nombre+'</option>');
		}
		input.prop('disabled', false);
		input.next().removeClass('customSelectDisabled');
		input.trigger('change');
	},'json');
}
function set_rank_bar(x){
	var max = $('.container').hasClass('B')?173:336;
	var rank = Math.round(x/max * 100);
	var offset = x - 12;
	$('#rank-bar .bar').css('width',x+'px').show();
	$('#rank-label').html(rank+'%').css('left',offset+'px').show();
	return rank;
}
function toggle_escuela(cct){
	if(typeof($.cookie('escuelas')) == 'undefined'){
		$.cookie('escuelas',[cct]);
	}else{
		var escuelas = $.cookie('escuelas').split('-');
		var index = escuelas.indexOf(cct);
		if(index != -1){
			escuelas.pop(index);
		}else{
			escuelas.push(cct);
		}
		escuelas.sort();
		$.cookie('escuelas',escuelas.join('-'));
		$('#compara-main-button').attr('href','/compara/escuelas/'+escuelas.join('-'));
		if( $('.container.resultados').hasClass('comparar')){
			var url=document.URL.replace(new RegExp('-*'+cct),'');
			location.href = url;
		}
	}
}
function twitterIni(){
    var username =  "mejoratuescuela",
	page_proxy = '/home/twitter';
	$("#tweets .tweet p").html("cargando tweets...");
	$.getJSON(page_proxy, function(data){
		$("#tweets .tweet").css('display','none');
		$("#tweets").append('

');
		for(d in data){
			var x = data[d];
			$("#tweets ul").append('

@'+username+' '+x.text+'

');
	    	}
	    })
}
<commit_msg>error redirecciona en search de compara/escuelas<commit_after>$(document).ready(function(){
	if($('#content .container').hasClass('home'))
		twitterIni();
	$.cookie.defaults.path = '/';
	$('.jscrollpane').jScrollPane();
	$('.custom-select').customSelect();
	$('.calificacion-form').validate();
	$('.reporte-form').validate();
	$('.petition-form').validate();
	$('.contacto-form').validate();
	$('form.newsletter').validate();

	$('#ver-en-mapa').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action',$(this).attr('href'));
		$('#general-search').submit();
	});

	$('.compara-tabs a').click(function(e){
		e.preventDefault();
		var index = $(this).index();
		$('.compara-tabs a.on').removeClass('on');
		$(this).addClass('on');
		$('.compara-tab-container .tab.on').removeClass('on');
		$('.compara-tab-container .tab').eq(index).addClass('on');
	})

	$('.compara-escuela').on('click',function(e){
		e.preventDefault();
		var tr = $(this).parent().parent().toggleClass('on');
		var cct = $(this).attr('href');
		toggle_escuela(cct);
	});

	$('#content .perfil .tabs li a').click(function(e){
		e.preventDefault();
		var index = 4 - $(this).parent().index();
		$('#content .perfil .tabs li.on').removeClass('on');
		$(this).parent().addClass('on');
		$('#content .perfil .tab-container .tab.on').removeClass('on');
		$('#content .perfil .tab-container .tab').eq(index).addClass('on').jScrollPane();
		if($(this).html() == 'Resultados Educativos' ) drawCharts();
	})
	$('#rank-bar').mousemove(function(e){
		set_rank_bar(e.pageX - $(this).offset().left);
	});
	$('#rank-bar').click(function(e){
		var rank = set_rank_bar(e.pageX - $(this).offset().left);
		$('#rank-value').val(rank);
	});
	$('#rank-bar').mouseout(function(e){
		var max = $('.container').hasClass('B')?173:336;
		var x = e.pageX - $(this).offset().left;
		var y = e.pageY - $(this).offset().top;
		if((y >= 10 || y < 0) || (x < 0 || x > max)){
			var val = $('#rank-value').val();
			if(val != ''){
				set_rank_bar(Math.round(val/100*max));
			}else{
				$('#rank-bar .bar').hide();
				$('#rank-label').hide();
			}
		}
	});

	if($("#name-input") .length)
	$( "#name-input" ).autocomplete({
  		source: function(request,response){
  			$.post("/main/get_escuelas/",{
  				term : request.term,
  				entidad : $("#state-input").val(),
  				municipio : $("#municipio-input").val(),
  				localidad : $("#localidad-input").val(),
  				nivel : $("#nivel-input").val(),
  				json : true
  			},response,'json');
  		},
  		minLength: 3,
		select: function( event, ui ) {
			window.location = "/escuelas/index/"+ui.item.cct;
			return false;
		}
	}).data( "ui-autocomplete" )._renderItem = function( ul, item ){
      return $("
").append(""+item.label+""+item.address+"").appendTo(ul);
    };

	$('#map-button').click(function(e){
		e.preventDefault();
		$('#general-search').attr('action','/mapa/');
		$('#general-search').submit();

	});
	$('#state-input').change(function(e){
		$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
		load_location_options(
			$("#municipio-input"),
			'load_municipios',
			{entidad:$(this).val(),json:true},
			"Municipio"
		);
	});

	$('#municipio-input').change(function(){
		if($(this).val() != "" || ($("#state-input option:selected").val() != "" && $("#state-input option:selected").val() != 7 && $("#state-input option:selected").val() != 20 && $("#state-input option:selected").val() != 30)){
			load_location_options(
				$("#localidad-input"),
				'load_localidades',
				{municipio:$(this).val(),entidad:$("#state-input option:selected").val(),json:true},
				"Localidad"
			);
		}else{
			$("#localidad-input").prop('disabled', true).next().addClass('customSelectDisabled');
			$("#localidad-input").html('<option value="">Localidad</option>');
		}
	});

	$('#content .home .circle a.line').hover(function(){
		var x=[27,23,19];
		var i=$(this).index();
		var xP=$(this).position().left;
		$(this).parent().find('.line1').css({'left':xP+x[i-1] + 'px','display':'block'});
		$(this).parent().find('.line2').css({'left':89+xP+x[i-1]+'px','display':'block'});
	},function(){
			$(this).parent().find('.line1').css('display','none');
			$(this).parent().find('.line2').css('display','none');
	});

	$('#content .share-bt a.button-frame').click(function(e){
		e.preventDefault();
		$('#content .share-bt .social').toggleClass('on');
	});

	$('.wrap_cal span').click(function(){
		var span =  $(this).parent().find('span');
		if($(this).hasClass('on') && $(this).index()==0){
			span.removeClass('on');
		}else{
			span.removeClass('on');
			for(var i=0;i<=$(this).index();i++){
				$(span[i]).addClass('on');
			}
		}
		var promedio = $('.wrap_cal span.on').size() / $('.wrap_cal').size();
		promedio = promedio.toString().length>3?promedio.toFixed(1):promedio;
		$('.promedio span').html(promedio);
		$('#rank-value').val(promedio);
	});

	/*
	$('.califica .button-frame').click(function(e){
		e.preventDefault();
		var promedio = $('.wrap_cal span.on').size() / $('.wrap_cal').size();
		promedio = promedio.toString().length>3?promedio.toFixed(1):promedio;
		$('.promedio span').html(promedio);
		$('#rank-value').val(promedio);
	});
	*/

	$('.menu a.logo + a + a').click(function(e){
		e.preventDefault();
		var cookie = $.cookie('escuelas'),
		    url = '/compara/escuelas/'+ (cookie != undefined ? cookie:'');
		location.href = url;
	});

	$('.search-estado select.custom-select').change(function(){
		var id;
		if((id = $(this).val())!=''){
			location.href = '/resultados-nacionales/entidad/'+id;
		}
	});

	$('.peticion h1').click(function(){
		$('.wrap_peticion, .social.on').removeClass('on');
		$(this).next().addClass('on');
	});

	if($('#content .container').hasClass('perfil')){
		$('.menu a.logo + a + a + a').click(function(e){
			e.preventDefault();
			location.href = $('.califica a.title').attr('href');
		});

		$('.tabs a.result').click(function(){
		var texts = $('text[text-anchor="start"]'),
		    text;
		for(var i=0;i<texts.length;i++){
			text = $(texts[i]);
			text.text(text.text()+' grado');
		}
		});

	}

	$('td.school').hover(function(){
		$('.tooltip').css({top:$(this).position().top,display:'block'});
	},
	function(){
		$('.tooltip').css('display','none');
	});

	if($('.container').hasClass('perfil')){
		var cct = $('span.CCT').html();
		if(!($.cookie('escuelas')) || $.cookie('escuelas').split('-').indexOf(cct)==-1){
			$('a[href="'+cct+'"]').trigger('click');
			if(!$('a[href="'+cct+'"]').size()){
				toggle_escuela(cct);
			}
		}

	}

	if($('.container').hasClass('comparar')){
		console.log(false);
		$('#general-search').submit(function(e){
			e.preventDefault();
			var url='';
			$(this).find('[name]').each(function(i,val){
				url +='&'+$(val).attr('name')+'='+$(val).val();
			});
			window.location = $(this).attr('action')+url;
		});
	}

});

function load_location_options(input,directive,options,name){
	input.prop('disabled', true);
	input.next().addClass('customSelectDisabled');
	$.post('/main/'+directive,options,function(data){
		input.html('<option value="">'+name+'</option>');
		for(x in data){
			var item = data[x];
			input.append('<option value="'+item.id+'">'+item.nombre+'</option>');
		}
		input.prop('disabled', false);
		input.next().removeClass('customSelectDisabled');
		input.trigger('change');
	},'json');
}
function set_rank_bar(x){
	var max = $('.container').hasClass('B')?173:336;
	var rank = Math.round(x/max * 100);
	var offset = x - 12;
	$('#rank-bar .bar').css('width',x+'px').show();
	$('#rank-label').html(rank+'%').css('left',offset+'px').show();
	return rank;
}
function toggle_escuela(cct){
	if(typeof($.cookie('escuelas')) == 'undefined'){
		$.cookie('escuelas',[cct]);
	}else{
		var escuelas = $.cookie('escuelas').split('-');
		var index = escuelas.indexOf(cct);
		if(index != -1){
			escuelas.pop(index);
		}else{
			escuelas.push(cct);
		}
		escuelas.sort();
		$.cookie('escuelas',escuelas.join('-'));
		$('#compara-main-button').attr('href','/compara/escuelas/'+escuelas.join('-'));
		if( $('.container.resultados').hasClass('comparar')){
			var url=document.URL.replace(new RegExp('-*'+cct),'');
			if(document.URL != url)
				location.href = url;
		}
	}
}
function twitterIni(){
    var username =  "mejoratuescuela",
	page_proxy = '/home/twitter';
	$("#tweets .tweet p").html("cargando tweets...");
	$.getJSON(page_proxy, function(data){
		$("#tweets .tweet").css('display','none');
		$("#tweets").append('

');
		for(d in data){
			var x = data[d];
			$("#tweets ul").append('

@'+username+' '+x.text+'

');
	    	}
	    })
}
<|endoftext|>


<commit_before>function runTest()
{
    FBTest.sysout("issue5247.START");

    FBTest.openNewTab(basePath + "dom/5247/issue5247.html", function(win)
    {
        FBTest.openFirebug();
        var panel = FBTest.selectPanel("stylesheet");

        if (FBTest.selectPanelLocationByName(panel, "issue5247.html"))
        {
            FBTest.executeContextMenuCommand(FW.Firebug.chrome.$("fbLocationList"),
                "InspectIndomPanel", function()
            {
                // xxxHonza, xxxsz: hack that fixes this text on Mac. The panel can
                // be selected asynchronously.
                setTimeout(function() {
                    onInspect();
                }, 1000);
            });
        }
        else
        {
            FBTest.testDone("issue5247.DONE");
        }
    });
}

function onInspect()
{
    var panel = FBTest.getSelectedPanel();
    if (FBTest.compare("dom", panel.name, "DOM panel must be selected now"))
    {
        var props = panel.panelNode.getElementsByClassName("memberLabel");
        var prop;

        for (var i=0; i<props.length; i++)
        {
            if (props[i].textContent == "cssRules")
            {
                prop = props[i];
                break;
            }
        }

        var config = {tagName: "tr", classes: "memberRow ordinalRow", counter: 6};
        FBTest.waitForDisplayedElement("dom", config, function(row)
        {
            var cssRulesLabels = panel.panelNode.
                querySelectorAll(".memberRow.ordinalRow[level=\"1\"] .memberLabel");
            var cssRules = [];
            for (var i=0; i<cssRulesLabels.length; i++)
            {
                var cssRulesLabel = cssRulesLabels[i];
                cssRules.push(FW.FBL.getAncestorByClass(cssRulesLabel, "memberRow").
                    getElementsByClassName("memberValueCell").item(0));
            }

            if (FBTest.compare(6, cssRules.length, "There must be 6 CSS rules"))
            {
                var expectedCSSRules =
                [
                    "CSSCharsetRule utf-8",
                    "CSSImportRule external/externalStylesheet.css",
                    "CSSMediaRule (min-width: 500px) and (max-width: 700px)",
                    "CSSFontFaceRule \"TitilliumMaps\"",
                    "CSSKeyframesRule slidein",
                    "CSSStyleRule #internalRule"
                ];

                // xxxsz: We don't check the tooltips yet
                for (var i=0; i<cssRules.length; i++)
                {
                    FBTest.compare(expectedCSSRules[i], cssRules[i].textContent, (i+1)+
                        ". rule must be '"+expectedCSSRules[i]+"'");
                }
            }

            FBTest.testDone("issue5247.DONE");
        });

        FBTest.click(prop);
    }
}
<commit_msg>FBTest: fix test for dom/5247/issue5247.js<commit_after>function runTest()
{
    FBTest.sysout("issue5247.START");

    FBTest.openNewTab(basePath + "dom/5247/issue5247.html", function(win)
    {
        FBTest.openFirebug();
        var panel = FBTest.selectPanel("stylesheet");

        if (FBTest.selectPanelLocationByName(panel, "issue5247.html"))
        {
            FBTest.executeContextMenuCommand(FW.Firebug.chrome.$("fbLocationList"),
                "InspectIndomPanel", function()
            {
                // xxxHonza, xxxsz: hack that fixes this test on Mac. The panel can
                // be selected asynchronously.
                setTimeout(function() {
                    onInspect();
                }, 1000);
            });
        }
        else
        {
            FBTest.testDone("issue5247.DONE");
        }
    });
}

function onInspect()
{
    var panel = FBTest.getSelectedPanel();
    if (FBTest.compare("dom", panel.name, "DOM panel must be selected now"))
    {
        var props = panel.panelNode.getElementsByClassName("memberLabel");
        var prop;

        for (var i=0; i<props.length; i++)
        {
            var propName = props[i].lastChild.textContent
            if (propName == "cssRules")
            {
                prop = props[i];
                break;
            }
        }

        if (!FBTest.ok(prop, "cssRules property must be there"))
        {
            FBTest.testDone("issue5247.DONE");
            return;
        }

        var config = {tagName: "tr", classes: "memberRow ordinalRow", counter: 6};
        FBTest.waitForDisplayedElement("dom", config, function(row)
        {
            var cssRulesLabels = panel.panelNode.
                querySelectorAll(".memberRow.ordinalRow[level=\"1\"] .memberLabel");
            var cssRules = [];
            for (var i=0; i<cssRulesLabels.length; i++)
            {
                var cssRulesLabel = cssRulesLabels[i];
                cssRules.push(FW.FBL.getAncestorByClass(cssRulesLabel, "memberRow").
                    getElementsByClassName("memberValueCell").item(0));
            }

            if (FBTest.compare(6, cssRules.length, "There must be 6 CSS rules"))
            {
                var expectedCSSRules =
                [
                    "CSSCharsetRule utf-8",
                    "CSSImportRule external/externalStylesheet.css",
                    "CSSMediaRule (min-width: 500px) and (max-width: 700px)",
                    "CSSFontFaceRule \"TitilliumMaps\"",
                    "CSSKeyframesRule slidein",
                    "CSSStyleRule #internalRule"
                ];

                // xxxsz: We don't check the tooltips yet
                for (var i=0; i<cssRules.length; i++)
                {
                    FBTest.compare(expectedCSSRules[i], cssRules[i].textContent, (i+1)+
                        ". rule must be '"+expectedCSSRules[i]+"'");
                }
            }

            FBTest.testDone("issue5247.DONE");
        });

        FBTest.click(prop);
    }
}
<|endoftext|>