<commit_before>acp.controller('search_controller', ['$rootScope', '$scope', '$http', 'MyService',
                function($rootScope, $scope, $http, MyService) {

    $scope.address = "7000 Briarcliff Gables Cir NE";
    $scope.city = "Atlanta";
    $scope.state = "GA";
    $scope.country = "";
    $scope.postal_code = "30329";
    $scope.radius = 1000;

    $scope.price;
    $scope.link_name;
    $scope.link;
    $scope.num_gas;
    $scope.num_bank;
    $scope.num_supermarket;
    $scope.num_restaurant;

    $scope.rating;
    $scope.review;

    $scope.lat;
    $scope.lng;
    $scope.place_id;
    $scope.reference;

    $scope.google_place_key;
    $scope.zillow_key;

    $scope.allow_to_collect_data = true;

    $scope.search = function() {
        $scope.collect_data();
        $scope.getAddress();
        $scope.getZillow();

        setTimeout(function () {
            $scope.getPlaceDetails();
        }, 3000);
    }

    $scope.getAPIkey = function() {
        // get google place key
        var data = {
            'api_name' : "google_place_api"
        }

        $http({
            url: 'php/get_api_key.php',
            method: "POST",
            data: data
        })
        .success(function(data, status, headers, config) {
            console.log(status + ' - get API key');
            $scope.data = data;
        })
        .error(function(data, status, headers, config) {
            console.log('error');
        }).then(function(data, status, headers, config) {
            $scope.google_place_key = $scope.data;
        });

        // get zillow key
        var data = {
            'api_name' : "zillow_api"
        }

        $http({
            url: 'php/get_api_key.php',
            method: "POST",
            data: data
        })
        .success(function(data, status, headers, config) {
            console.log(status + ' - get API key');
            $scope.data = data;
        })
        .error(function(data, status, headers, config) {
            console.log('error');
        }).then(function(data, status, headers, config) {
            $scope.zillow_key = $scope.data;
        });
    }
    $scope.getAPIkey();

    $scope.collect_data = function() {
        if ($scope.allow_to_collect_data == true) {
            var data = {
                'address'     : $scope.address,
                'city'        : $scope.city,
                'state'       : $scope.state,
                'postal_code' : $scope.postal_code,
                'radius'      : $scope.radius
            }

            $http({
                url: 'php/collect_data.php',
                method: "POST",
                data: data
            })
            .success(function(data, status, headers, config) {
                console.log(status);
                $scope.data = data;
            })
            .error(function(data, status, headers, config) {
                console.log('error');
            }).then(function(data, status, headers, config){
                console.log($scope.data);
            });
        }
    }

    $scope.getAddress = function() {
        var url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=";
        var address = $scope.address + "+" + $scope.city + "+" + $scope.state + "+" + $scope.postal_code;
        address = address.replace(/\s+/g, '+').toLowerCase();
        var api_key = '&key=' + $scope.google_place_key;

        $http({
            url: url + address + api_key,
            method: "GET",
            dataType: 'json'
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            var json = $scope.data;
            for(i = 0; i < json.results.length; i++) {
                $scope.place    = json.results[i].formatted_address;
                $scope.lat      = json.results[i].geometry.location.lat;
                $scope.lng      = json.results[i].geometry.location.lng;
                $scope.place_id = json.results[i].place_id;
            }
            $scope.getNearby();
            $scope.getLocation();
        });
    };

    $scope.getLocation = function() {
        var request = {
            placeId: $scope.place_id
        };

        var map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: $scope.lat, lng: $scope.lng},
            zoom: 15
        });

        var marker = new google.maps.Marker({
            position: {lat: $scope.lat, lng: $scope.lng},
            map: map
        });

        var service = new google.maps.places.PlacesService(map);

        service.getDetails(request, function(place, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                var extraordinary = google.maps.places.RatingLevel.EXTRAORDINARY;
                var excellent     = google.maps.places.RatingLevel.EXCELLENT;
                var very_good     = google.maps.places.RatingLevel.VERY_GOOD;
                var good          = google.maps.places.RatingLevel.GOOD;
                $scope.rating = (extraordinary * 4 + excellent * 3 + very_good * 2 + good * 1) / 4.8
                $scope.rating = Math.round($scope.rating * 100) / 100
            }
        });
    }

    $scope.getPlaceDetails = function() {
        var url = "https://maps.googleapis.com/maps/api/place/details/json?";
        var place = "placeid=" + $scope.place_id;
        var api_key = '&key=' + $scope.google_place_key;

        $http({
            url: url + place + api_key,
            method: "GET",
            dataType: 'json'
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            var street_number = $scope.data.result.address_components[0].short_name;
            var street_name   = $scope.data.result.address_components[1].short_name;
            var city          = $scope.data.result.address_components[2].short_name;
            var county        = $scope.data.result.address_components[3].short_name;
            var state         = $scope.data.result.address_components[4].short_name;
            var country       = $scope.data.result.address_components[5].short_name;
            var postal_code   = $scope.data.result.address_components[6].short_name;

            MyService.result.isSet       = true;
            MyService.result.address     = street_number + " " + street_name;
            MyService.result.city        = city;
            MyService.result.county      = county;
            MyService.result.state       = state;
            MyService.result.postal_code = postal_code;
            MyService.result.radius      = $scope.radius;
            MyService.result.price       = $scope.price;
            MyService.result.link        = $scope.link;
            MyService.result.num_gas     = $scope.num_gas;
            MyService.result.num_bank    = $scope.num_bank;
            MyService.result.num_supermarket = $scope.num_supermarket;
            MyService.result.num_restaurant  = $scope.num_restaurant;
            MyService.result.rating      = $scope.rating;
            MyService.result.lat         = $scope.lat;
            MyService.result.lng         = $scope.lng;
            MyService.result.place_id    = $scope.place_id;
        });
    }

    $scope.getNearby = function() {
        var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
        var location    = "location=" + $scope.lat +","+ $scope.lng;
        var radius      = "&radius=" + $scope.radius;
        var restaurant  = "&type=restaurant";
        var supermarket = "&type=supermarket";
        var bank        = "&type=bank";
        var gas         = "&type=gas+station";
        var api_key     = '&key=' + $scope.google_place_key;

        $http({
            url: url + location + radius + restaurant + api_key,
            method: "GET",
            dataType: 'json'
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            $scope.num_restaurant = $scope.data.results.length;
        });

        $http({
            url: url + location + radius + supermarket + api_key,
            method: "GET",
            dataType: 'json'
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            $scope.num_supermarket = $scope.data.results.length;
        });

        $http({
            url: url + location + radius + bank + api_key,
            method: "GET",
            dataType: 'json'
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            $scope.num_bank = $scope.data.results.length;
        });

        $http({
            url: url + location + radius + gas + api_key,
            method: "GET",
            dataType: 'json'
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            $scope.num_gas = $scope.data.results.length;
        });
    }

    $scope.getZillow = function() {
        var url           = "http://www.zillow.com/webservice/GetSearchResults.htm?";
        var ZWSID         = "zws-id=" + $scope.zillow_key;
        var address       = "&address=" + $scope.address.replace(/\s+/g, '+').toLowerCase();
        var citystatezip  = "&citystatezip=Atlanta%2C+GA";
        var rentzestimate = "&rentzestimate=true";
        $http({
            url: url + ZWSID + address + citystatezip + rentzestimate,
            method: "GET"
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            var parser  = new DOMParser();
            var xmlDoc  = parser.parseFromString($scope.data, "text/xml");

            var results;
            try {
                results = xmlDoc.getElementsByTagName("response")[0].childNodes[0];
            }
            catch(err) {
                $scope.link_name = "not available";
                $scope.price     = "not available";
            }

            var links         = results.getElementsByTagName("result")[0].childNodes[1];
            var rentzestimate = results.getElementsByTagName("result")[0].childNodes[4];

            try {
                var link    = links.getElementsByTagName("homedetails")[0].childNodes[0].nodeValue;
                $scope.link_name = "Zillow"
                $scope.link = link;
            }
            catch(err) {
                $scope.link_name =  "not available";
            }

            try {
                var amount = rentzestimate.getElementsByTagName("amount")[0].childNodes[0].nodeValue;
                $scope.price = "$" + amount + "+ /mo";
            }
            catch(err) {
                $scope.price = "not available";
            }
        });
    }

    $scope.clearFunc = function() {
        $scope.address = "";
        $scope.city = "";
        $scope.state = "";
        $scope.country = "";
        $scope.postal_code = "";
        $scope.rating = "";
        $scope.price = "";
        $scope.num_gas = "";
        $scope.num_bank = "";
        $scope.num_supermarket = "";
        $scope.num_restaurant = "";
        $scope.link_name = "";
        $scope.link = "";
    };

    $rootScope.$on('check_price', function(event, data) {
        $scope.data        = data;
        $scope.address     = $scope.data[0].address;
        $scope.city        = $scope.data[0].city;
        $scope.state       = $scope.data[0].state;
        $scope.postal_code = $scope.data[0].postal_code;
        $scope.radius      = $scope.data[0].radius;
        $scope.search();
    });
}]);
<commit_msg>remove the hardcoded location<commit_after>acp.controller('search_controller', ['$rootScope', '$scope', '$http', 'MyService',
                function($rootScope, $scope, $http, MyService) {

    $scope.address = "";
    $scope.city = "";
    $scope.state = "";
    $scope.country = "";
    $scope.postal_code = "";
    $scope.radius;

    $scope.price;
    $scope.link_name;
    $scope.link;
    $scope.num_gas;
    $scope.num_bank;
    $scope.num_supermarket;
    $scope.num_restaurant;

    $scope.rating;
    $scope.review;

    $scope.lat;
    $scope.lng;
    $scope.place_id;
    $scope.reference;

    $scope.google_place_key;
    $scope.zillow_key;

    $scope.allow_to_collect_data = true;

    $scope.search = function() {
        $scope.collect_data();
        $scope.getAddress();
        $scope.getZillow();

        setTimeout(function () {
            $scope.getPlaceDetails();
        }, 3000);
    }

    $scope.getAPIkey = function() {
        // get google place key
        var data = {
            'api_name' : "google_place_api"
        }

        $http({
            url: 'php/get_api_key.php',
            method: "POST",
            data: data
        })
        .success(function(data, status, headers, config) {
            console.log(status + ' - get API key');
            $scope.data = data;
        })
        .error(function(data, status, headers, config) {
            console.log('error');
        }).then(function(data, status, headers, config) {
            $scope.google_place_key = $scope.data;
        });

        // get zillow key
        var data = {
            'api_name' : "zillow_api"
        }

        $http({
            url: 'php/get_api_key.php',
            method: "POST",
            data: data
        })
        .success(function(data, status, headers, config) {
            console.log(status + ' - get API key');
            $scope.data = data;
        })
        .error(function(data, status, headers, config) {
            console.log('error');
        }).then(function(data, status, headers, config) {
            $scope.zillow_key = $scope.data;
        });
    }
    $scope.getAPIkey();

    $scope.collect_data = function() {
        if ($scope.allow_to_collect_data == true) {
            var data = {
                'address'     : $scope.address,
                'city'        : $scope.city,
                'state'       : $scope.state,
                'postal_code' : $scope.postal_code,
                'radius'      : $scope.radius
            }

            $http({
                url: 'php/collect_data.php',
                method: "POST",
                data: data
            })
            .success(function(data, status, headers, config) {
                console.log(status);
                $scope.data = data;
            })
            .error(function(data, status, headers, config) {
                console.log('error');
            }).then(function(data, status, headers, config){
                console.log($scope.data);
            });
        }
    }

    $scope.getAddress = function() {
        var url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=";
        var address = $scope.address + "+" + $scope.city + "+" + $scope.state + "+" + $scope.postal_code;
        address = address.replace(/\s+/g, '+').toLowerCase();
        var api_key = '&key=' + $scope.google_place_key;

        $http({
            url: url + address + api_key,
            method: "GET",
            dataType: 'json'
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            var json = $scope.data;
            for(i = 0; i < json.results.length; i++) {
                $scope.place    = json.results[i].formatted_address;
                $scope.lat      = json.results[i].geometry.location.lat;
                $scope.lng      = json.results[i].geometry.location.lng;
                $scope.place_id = json.results[i].place_id;
            }
            $scope.getNearby();
            $scope.getLocation();
        });
    };

    $scope.getLocation = function() {
        var request = {
            placeId: $scope.place_id
        };

        var map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: $scope.lat, lng: $scope.lng},
            zoom: 15
        });

        var marker = new google.maps.Marker({
            position: {lat: $scope.lat, lng: $scope.lng},
            map: map
        });

        var service = new google.maps.places.PlacesService(map);

        service.getDetails(request, function(place, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                var extraordinary = google.maps.places.RatingLevel.EXTRAORDINARY;
                var excellent     = google.maps.places.RatingLevel.EXCELLENT;
                var very_good     = google.maps.places.RatingLevel.VERY_GOOD;
                var good          = google.maps.places.RatingLevel.GOOD;
                $scope.rating = (extraordinary * 4 + excellent * 3 + very_good * 2 + good * 1) / 4.8
                $scope.rating = Math.round($scope.rating * 100) / 100
            }
        });
    }

    $scope.getPlaceDetails = function() {
        var url = "https://maps.googleapis.com/maps/api/place/details/json?";
        var place = "placeid=" + $scope.place_id;
        var api_key = '&key=' + $scope.google_place_key;

        $http({
            url: url + place + api_key,
            method: "GET",
            dataType: 'json'
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            var street_number = $scope.data.result.address_components[0].short_name;
            var street_name   = $scope.data.result.address_components[1].short_name;
            var city          = $scope.data.result.address_components[2].short_name;
            var county        = $scope.data.result.address_components[3].short_name;
            var state         = $scope.data.result.address_components[4].short_name;
            var country       = $scope.data.result.address_components[5].short_name;
            var postal_code   = $scope.data.result.address_components[6].short_name;

            MyService.result.isSet       = true;
            MyService.result.address     = street_number + " " + street_name;
            MyService.result.city        = city;
            MyService.result.county      = county;
            MyService.result.state       = state;
            MyService.result.postal_code = postal_code;
            MyService.result.radius      = $scope.radius;
            MyService.result.price       = $scope.price;
            MyService.result.link        = $scope.link;
            MyService.result.num_gas     = $scope.num_gas;
            MyService.result.num_bank    = $scope.num_bank;
            MyService.result.num_supermarket = $scope.num_supermarket;
            MyService.result.num_restaurant  = $scope.num_restaurant;
            MyService.result.rating      = $scope.rating;
            MyService.result.lat         = $scope.lat;
            MyService.result.lng         = $scope.lng;
            MyService.result.place_id    = $scope.place_id;
        });
    }

    $scope.getNearby = function() {
        var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
        var location    = "location=" + $scope.lat +","+ $scope.lng;
        var radius      = "&radius=" + $scope.radius;
        var restaurant  = "&type=restaurant";
        var supermarket = "&type=supermarket";
        var bank        = "&type=bank";
        var gas         = "&type=gas+station";
        var api_key     = '&key=' + $scope.google_place_key;

        $http({
            url: url + location + radius + restaurant + api_key,
            method: "GET",
            dataType: 'json'
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            $scope.num_restaurant = $scope.data.results.length;
        });

        $http({
            url: url + location + radius + supermarket + api_key,
            method: "GET",
            dataType: 'json'
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            $scope.num_supermarket = $scope.data.results.length;
        });

        $http({
            url: url + location + radius + bank + api_key,
            method: "GET",
            dataType: 'json'
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            $scope.num_bank = $scope.data.results.length;
        });

        $http({
            url: url + location + radius + gas + api_key,
            method: "GET",
            dataType: 'json'
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            $scope.num_gas = $scope.data.results.length;
        });
    }

    $scope.getZillow = function() {
        var url           = "http://www.zillow.com/webservice/GetSearchResults.htm?";
        var ZWSID         = "zws-id=" + $scope.zillow_key;
        var address       = "&address=" + $scope.address.replace(/\s+/g, '+').toLowerCase();
        var citystatezip  = "&citystatezip=Atlanta%2C+GA";
        var rentzestimate = "&rentzestimate=true";
        $http({
            url: url + ZWSID + address + citystatezip + rentzestimate,
            method: "GET"
        }).success(function(data, status, headers, config) {
            $scope.data = data;
        }).error(function(data, status, headers, config) {
            $scope.status = status;
        }).then(function(data, status, headers, config) {
            var parser  = new DOMParser();
            var xmlDoc  = parser.parseFromString($scope.data, "text/xml");

            var results;
            try {
                results = xmlDoc.getElementsByTagName("response")[0].childNodes[0];
            }
            catch(err) {
                $scope.link_name = "not available";
                $scope.price     = "not available";
            }

            var links         = results.getElementsByTagName("result")[0].childNodes[1];
            var rentzestimate = results.getElementsByTagName("result")[0].childNodes[4];

            try {
                var link    = links.getElementsByTagName("homedetails")[0].childNodes[0].nodeValue;
                $scope.link_name = "Zillow"
                $scope.link = link;
            }
            catch(err) {
                $scope.link_name =  "not available";
            }

            try {
                var amount = rentzestimate.getElementsByTagName("amount")[0].childNodes[0].nodeValue;
                $scope.price = "$" + amount + "+ /mo";
            }
            catch(err) {
                $scope.price = "not available";
            }
        });
    }

    $scope.clearFunc = function() {
        $scope.address = "";
        $scope.city = "";
        $scope.state = "";
        $scope.country = "";
        $scope.postal_code = "";
        $scope.rating = "";
        $scope.price = "";
        $scope.num_gas = "";
        $scope.num_bank = "";
        $scope.num_supermarket = "";
        $scope.num_restaurant = "";
        $scope.link_name = "";
        $scope.link = "";
    };

    $rootScope.$on('check_price', function(event, data) {
        $scope.data        = data;
        $scope.address     = $scope.data[0].address;
        $scope.city        = $scope.data[0].city;
        $scope.state       = $scope.data[0].state;
        $scope.postal_code = $scope.data[0].postal_code;
        $scope.radius      = $scope.data[0].radius;
        $scope.search();
    });
}]);
<|endoftext|>


<commit_before>//= require ./lib/jquery
//= require ./lib/shim
//= require ./lib/bootstrap
//= require ./lib/highcharts
//= require ./lib/highcharts
//= require_tree ./application
//= require ./nav_items
//= require ./wysiwyg

! function () {

  var $window = $ (window)

  $.livequery.registerPlugin ("html");

  $.application.debug = true;

  // $('.tab-content').application
  //   (function ($this) { $this.children ().maximise ('height'); });

  $ ('.date.input').application
    (true, function ($this) { $this.koiDatePicker () });

  // $('.rich.text.input').application
  //   (true, function ($this) { $this.koiEditor () });

  $ ('.sortable.fields').application
    (true, function ($this) { $this.koiSortable () });

  $ ('.nested-fields').application
    (true, function ($this) { $this.koiNestedFields () });

  $ ('.superfish').application
    (true, function ($this) { $this.superfish ({ delay:100 }); });

  $ ('.modal').livequery (function ()
    {
      $ (this).on ('shown', function () { console.log ('foo')  })
    })

  var fnModal = $.fn.modal

  $.fn.modal = function ()
  {
    var it = $ (this)

    if (it.data ('modal')) return fnModal.apply (this, arguments)

    fnModal.apply (this, arguments)

    if (it.hasClass ('fade')) it.on ('show', function () { it.css ('top', $window.scrollTop () + 100) })
    return this
  }

} (jQuery);
<commit_msg>Log statement left in.<commit_after>//= require ./lib/jquery
//= require ./lib/shim
//= require ./lib/bootstrap
//= require ./lib/highcharts
//= require ./lib/highcharts
//= require_tree ./application
//= require ./nav_items
//= require ./wysiwyg

! function () {

  var $window = $ (window)

  $.livequery.registerPlugin ("html");

  $.application.debug = true;

  // $('.tab-content').application
  //   (function ($this) { $this.children ().maximise ('height'); });

  $ ('.date.input').application
    (true, function ($this) { $this.koiDatePicker () });

  // $('.rich.text.input').application
  //   (true, function ($this) { $this.koiEditor () });

  $ ('.sortable.fields').application
    (true, function ($this) { $this.koiSortable () });

  $ ('.nested-fields').application
    (true, function ($this) { $this.koiNestedFields () });

  $ ('.superfish').application
    (true, function ($this) { $this.superfish ({ delay:100 }); });

  var fnModal = $.fn.modal

  $.fn.modal = function ()
  {
    var it = $ (this)

    if (it.data ('modal')) return fnModal.apply (this, arguments)

    fnModal.apply (this, arguments)

    if (it.hasClass ('fade')) it.on ('show', function () { it.css ('top', $window.scrollTop () + 100) })
    return this
  }

} (jQuery);
<|endoftext|>


<commit_before>Template['home'].helpers({
  url: function(){
    var hex = Math.floor(Math.random() * 1000000000).toString(16);
    return "http://clink.meteor.com/c/" + hex
  },
});

Template['home'].events({
    'click .expose-share-url': function(e) {
        $('.expose-share-url').fadeOut('fast', function() {
            $('.share-url-wrap').removeClass('hide').fadeIn('fast');
        });
        // $('.share-url-wrap').removeClass('hide').fadeIn('fast');
    }
});<commit_msg>upping the url<commit_after>Template['home'].helpers({
  url: function(){
    var hex = Math.floor(Math.random() * 1000000000).toString(16);
    return "http://clinit.co/c/" + hex
  },
});

Template['home'].events({
    'click .expose-share-url': function(e) {
        $('.expose-share-url').fadeOut('fast', function() {
            $('.share-url-wrap').removeClass('hide').fadeIn('fast');
        });
        // $('.share-url-wrap').removeClass('hide').fadeIn('fast');
    }
});<|endoftext|>


<commit_before>/* eslint-env mocha */
/* eslint max-nested-callbacks: ["error", 8] */

'use strict'

const chai = require('chai')
const dirtyChai = require('dirty-chai')
const expect = chai.expect
chai.use(dirtyChai)

module.exports = (common) => {
  describe('.miscellaneous', () => {
    let ipfs
    let withGo

    before(function (done) {
      // CI takes longer to instantiate the daemon, so we need to increase the
      // timeout for the before step
      this.timeout(60 * 1000)

      common.setup((err, factory) => {
        expect(err).to.not.exist()
        factory.spawnNode((err, node) => {
          expect(err).to.not.exist()
          ipfs = node
          ipfs.id((err, id) => {
            expect(err).to.not.exist()
            withGo = id.agentVersion.startsWith('go-ipfs')
            done()
          })
        })
      })
    })

    after((done) => {
      common.teardown(done)
    })

    it('.id', (done) => {
      ipfs.id((err, res) => {
        expect(err).to.not.exist()
        expect(res).to.have.a.property('id')
        expect(res).to.have.a.property('publicKey')
        done()
      })
    })

    it('.version', (done) => {
      ipfs.version((err, result) => {
        expect(err).to.not.exist()
        expect(result).to.have.a.property('version')
        expect(result).to.have.a.property('commit')
        expect(result).to.have.a.property('repo')
        done()
      })
    })

    it('.dns', (done) => {
      ipfs.dns('ipfs.io', (err, path) => {
        expect(err).to.not.exist()
        expect(path).to.exist()
        done()
      })
    })

    it('.id Promises support', () => {
      return ipfs.id()
        .then((res) => {
          expect(res).to.have.a.property('id')
          expect(res).to.have.a.property('publicKey')
        })
    })

    it('.version Promises support', () => {
      return ipfs.version()
        .then((result) => {
          expect(result).to.have.a.property('version')
          expect(result).to.have.a.property('commit')
          expect(result).to.have.a.property('repo')
        })
    })

    it('.dns Promises support', () => {
      return ipfs.dns('ipfs.io')
        .then((res) => {
          expect(res).to.exist()
        })
    })

    // must be last test to run
    it('.stop', function (done) {
      this.timeout(10 * 1000)
      ipfs.stop((err) => {
        // TODO: go-ipfs returns an error, https://github.com/ipfs/go-ipfs/issues/4078
        if (!withGo) {
          expect(err).to.not.exist()
        }
        // Trying to stop an already stopped node should return an error
        // as the node can't respond to requests anymore
        ipfs.stop((err) => {
          expect(err).to.exist()
          done()
        })
      })
    })
  })
}
<commit_msg>chore: bump dns test timeout<commit_after>/* eslint-env mocha */
/* eslint max-nested-callbacks: ["error", 8] */

'use strict'

const chai = require('chai')
const dirtyChai = require('dirty-chai')
const expect = chai.expect
chai.use(dirtyChai)

module.exports = (common) => {
  describe('.miscellaneous', () => {
    let ipfs
    let withGo

    before(function (done) {
      // CI takes longer to instantiate the daemon, so we need to increase the
      // timeout for the before step
      this.timeout(60 * 1000)

      common.setup((err, factory) => {
        expect(err).to.not.exist()
        factory.spawnNode((err, node) => {
          expect(err).to.not.exist()
          ipfs = node
          ipfs.id((err, id) => {
            expect(err).to.not.exist()
            withGo = id.agentVersion.startsWith('go-ipfs')
            done()
          })
        })
      })
    })

    after((done) => {
      common.teardown(done)
    })

    it('.id', (done) => {
      ipfs.id((err, res) => {
        expect(err).to.not.exist()
        expect(res).to.have.a.property('id')
        expect(res).to.have.a.property('publicKey')
        done()
      })
    })

    it('.version', (done) => {
      ipfs.version((err, result) => {
        expect(err).to.not.exist()
        expect(result).to.have.a.property('version')
        expect(result).to.have.a.property('commit')
        expect(result).to.have.a.property('repo')
        done()
      })
    })

    it('.dns', function (done) {
      this.timeout(20 * 1000)

      ipfs.dns('ipfs.io', (err, path) => {
        expect(err).to.not.exist()
        expect(path).to.exist()
        done()
      })
    })

    it('.id Promises support', () => {
      return ipfs.id()
        .then((res) => {
          expect(res).to.have.a.property('id')
          expect(res).to.have.a.property('publicKey')
        })
    })

    it('.version Promises support', () => {
      return ipfs.version()
        .then((result) => {
          expect(result).to.have.a.property('version')
          expect(result).to.have.a.property('commit')
          expect(result).to.have.a.property('repo')
        })
    })

    // must be last test to run
    it('.stop', function (done) {
      this.timeout(10 * 1000)
      ipfs.stop((err) => {
        // TODO: go-ipfs returns an error, https://github.com/ipfs/go-ipfs/issues/4078
        if (!withGo) {
          expect(err).to.not.exist()
        }
        // Trying to stop an already stopped node should return an error
        // as the node can't respond to requests anymore
        ipfs.stop((err) => {
          expect(err).to.exist()
          done()
        })
      })
    })
  })
}
<|endoftext|>


<commit_before>'use strict';

var RSVP = require('rsvp');
var config  = require('../config');
var undefsafe = require('undefsafe');

var processors = {
  // list of available processors on the serverside
  supports: ['markdown', 'jade', 'coffeescript', 'less', 'jsx', 'myth', 'stylus', 'livescript'],

  support: function (language) {
    return processors.supports.indexOf(language) !== -1;
  },

  mime: {
    'js': 'application/javascript',
    'css': 'text/css',
    'html': 'text/html',
    'md': 'text/x-markdown',
    'mdown': 'text/x-markdown',
    'markdown': 'text/x-markdown',
    'coffee': 'application/javascript',
    'coffeescript': 'application/javascript',
    'jsx': 'application/javascript',
    'json': 'application/json',
    'ts': 'application/javascript',
    'ls': 'application/javascript',
    'styl': 'text/css',
    'less': 'text/css',
    'sass': 'text/css',
    'scss': 'text/css',
    'myth': 'text/css',
    '_default': 'text/plain'
  },

  aliases: {
    'md': 'markdown',
    'mdown': 'markdown',
    'coffee': 'coffeescript',
    'pde': 'processing',
    'ts': 'typescript',
    'styl': 'stylus',
    'ls': 'livescript'
  },

  lookup: {
    'markdown': 'html',
    'jade': 'html',
    'coffeescript': 'javascript',
    'jsx': 'javascript',
    'pde': 'javascript',
    'ts': 'javascript',
    'livescript': 'javascript',
    'stylus': 'css',
    'less': 'css',
    'sass': 'css',
    'scss': 'css',
    'myth': 'css'
  },
};

processors.run = (function () {
  if (!undefsafe(config, 'processor.address')) {
    return require('./fork');
  }

  try {
    var run = require('./socket');
    processors.supports.push('scss', 'sass');
    return run;
  } catch (e) {
    return require('./fork');
  }
})();

module.exports = processors;

if (!module.parent) {
  process.on('message', function (event) {
    var processor = require('./' + event.language);
    if (event.language && typeof processor === 'function') {
      processor(event.data).then(function (output) {
        process.send(JSON.stringify(output));
      }, function (error) {
        console.error(event.language, 'error:: ', error);
      }).then(function () {
        process.exit(0);
      });
    }
  });
}
<commit_msg>Fixed #1832<commit_after>'use strict';

var RSVP = require('rsvp');
var config  = require('../config');
var undefsafe = require('undefsafe');

var processors = {
  // list of available processors on the serverside
  supports: ['markdown', 'jade', 'coffeescript', 'less', 'jsx', 'myth', 'stylus', 'livescript'],

  support: function (language) {
    return processors.supports.indexOf(language) !== -1;
  },

  mime: {
    'js': 'application/javascript',
    'css': 'text/css',
    'html': 'text/html',
    'md': 'text/x-markdown',
    'mdown': 'text/x-markdown',
    'markdown': 'text/x-markdown',
    'coffee': 'application/javascript',
    'coffeescript': 'application/javascript',
    'jsx': 'application/javascript',
    'json': 'application/json',
    'ts': 'application/javascript',
    'ls': 'application/javascript',
    'styl': 'text/css',
    'less': 'text/css',
    'sass': 'text/css',
    'scss': 'text/css',
    'myth': 'text/css',
    'svg': 'image/svg+xml',
    '_default': 'text/plain'
  },

  aliases: {
    'md': 'markdown',
    'mdown': 'markdown',
    'coffee': 'coffeescript',
    'pde': 'processing',
    'ts': 'typescript',
    'styl': 'stylus',
    'ls': 'livescript'
  },

  lookup: {
    'markdown': 'html',
    'jade': 'html',
    'coffeescript': 'javascript',
    'jsx': 'javascript',
    'pde': 'javascript',
    'ts': 'javascript',
    'livescript': 'javascript',
    'stylus': 'css',
    'less': 'css',
    'sass': 'css',
    'scss': 'css',
    'myth': 'css'
  },
};

processors.run = (function () {
  if (!undefsafe(config, 'processor.address')) {
    return require('./fork');
  }

  try {
    var run = require('./socket');
    processors.supports.push('scss', 'sass');
    return run;
  } catch (e) {
    return require('./fork');
  }
})();

module.exports = processors;

if (!module.parent) {
  process.on('message', function (event) {
    var processor = require('./' + event.language);
    if (event.language && typeof processor === 'function') {
      processor(event.data).then(function (output) {
        process.send(JSON.stringify(output));
      }, function (error) {
        console.error(event.language, 'error:: ', error);
      }).then(function () {
        process.exit(0);
      });
    }
  });
}
<|endoftext|>


<commit_before>    var player;
    var platforms;
    var cursors;
    var cielo;

    var stars;
    var score = 0;
    var scoreText;
    var game;

    function crearNivel(nivel){

        switch(nivel) {
        case '0':
            game = new Phaser.Game(800, 600, Phaser.AUTO, 'juegoId', { preload: preload, create: create0, update: update });
            break;
        case '1':
            game = new Phaser.Game(800, 600, Phaser.AUTO, 'juegoId', { preload: preload, create: create1, update: update });
            break;
        case '2':
            game = new Phaser.Game(800, 600, Phaser.AUTO, 'juegoId', { preload: preload, create: create2, update: update });
            break;
        default: noHayNiveles();
            break;
}

    }

    function preload() {

        game.load.image('sky', 'assets/sky.png');
        game.load.image('ground', 'assets/platform.png');
        game.load.image('ground2', 'assets/platform2.png');
        game.load.image('star', 'assets/star.png');
        game.load.image('cielo', 'assets/heaven.png');

        game.load.spritesheet('dude', 'assets/dude.png', 32, 48);

    }

    function create0() {

        //  We're going to be using physics, so enable the Arcade Physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        //  A simple background for our game
        game.add.sprite(0, 0, 'sky');

        //  The platforms group contains the ground and the 2 ledges we can jump on
        platforms = game.add.group();
        cielo = game.add.group();
        //  We will enable physics for any object that is created in this group
        platforms.enableBody = true;
        cielo.enableBody = true;

        var fin=cielo.create(0,0,'cielo');
        fin.scale.setTo(2,1);

        // Here we create the ground.
        var ground = platforms.create(0, game.world.height - 64, 'ground');

        //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
        ground.scale.setTo(2, 2);

        //  This stops it from falling away when you jump on it
        ground.body.immovable = true;

        //  Now let's create two ledges
        var ledge = platforms.create(300, 400, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(-150, 250, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(350, 150, 'ground2');
        ledge.body.immovable = true;

        // The player and its settings
        player = game.add.sprite(32, game.world.height - 150, 'dude');

        //  We need to enable physics on the player
        game.physics.arcade.enable(player);

        //  Player physics properties. Give the little guy a slight bounce.
        player.body.bounce.y = 0.2;
        player.body.gravity.y = 400;
        player.body.collideWorldBounds = true;

        //  Our two animations, walking left and right.
        player.animations.add('left', [0, 1, 2, 3], 10, true);
        player.animations.add('right', [5, 6, 7, 8], 10, true);

        //  Finally some stars to collect
        stars = game.add.group();

        //  We will enable physics for any star that is created in this group
        stars.enableBody = true;

        //  Here we'll create 12 of them evenly spaced apart
        for (var i = 0; i < 12; i++)
        {
            //  Create a star inside of the 'stars' group
            var star = stars.create(i * 70, 0, 'star');

            //  Let gravity do its thing
            star.body.gravity.y = 300;

            //  This just gives each star a slightly random bounce value
            star.body.bounce.y = 0.7 + Math.random() * 0.2;
        }

        //  The score
        scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });

        //  Our controls.
        cursors = game.input.keyboard.createCursorKeys();

    }

    function create1() {

        //  We're going to be using physics, so enable the Arcade Physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        //  A simple background for our game
        game.add.sprite(0, 0, 'sky');

        //  The platforms group contains the ground and the 2 ledges we can jump on
        platforms = game.add.group();

        //  We will enable physics for any object that is created in this group
        platforms.enableBody = true;

        // Here we create the ground.
        var ground = platforms.create(0, game.world.height - 64, 'ground');

        //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
        ground.scale.setTo(2, 2);

        //  This stops it from falling away when you jump on it
        ground.body.immovable = true;

        //  Now let's create two ledges
        var ledge = platforms.create(300, 400, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(-150, 250, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(350, 150, 'ground');
        ledge.body.immovable = true;

        // The player and its settings
        player = game.add.sprite(32, game.world.height - 150, 'dude');

        //  We need to enable physics on the player
        game.physics.arcade.enable(player);

        //  Player physics properties. Give the little guy a slight bounce.
        player.body.bounce.y = 0.2;
        player.body.gravity.y = 400;
        player.body.collideWorldBounds = true;

        //  Our two animations, walking left and right.
        player.animations.add('left', [0, 1, 2, 3], 10, true);
        player.animations.add('right', [5, 6, 7, 8], 10, true);

        //  Finally some stars to collect
        stars = game.add.group();

        //  We will enable physics for any star that is created in this group
        stars.enableBody = true;

        //  Here we'll create 12 of them evenly spaced apart
        for (var i = 0; i < 12; i++)
        {
            //  Create a star inside of the 'stars' group
            var star = stars.create(i * 70, 0, 'star');

            //  Let gravity do its thing
            star.body.gravity.y = 300;

            //  This just gives each star a slightly random bounce value
            star.body.bounce.y = 0.7 + Math.random() * 0.2;
        }

        //  The score
        scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });

        //  Our controls.
        cursors = game.input.keyboard.createCursorKeys();

    }

    function create2() {

        //  We're going to be using physics, so enable the Arcade Physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        //  A simple background for our game
        game.add.sprite(0, 0, 'sky');

        //  The platforms group contains the ground and the 2 ledges we can jump on
        platforms = game.add.group();

        //  We will enable physics for any object that is created in this group
        platforms.enableBody = true;

        // Here we create the ground.
        var ground = platforms.create(0, game.world.height - 64, 'ground');

        //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
        ground.scale.setTo(2, 2);

        //  This stops it from falling away when you jump on it
        ground.body.immovable = true;

        //  Now let's create two ledges
        var ledge = platforms.create(300, 400, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(-150, 250, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(350, 150, 'ground');
        ledge.body.immovable = true;

        // The player and its settings
        player = game.add.sprite(32, game.world.height - 150, 'dude');

        //  We need to enable physics on the player
        game.physics.arcade.enable(player);

        //  Player physics properties. Give the little guy a slight bounce.
        player.body.bounce.y = 0.2;
        player.body.gravity.y = 400;
        player.body.collideWorldBounds = true;

        //  Our two animations, walking left and right.
        player.animations.add('left', [0, 1, 2, 3], 10, true);
        player.animations.add('right', [5, 6, 7, 8], 10, true);

        //  Finally some stars to collect
        stars = game.add.group();

        //  We will enable physics for any star that is created in this group
        stars.enableBody = true;

        //  Here we'll create 12 of them evenly spaced apart
        for (var i = 0; i < 12; i++)
        {
            //  Create a star inside of the 'stars' group
            var star = stars.create(i * 70, 0, 'star');

            //  Let gravity do its thing
            star.body.gravity.y = 300;

            //  This just gives each star a slightly random bounce value
            star.body.bounce.y = 0.7 + Math.random() * 0.2;
        }

        //  The score
        scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });

        //  Our controls.
        cursors = game.input.keyboard.createCursorKeys();

    }

    function update() {

        //  Collide the player and the stars with the platforms
        game.physics.arcade.collide(player, platforms);
        game.physics.arcade.collide(stars, platforms);

        //  Checks to see if the player overlaps with any of the stars, if he does call the collectStar function
        game.physics.arcade.overlap(player, stars, collectStar, null, this);

        game.physics.arcade.overlap(player, cielo, terminaNivel, null, this);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;

        if (cursors.left.isDown)
        {
            //  Move to the left
            player.body.velocity.x = -150;

            player.animations.play('left');
        }
        else if (cursors.right.isDown)
        {
            //  Move to the right
            player.body.velocity.x = 150;

            player.animations.play('right');
        }
        else
        {
            //  Stand still
            player.animations.stop();

            player.frame = 4;
        }

        //  Allow the player to jump if they are touching the ground.
        if (cursors.up.isDown && player.body.touching.down)
        {
            player.body.velocity.y = -350;
        }

    }

    function collectStar (player, star) {

        // Removes the star from the screen
        star.kill();

        //  Add and update the score
        player.vidas = player.vidas-1;
        scoreText.text = 'Vidas: ' + player.vidas;

        if(player.vidas<=0){
            scoreText.text = 'Has muerto';
        }

    }

    function terminaNivel (player, final) {

        //Llamar a nivel completado con el tiempo y las vidas
        //Matar al jugador
        console.log("NivelCompletado");

    }
<commit_msg>clase 13/10/2016<commit_after>    var player;
    var platforms;
    var cursors;
    var cielo;

    var stars;
    var score = 0;
    var vidas = 5;
    var scoreText;
    var game;

    function crearNivel(nivel){

        switch(nivel) {
        case '0':
            game = new Phaser.Game(800, 600, Phaser.AUTO, 'juegoId', { preload: preload, create: create0, update: update });
            break;
        case '1':
            game = new Phaser.Game(800, 600, Phaser.AUTO, 'juegoId', { preload: preload, create: create1, update: update });
            break;
        case '2':
            game = new Phaser.Game(800, 600, Phaser.AUTO, 'juegoId', { preload: preload, create: create2, update: update });
            break;
        default: noHayNiveles();
            break;
}

    }

    function preload() {

        game.load.image('sky', 'assets/sky.png');
        game.load.image('ground', 'assets/platform.png');
        game.load.image('ground2', 'assets/platform2.png');
        game.load.image('star', 'assets/star.png');
        game.load.image('cielo', 'assets/heaven.png');

        game.load.spritesheet('dude', 'assets/dude.png', 32, 48);

    }

    function create0() {

        //  We're going to be using physics, so enable the Arcade Physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        //  A simple background for our game
        game.add.sprite(0, 0, 'sky');

        //  The platforms group contains the ground and the 2 ledges we can jump on
        platforms = game.add.group();
        cielo = game.add.group();
        //  We will enable physics for any object that is created in this group
        platforms.enableBody = true;
        cielo.enableBody = true;

        var fin=cielo.create(0,0,'cielo');
        fin.scale.setTo(2,1);

        // Here we create the ground.
        var ground = platforms.create(0, game.world.height - 64, 'ground');

        //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
        ground.scale.setTo(2, 2);

        //  This stops it from falling away when you jump on it
        ground.body.immovable = true;

        //  Now let's create two ledges
        var ledge = platforms.create(300, 400, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(-150, 250, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(350, 150, 'ground2');
        ledge.body.immovable = true;

        // The player and its settings
        player = game.add.sprite(32, game.world.height - 150, 'dude');

        //  We need to enable physics on the player
        game.physics.arcade.enable(player);

        //  Player physics properties. Give the little guy a slight bounce.
        player.body.bounce.y = 0.2;
        player.body.gravity.y = 400;
        player.body.collideWorldBounds = true;

        //  Our two animations, walking left and right.
        player.animations.add('left', [0, 1, 2, 3], 10, true);
        player.animations.add('right', [5, 6, 7, 8], 10, true);

        //  Finally some stars to collect
        stars = game.add.group();

        //  We will enable physics for any star that is created in this group
        stars.enableBody = true;

        //  Here we'll create 12 of them evenly spaced apart
        for (var i = 0; i < 12; i++)
        {
            //  Create a star inside of the 'stars' group
            var star = stars.create(i * 70, 0, 'star');

            //  Let gravity do its thing
            star.body.gravity.y = 300;

            //  This just gives each star a slightly random bounce value
            star.body.bounce.y = 0.7 + Math.random() * 0.2;
        }

        //  The score
        scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });

        //  Our controls.
        cursors = game.input.keyboard.createCursorKeys();

    }

    function create1() {

        //  We're going to be using physics, so enable the Arcade Physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        //  A simple background for our game
        game.add.sprite(0, 0, 'sky');

        //  The platforms group contains the ground and the 2 ledges we can jump on
        platforms = game.add.group();

        //  We will enable physics for any object that is created in this group
        platforms.enableBody = true;

        // Here we create the ground.
        var ground = platforms.create(0, game.world.height - 64, 'ground');

        //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
        ground.scale.setTo(2, 2);

        //  This stops it from falling away when you jump on it
        ground.body.immovable = true;

        //  Now let's create two ledges
        var ledge = platforms.create(300, 400, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(-150, 250, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(350, 150, 'ground');
        ledge.body.immovable = true;

        // The player and its settings
        player = game.add.sprite(32, game.world.height - 150, 'dude');

        //  We need to enable physics on the player
        game.physics.arcade.enable(player);

        //  Player physics properties. Give the little guy a slight bounce.
        player.body.bounce.y = 0.2;
        player.body.gravity.y = 400;
        player.body.collideWorldBounds = true;

        //  Our two animations, walking left and right.
        player.animations.add('left', [0, 1, 2, 3], 10, true);
        player.animations.add('right', [5, 6, 7, 8], 10, true);

        //  Finally some stars to collect
        stars = game.add.group();

        //  We will enable physics for any star that is created in this group
        stars.enableBody = true;

        //  Here we'll create 12 of them evenly spaced apart
        for (var i = 0; i < 12; i++)
        {
            //  Create a star inside of the 'stars' group
            var star = stars.create(i * 70, 0, 'star');

            //  Let gravity do its thing
            star.body.gravity.y = 300;

            //  This just gives each star a slightly random bounce value
            star.body.bounce.y = 0.7 + Math.random() * 0.2;
        }

        //  The score
        scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });

        //  Our controls.
        cursors = game.input.keyboard.createCursorKeys();

    }

    function create2() {

        //  We're going to be using physics, so enable the Arcade Physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        //  A simple background for our game
        game.add.sprite(0, 0, 'sky');

        //  The platforms group contains the ground and the 2 ledges we can jump on
        platforms = game.add.group();

        //  We will enable physics for any object that is created in this group
        platforms.enableBody = true;

        // Here we create the ground.
        var ground = platforms.create(0, game.world.height - 64, 'ground');

        //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
        ground.scale.setTo(2, 2);

        //  This stops it from falling away when you jump on it
        ground.body.immovable = true;

        //  Now let's create two ledges
        var ledge = platforms.create(300, 400, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(-150, 250, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(350, 150, 'ground');
        ledge.body.immovable = true;

        // The player and its settings
        player = game.add.sprite(32, game.world.height - 150, 'dude');

        //  We need to enable physics on the player
        game.physics.arcade.enable(player);

        //  Player physics properties. Give the little guy a slight bounce.
        player.body.bounce.y = 0.2;
        player.body.gravity.y = 400;
        player.body.collideWorldBounds = true;

        //  Our two animations, walking left and right.
        player.animations.add('left', [0, 1, 2, 3], 10, true);
        player.animations.add('right', [5, 6, 7, 8], 10, true);

        //  Finally some stars to collect
        stars = game.add.group();

        //  We will enable physics for any star that is created in this group
        stars.enableBody = true;

        //  Here we'll create 12 of them evenly spaced apart
        for (var i = 0; i < 12; i++)
        {
            //  Create a star inside of the 'stars' group
            var star = stars.create(i * 70, 0, 'star');

            //  Let gravity do its thing
            star.body.gravity.y = 300;

            //  This just gives each star a slightly random bounce value
            star.body.bounce.y = 0.7 + Math.random() * 0.2;
        }

        //  The score
        scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });

        //  Our controls.
        cursors = game.input.keyboard.createCursorKeys();

    }

    function update() {

        //  Collide the player and the stars with the platforms
        game.physics.arcade.collide(player, platforms);
        game.physics.arcade.collide(stars, platforms);

        //  Checks to see if the player overlaps with any of the stars, if he does call the collectStar function
        game.physics.arcade.overlap(player, stars, collectStar, null, this);

        game.physics.arcade.overlap(player, cielo, terminaNivel, null, this);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;

        if (cursors.left.isDown)
        {
            //  Move to the left
            player.body.velocity.x = -150;

            player.animations.play('left');
        }
        else if (cursors.right.isDown)
        {
            //  Move to the right
            player.body.velocity.x = 150;

            player.animations.play('right');
        }
        else
        {
            //  Stand still
            player.animations.stop();

            player.frame = 4;
        }

        //  Allow the player to jump if they are touching the ground.
        if (cursors.up.isDown && player.body.touching.down)
        {
            player.body.velocity.y = -350;
        }

    }

    function collectStar (player, star) {

        // Removes the star from the screen
        star.kill();

        //  Add and update the score
        player.vidas = player.vidas-1;
        scoreText.text = 'Vidas: ' + player.vidas;

        if(player.vidas<=0){
            scoreText.text = 'Has muerto';
        }

    }

    function terminaNivel (player, final) {

        //Llamar a nivel completado con el tiempo y las vidas
        //Matar al jugador
        console.log("NivelCompletado");

    }
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var moment = require('moment-timezone');
var NodeCache = require('node-cache');

function init(profileData) {

  var profile = { };

  profile.timeValueCache = new NodeCache({ stdTTL: 600, checkperiod: 600 });

  profile.loadData = function loadData(profileData) {
    if (profileData && profileData.length) {
      profile.data = _.cloneDeep(profileData);
      profile.preprocessProfileOnLoad(profile.data[0]);
    }
  };

  profile.timeStringToSeconds = function timeStringToSeconds(time) {
    var split = time.split(':');
    return parseInt(split[0])*3600 + parseInt(split[1])*60;
  };

  // preprocess the timestamps to seconds for a couple orders of magnitude faster operation
  profile.preprocessProfileOnLoad = function preprocessProfileOnLoad(container) {
    _.forEach(container, function eachValue (value) {
      if( Object.prototype.toString.call(value) === '[object Array]' ) {
        profile.preprocessProfileOnLoad(value);
      }

      if (value.time) {
        var sec = profile.timeStringToSeconds(value.time);
        if (!isNaN(sec)) { value.timeAsSeconds = sec; }
      }
    });
  };

  profile.getValueByTime = function getValueByTime (time, valueType) {
    if (!time) { time = Date.now(); }

    var cacheKey = (time + valueType);
    var returnValue = profile.timeValueCache[cacheKey];

    if (returnValue) {
      return returnValue;
    }

    var valueContainer = profile.getCurrentProfile()[valueType];

    // Assumes the timestamps are in UTC
    // Use local time zone if profile doesn't contain a time zone
    // This WILL break on the server; added warnings elsewhere that this is missing
    // TODO: Better warnings to user for missing configuration

    var t = profile.getTimezone() ? moment(time).tz(profile.getTimezone()) : moment(time);

    // Convert to seconds from midnight
    var mmtMidnight = t.clone().startOf('day');
    var timeAsSecondsFromMidnight = t.clone().diff(mmtMidnight, 'seconds');

    // If the container is an Array, assume it's a valid timestamped value container

    returnValue = valueContainer;

    if( Object.prototype.toString.call(valueContainer) === '[object Array]' ) {
      _.forEach(valueContainer, function eachValue (value) {
        if (timeAsSecondsFromMidnight >= value.timeAsSeconds) {
          returnValue = value.value;
        }
      });
    }

    profile.timeValueCache[cacheKey] = returnValue;

    return returnValue;
  };

  profile.getCurrentProfile = function getCurrentProfile() {
    return profile.hasData() ? profile.data[0] : {};
  };

  profile.getUnits = function getUnits() {
    return profile.getCurrentProfile()['units'];
  };

  profile.getTimezone = function getTimezone() {
    return profile.getCurrentProfile()['timezone'];
  };

  profile.hasData = function hasData() {
    return profile.data ? true : false;
  };

  profile.getDIA = function getDIA(time) {
    return profile.getValueByTime(time, 'dia');
  };

  profile.getSensitivity = function getSensitivity(time) {
    return profile.getValueByTime(time, 'sens');
  };

  profile.getCarbRatio = function getCarbRatio(time) {
    return profile.getValueByTime(time, 'carbratio');
  };

  profile.getCarbAbsorptionRate = function getCarbAbsorptionRate(time) {
    return profile.getValueByTime(time, 'carbs_hr');
  };

  profile.getLowBGTarget = function getLowBGTarget(time) {
    return profile.getValueByTime(time, 'target_low');
  };

  profile.getHighBGTarget = function getHighBGTarget(time) {
    return profile.getValueByTime(time, 'target_high');
  };

  profile.getBasal = function getBasal(time) {
    return profile.getValueByTime(time,'basal');
  };

  if (profileData) { profile.loadData(profileData); }

  return profile;
}

module.exports = init;<commit_msg>use time rounded to the minute for getValueByTime to improve caching<commit_after>'use strict';

var _ = require('lodash');
var moment = require('moment-timezone');
var NodeCache = require('node-cache');

function init(profileData) {

  var profile = { };

  profile.timeValueCache = new NodeCache({ stdTTL: 600, checkperiod: 600 });

  profile.loadData = function loadData(profileData) {
    if (profileData && profileData.length) {
      profile.data = _.cloneDeep(profileData);
      profile.preprocessProfileOnLoad(profile.data[0]);
    }
  };

  profile.timeStringToSeconds = function timeStringToSeconds(time) {
    var split = time.split(':');
    return parseInt(split[0])*3600 + parseInt(split[1])*60;
  };

  // preprocess the timestamps to seconds for a couple orders of magnitude faster operation
  profile.preprocessProfileOnLoad = function preprocessProfileOnLoad(container) {
    _.forEach(container, function eachValue (value) {
      if( Object.prototype.toString.call(value) === '[object Array]' ) {
        profile.preprocessProfileOnLoad(value);
      }

      if (value.time) {
        var sec = profile.timeStringToSeconds(value.time);
        if (!isNaN(sec)) { value.timeAsSeconds = sec; }
      }
    });
  };

  profile.getValueByTime = function getValueByTime (time, valueType) {
    if (!time) { time = Date.now(); }

    //round to the minute for better caching
    var minuteTime = Math.round(time / 60000) * 60000;

    var cacheKey = (minuteTime + valueType);
    var returnValue = profile.timeValueCache[cacheKey];

    if (returnValue) {
      return returnValue;
    }

    var valueContainer = profile.getCurrentProfile()[valueType];

    // Assumes the timestamps are in UTC
    // Use local time zone if profile doesn't contain a time zone
    // This WILL break on the server; added warnings elsewhere that this is missing
    // TODO: Better warnings to user for missing configuration

    var t = profile.getTimezone() ? moment(minuteTime).tz(profile.getTimezone()) : moment(minuteTime);

    // Convert to seconds from midnight
    var mmtMidnight = t.clone().startOf('day');
    var timeAsSecondsFromMidnight = t.clone().diff(mmtMidnight, 'seconds');

    // If the container is an Array, assume it's a valid timestamped value container

    returnValue = valueContainer;

    if( Object.prototype.toString.call(valueContainer) === '[object Array]' ) {
      _.forEach(valueContainer, function eachValue (value) {
        if (timeAsSecondsFromMidnight >= value.timeAsSeconds) {
          returnValue = value.value;
        }
      });
    }

    profile.timeValueCache[cacheKey] = returnValue;

    return returnValue;
  };

  profile.getCurrentProfile = function getCurrentProfile() {
    return profile.hasData() ? profile.data[0] : {};
  };

  profile.getUnits = function getUnits() {
    return profile.getCurrentProfile()['units'];
  };

  profile.getTimezone = function getTimezone() {
    return profile.getCurrentProfile()['timezone'];
  };

  profile.hasData = function hasData() {
    return profile.data ? true : false;
  };

  profile.getDIA = function getDIA(time) {
    return profile.getValueByTime(time, 'dia');
  };

  profile.getSensitivity = function getSensitivity(time) {
    return profile.getValueByTime(time, 'sens');
  };

  profile.getCarbRatio = function getCarbRatio(time) {
    return profile.getValueByTime(time, 'carbratio');
  };

  profile.getCarbAbsorptionRate = function getCarbAbsorptionRate(time) {
    return profile.getValueByTime(time, 'carbs_hr');
  };

  profile.getLowBGTarget = function getLowBGTarget(time) {
    return profile.getValueByTime(time, 'target_low');
  };

  profile.getHighBGTarget = function getHighBGTarget(time) {
    return profile.getValueByTime(time, 'target_high');
  };

  profile.getBasal = function getBasal(time) {
    return profile.getValueByTime(time,'basal');
  };

  if (profileData) { profile.loadData(profileData); }

  return profile;
}

module.exports = init;<|endoftext|>


<commit_before>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: AjaxObject.js
 */

function AjaxObject(root_object_val) {
    "use strict";
    this.theRootObject = root_object_val;

    this.objectName = function () {
        return "AjaxObject";
    };

    this.rootObject = function () {
        return this.theRootObject;
    };

    this.utilObject = function () {
        return this.rootObject().utilObject();
    };

    this.callbackIndex = function () {
        return this.theCallbackIndex;
    };

    this.incrementCallbackIndex = function () {
        return this.theCallbackIndex += 1;
    };

    this.callbackArray = function () {
        return this.theCallbackArray;
    };

    this.callbackArrayElement = function (index_val) {
        return this.theCallbackArray[index_val];
    };

    this.setCallbackArrayElement = function (index_val, data_val) {
        this.theCallbackArray[index_val] = data_val;
    };

    this.ajaxRoute = function () {
        return "/go_msg";
    };

    this.jsonContext = function () {
        return "application/json; charset=utf-8";
    }
    this.plainTextContext = function () {
        return "text/plain; charset=utf-8";
    }

    this.httpGetRequest = function () {
        return this.theHttpGetRequest;
    };

    this.httpPostRequest = function () {
        return this.theHttpPostRequest;
    };

    this.formJsonString = function (msg_val, session_val) {
        var s = JSON.stringify({
            his_name: session_val.hisName(),
            my_name: session_val.myName(),
            data: msg_val,
            xmt_seq: session_val.xmtSeq(),
            link_id: this.rootObject().linkId(),
            session_id: session_val.sessionId(),
        });
        session_val.incrementXmtSeq();
        return s;
    };

    this.setupCallback = function (command_val, id_val, func_val, param_val1, param_val2, param_val3) {
        this.setCallbackArrayElement(this.callbackIndex(),
                                     {command: command_val,
                                      id: id_val,
                                      func: func_val,
                                      param1: param_val1,
                                      param2: param_val2,
                                      param3: param_val3});
        this.incrementCallbackIndex();
    };

    this.getCallbackInfo = function (command_val, ajax_id_val) {
        var i = 0;
        while (i < this.callbackArray().length) {
            if (this.callbackArrayElement(i).command === command_val) {
                //this.logit("getCallbackInfo", ajax_id_val + " " + this.callbackArrayElement(i).id);
                //if (!this.callbackArrayElement(i).id || this.callbackArrayElement(i).id === ajax_id_val) {
                    return this.callbackArrayElement(i);
                //}
            }
            i += 1;
        }
    }

    this.getPendingData = function (callback_func_val, callback_param_val) {
        var this0 = this;
        var request0 = this.httpGetRequest();
        var root0 = this.rootObject();

        //this.logit("getPendingData", this.rootObject().myName());
        this.httpGetRequest().open("GET", this.ajaxRoute(), true);
        this.httpGetRequest().setRequestHeader("Content-Type", this.jsonContext());
        this.httpGetRequest().setRequestHeader("command", "get_pending_data");
        this.httpGetRequest().setRequestHeader("my_name", this.rootObject().myName());

        this.httpGetRequest().onreadystatechange = function() {
            if ((request0.readyState === 4) && (request0.status === 200)) {
                var context_type = request0.getResponseHeader("Content-Type");
                //this0.logit("getPendingData", request0.responseText);
                callback_func_val(callback_param_val);
            }
        };
        this.httpGetRequest().send(null);
    };

    this.setupLink = function (callback_func_val, ajax_id_val, callback_param_val) {
        this.logit("setupLink", this.rootObject().myName());
        this.waitOnreadyStateChange();
        var ajax = {
            command: "setup_link",
            callback_func: callback_func_val,
            callback_param: callback_param_val,
            header: [{type: "ajax_id", value: this.rootObject().myName()},
                     {type: "my_name", value: this.rootObject().myName()}]
            };
        this.enqueueOutput(ajax);
    };

    this.enqueueOutput = function (ajax_val) {
        this.outputQueue.enQueue(ajax_val);
        this.ajaxJob();
    };

    this.ajaxJob = function () {
        if (this.outputQueue.size() === 0) {
            this.sendKeepAlive();
        }
        while (this.outputQueue.size() > 0) {
            var ajax = this.outputQueue.deQueue();
            var header = ajax.header;
            this.httpGetRequest().open("GET", this.ajaxRoute(), true);
            this.httpGetRequest().setRequestHeader("Content-Type", this.jsonContext());
            this.httpGetRequest().setRequestHeader("command", ajax.command);
            var i = 0;
            while (i < header.length) {
                this.httpGetRequest().setRequestHeader(header[i].type, header[i].value);
                i += 1;
            }
            this.httpGetRequest().send(null);
        }
    };

    this.sendKeepAlive = function (root_val) {
        var ajax = {
            command: "keep_alive",
            callback_func: null,
            callback_param: null,
            header: [{type: "ajax_id", value: this.rootObject().myName()},
                     {type: "my_name", value: this.rootObject().myName()},
                     {type: "link_id", value: this.rootObject().linkId()}]
            };
        this.enqueueOutput(ajax);
    };

    this.getNameList = function (callback_func_val, callback_param_val) {
        var this0 = this;
        var request0 = this.httpGetRequest();
        var root0 = this.rootObject();

        this.httpGetRequest().onreadystatechange = function() {
            if ((request0.readyState === 4) && (request0.status === 200)) {
                var context_type = request0.getResponseHeader("Content-Type");
                var json = JSON.parse(request0.responseText);
                this0.logit("getSessionData", "command=" + json.command + " ajax_id=" + json.ajax_id + " data=" + json.data);
                this0.logit("getNameList", "name_list= " + json.data);
                //root0.setNameList(JSON.parse(json.data));
                if (callback_func_val) {
                    callback_func_val(json.data, callback_param_val);
                }
            }
        };
        var ajax = {
            command: "get_name_list",
            callback_func: callback_func_val,
            callback_param: callback_param_val,
            header: [{type: "ajax_id", value: this.rootObject().linkId()},
                     {type: "my_name", value: this.rootObject().myName()},
                     {type: "link_id", value: this.rootObject().linkId()}]
            };
        this.enqueueOutput(ajax);
    };

    this.waitOnreadyStateChange = function () {
        var this0 = this;
        var request0 = this.httpGetRequest();

        this.httpGetRequest().onreadystatechange = function() {
            if ((request0.readyState === 4) && (request0.status === 200)) {
                this0.logit("waitOnreadyStateChange", "json_str= " + request0.responseText);
                var json = JSON.parse(request0.responseText);
                this0.logit("waitOnreadyStateChange", "command=" + json.command + " ajax_id=" + json.ajax_id + " data=" + json.data);
                var callback_info = this0.getCallbackInfo(json.command, json.ajax_id);
                if (callback_info) {
                    callback_info.func(json.data, callback_info.param1);
                }
            }
        };
    };

    this.getSessionData = function (callback_func_val, ajax_id_val, session_val) {
        //this.logit("getSessionData", "ajax_id=", ajax_id_val);
        this.waitOnreadyStateChange();
        var ajax = {
            command: "get_session_data",
            callback_func: callback_func_val,
            callback_param: session_val,
            header: [{type: "ajax_id", value: session_val.sessionId()},
                     {type: "my_name", value: this.rootObject().myName()},
                     {type: "link_id", value: this.rootObject().linkId()},
                     {type: "session_id", value: session_val.sessionId()},
                     {type: "his_name", value: session_val.hisName()}],
            };
        this.enqueueOutput(ajax);
    };

    this.initiateSessionConnection = function (callback_func_val, ajax_id_val, session_val) {
        this.logit("initiateSessionConnection", session_val.myName());
        this.waitOnreadyStateChange();
        var ajax = {
            command: "setup_session",
            callback_func: callback_func_val,
            callback_param: session_val,
            header: [{type: "ajax_id", value: this.rootObject().linkId()},
                     {type: "my_name", value: this.rootObject().myName()},
                     {type: "link_id", value: this.rootObject().linkId()},
                     {type: "his_name", value: session_val.hisName()}],
            };
        this.enqueueOutput(ajax);
    };

    this.sendDataToPeer = function (sesson_mgr_val, session_val) {
        this.httpGetRequest().open("GET", this.ajaxRoute(), true);
        this.httpGetRequest().setRequestHeader("Content-Type", this.jsonContext());
        this.httpGetRequest().setRequestHeader("command", "peer");
        this.httpGetRequest().setRequestHeader("my_name", session_val.myName());
        this.httpGetRequest().setRequestHeader("his_name", session_val.hisName());
        this.httpGetRequest().setRequestHeader("link_id", this.rootObject().linkId());
        this.httpGetRequest().setRequestHeader("session_id", session_val.sessionId());

        this.getRequest(sesson_mgr_val, session_val);
    };

    this.getRequest = function (sesson_mgr_val, session_val) {
        var this0 = this;
        var request0 = this.httpGetRequest();

        this.httpGetRequest().onreadystatechange = function() {
            if ((request0.readyState === 4) && (request0.status === 200)) {
                var context_type = request0.getResponseHeader("Content-Type");
                this0.logit("getMessage", "data= " + request0.responseText);
                session_val.receiveData(request0.responseText);
            }
        };
        this.httpGetRequest().send(null);
    };

    this.postRequest = function (msg_val, session_val) {
        this.httpPostRequest().open("POST", this.ajaxRoute(), true);
        this.httpPostRequest().setRequestHeader("Content-Type", this.jsonContext());

        var json_str = this.formJsonString(msg_val, session_val);
        this.logit("postMessage", "json=" + json_str);
        this.httpPostRequest().send(json_str);

/*
        $.ajax({
            data: {data: msg_val},
            url: dir_val,
            type: 'post',
            dataType: 'json',

        });
*/
    };

    this.setupAjax = function () {
        this.httpGetRequest().onreadystatechange = function() {
            if ((request0.readyState === 4) && (request0.status === 200)) {
                var context_type = request0.getResponseHeader("Content-Type");
                var link_id = request0.responseText;
                this0.logit("setupLink", "link_id= " + request0.responseText);
                root0.setLinkId(Number(link_id));
                callback_func_val(callback_param_val);
            }
        };
    };

    this.newHttpRequest = function () {
        var request = new XMLHttpRequest();
        return request;
    };

    this.abend = function (str1_val, str2_val) {
        return this.utilObject().utilAbend(this.objectName() + "." + str1_val, str2_val);
    };

    this.logit = function (str1_val, str2_val) {
        return this.utilObject().utilLogit(this.objectName() + "." + str1_val, str2_val);
    };

    this.theCallbackIndex = 0;
    this.theCallbackArray = [];
    this.outputQueue = new QueueObject(this.utilObject());
    this.inputQueue = new QueueObject(this.utilObject());
    this.theHttpGetRequest = new XMLHttpRequest();
    this.setupAjax();
    this.theHttpPostRequest = new XMLHttpRequest();
}

<commit_msg>setup link<commit_after>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: AjaxObject.js
 */

function AjaxObject(root_object_val) {
    "use strict";
    this.theRootObject = root_object_val;

    this.objectName = function () {
        return "AjaxObject";
    };

    this.rootObject = function () {
        return this.theRootObject;
    };

    this.utilObject = function () {
        return this.rootObject().utilObject();
    };

    this.callbackIndex = function () {
        return this.theCallbackIndex;
    };

    this.incrementCallbackIndex = function () {
        return this.theCallbackIndex += 1;
    };

    this.callbackArray = function () {
        return this.theCallbackArray;
    };

    this.callbackArrayElement = function (index_val) {
        return this.theCallbackArray[index_val];
    };

    this.setCallbackArrayElement = function (index_val, data_val) {
        this.theCallbackArray[index_val] = data_val;
    };

    this.ajaxRoute = function () {
        return "/go_msg";
    };

    this.jsonContext = function () {
        return "application/json; charset=utf-8";
    }
    this.plainTextContext = function () {
        return "text/plain; charset=utf-8";
    }

    this.httpGetRequest = function () {
        return this.theHttpGetRequest;
    };

    this.httpPostRequest = function () {
        return this.theHttpPostRequest;
    };

    this.formJsonString = function (msg_val, session_val) {
        var s = JSON.stringify({
            his_name: session_val.hisName(),
            my_name: session_val.myName(),
            data: msg_val,
            xmt_seq: session_val.xmtSeq(),
            link_id: this.rootObject().linkId(),
            session_id: session_val.sessionId(),
        });
        session_val.incrementXmtSeq();
        return s;
    };

    this.setupCallback = function (command_val, id_val, func_val, param_val1, param_val2, param_val3) {
        this.setCallbackArrayElement(this.callbackIndex(),
                                     {command: command_val,
                                      id: id_val,
                                      func: func_val,
                                      param1: param_val1,
                                      param2: param_val2,
                                      param3: param_val3});
        this.incrementCallbackIndex();
    };

    this.getCallbackInfo = function (command_val, ajax_id_val) {
        var i = 0;
        while (i < this.callbackArray().length) {
            if (this.callbackArrayElement(i).command === command_val) {
                //this.logit("getCallbackInfo", ajax_id_val + " " + this.callbackArrayElement(i).id);
                //if (!this.callbackArrayElement(i).id || this.callbackArrayElement(i).id === ajax_id_val) {
                    return this.callbackArrayElement(i);
                //}
            }
            i += 1;
        }
    }

/*
    this.getPendingData11111 = function (callback_func_val, callback_param_val) {
        var this0 = this;
        var request0 = this.httpGetRequest();
        var root0 = this.rootObject();

        //this.logit("getPendingData", this.rootObject().myName());
        this.httpGetRequest().open("GET", this.ajaxRoute(), true);
        this.httpGetRequest().setRequestHeader("Content-Type", this.jsonContext());
        this.httpGetRequest().setRequestHeader("command", "get_pending_data");
        this.httpGetRequest().setRequestHeader("my_name", this.rootObject().myName());

        this.httpGetRequest().onreadystatechange = function() {
            if ((request0.readyState === 4) && (request0.status === 200)) {
                var context_type = request0.getResponseHeader("Content-Type");
                //this0.logit("getPendingData", request0.responseText);
                callback_func_val(callback_param_val);
            }
        };
        this.httpGetRequest().send(null);
    };
*/

    this.enqueueOutput = function (ajax_val) {
        this.outputQueue.enQueue(ajax_val);
        this.ajaxJob();
    };

    this.ajaxJob = function () {
        if (this.outputQueue.size() === 0) {
            this.sendKeepAlive();
        }
        while (this.outputQueue.size() > 0) {
            var ajax = this.outputQueue.deQueue();
            var header = ajax.header;
            this.httpGetRequest().open("GET", this.ajaxRoute(), true);
            this.httpGetRequest().setRequestHeader("Content-Type", this.jsonContext());
            this.httpGetRequest().setRequestHeader("command", ajax.command);
            var i = 0;
            while (i < header.length) {
                this.httpGetRequest().setRequestHeader(header[i].type, header[i].value);
                i += 1;
            }
            this.httpGetRequest().send(null);
        }
    };

    this.sendKeepAlive = function (root_val) {
        var ajax = {
            command: "keep_alive",
            callback_func: null,
            callback_param: null,
            header: [{type: "ajax_id", value: this.rootObject().myName()},
                     {type: "my_name", value: this.rootObject().myName()},
                     {type: "link_id", value: this.rootObject().linkId()}]
            };
        this.enqueueOutput(ajax);
    };

    this.setupLink = function (callback_func_val, ajax_id_val, callback_param_val) {
        this.logit("setupLink", this.rootObject().myName());
        this.waitOnreadyStateChange();
        var ajax = {
            command: "setup_link",
            callback_func: callback_func_val,
            callback_param: callback_param_val,
            header: [{type: "ajax_id", value: this.rootObject().myName()},
                     {type: "my_name", value: this.rootObject().myName()}]
            };
        this.enqueueOutput(ajax);
    };

    this.getNameList = function (callback_func_val, callback_param_val) {
        var this0 = this;
        var request0 = this.httpGetRequest();
        var root0 = this.rootObject();

        this.httpGetRequest().onreadystatechange = function() {
            if ((request0.readyState === 4) && (request0.status === 200)) {
                var context_type = request0.getResponseHeader("Content-Type");
                var json = JSON.parse(request0.responseText);
                this0.logit("getSessionData", "command=" + json.command + " ajax_id=" + json.ajax_id + " data=" + json.data);
                this0.logit("getNameList", "name_list= " + json.data);
                //root0.setNameList(JSON.parse(json.data));
                if (callback_func_val) {
                    callback_func_val(json.data, callback_param_val);
                }
            }
        };
        var ajax = {
            command: "get_name_list",
            callback_func: callback_func_val,
            callback_param: callback_param_val,
            header: [{type: "ajax_id", value: this.rootObject().linkId()},
                     {type: "my_name", value: this.rootObject().myName()},
                     {type: "link_id", value: this.rootObject().linkId()}]
            };
        this.enqueueOutput(ajax);
    };

    this.waitOnreadyStateChange = function () {
        var this0 = this;
        var request0 = this.httpGetRequest();

        this.httpGetRequest().onreadystatechange = function() {
            if ((request0.readyState === 4) && (request0.status === 200)) {
                this0.logit("waitOnreadyStateChange", "json_str= " + request0.responseText);
                var json = JSON.parse(request0.responseText);
                this0.logit("waitOnreadyStateChange", "command=" + json.command + " ajax_id=" + json.ajax_id + " data=" + json.data);
                var callback_info = this0.getCallbackInfo(json.command, json.ajax_id);
                if (callback_info) {
                    callback_info.func(json.data, callback_info.param1);
                }
            }
        };
    };

    this.getSessionData = function (callback_func_val, ajax_id_val, session_val) {
        //this.logit("getSessionData", "ajax_id=", ajax_id_val);
        this.waitOnreadyStateChange();
        var ajax = {
            command: "get_session_data",
            callback_func: callback_func_val,
            callback_param: session_val,
            header: [{type: "ajax_id", value: session_val.sessionId()},
                     {type: "my_name", value: this.rootObject().myName()},
                     {type: "link_id", value: this.rootObject().linkId()},
                     {type: "session_id", value: session_val.sessionId()},
                     {type: "his_name", value: session_val.hisName()}],
            };
        this.enqueueOutput(ajax);
    };

    this.initiateSessionConnection = function (callback_func_val, ajax_id_val, session_val) {
        this.logit("initiateSessionConnection", session_val.myName());
        this.waitOnreadyStateChange();
        var ajax = {
            command: "setup_session",
            callback_func: callback_func_val,
            callback_param: session_val,
            header: [{type: "ajax_id", value: this.rootObject().linkId()},
                     {type: "my_name", value: this.rootObject().myName()},
                     {type: "link_id", value: this.rootObject().linkId()},
                     {type: "his_name", value: session_val.hisName()}],
            };
        this.enqueueOutput(ajax);
    };

    this.sendDataToPeer = function (sesson_mgr_val, session_val) {
        this.httpGetRequest().open("GET", this.ajaxRoute(), true);
        this.httpGetRequest().setRequestHeader("Content-Type", this.jsonContext());
        this.httpGetRequest().setRequestHeader("command", "peer");
        this.httpGetRequest().setRequestHeader("my_name", session_val.myName());
        this.httpGetRequest().setRequestHeader("his_name", session_val.hisName());
        this.httpGetRequest().setRequestHeader("link_id", this.rootObject().linkId());
        this.httpGetRequest().setRequestHeader("session_id", session_val.sessionId());

        this.getRequest(sesson_mgr_val, session_val);
    };

    this.getRequest = function (sesson_mgr_val, session_val) {
        var this0 = this;
        var request0 = this.httpGetRequest();

        this.httpGetRequest().onreadystatechange = function() {
            if ((request0.readyState === 4) && (request0.status === 200)) {
                var context_type = request0.getResponseHeader("Content-Type");
                this0.logit("getMessage", "data= " + request0.responseText);
                session_val.receiveData(request0.responseText);
            }
        };
        this.httpGetRequest().send(null);
    };

    this.postRequest = function (msg_val, session_val) {
        this.httpPostRequest().open("POST", this.ajaxRoute(), true);
        this.httpPostRequest().setRequestHeader("Content-Type", this.jsonContext());

        var json_str = this.formJsonString(msg_val, session_val);
        this.logit("postMessage", "json=" + json_str);
        this.httpPostRequest().send(json_str);

/*
        $.ajax({
            data: {data: msg_val},
            url: dir_val,
            type: 'post',
            dataType: 'json',

        });
*/
    };

    this.setupAjax = function () {
        this.httpGetRequest().onreadystatechange = function() {
            if ((request0.readyState === 4) && (request0.status === 200)) {
                var context_type = request0.getResponseHeader("Content-Type");
                var link_id = request0.responseText;
                this0.logit("setupLink", "link_id= " + request0.responseText);
                root0.setLinkId(Number(link_id));
                callback_func_val(callback_param_val);
            }
        };
    };

    this.newHttpRequest = function () {
        var request = new XMLHttpRequest();
        return request;
    };

    this.abend = function (str1_val, str2_val) {
        return this.utilObject().utilAbend(this.objectName() + "." + str1_val, str2_val);
    };

    this.logit = function (str1_val, str2_val) {
        return this.utilObject().utilLogit(this.objectName() + "." + str1_val, str2_val);
    };

    this.theCallbackIndex = 0;
    this.theCallbackArray = [];
    this.outputQueue = new QueueObject(this.utilObject());
    this.inputQueue = new QueueObject(this.utilObject());
    this.theHttpGetRequest = new XMLHttpRequest();
    this.setupAjax();
    this.theHttpPostRequest = new XMLHttpRequest();
}

<|endoftext|>