<commit_before>(function (global, m) {

    var app = global.app = global.app || {};
    //create a new element and its sub-elements (detail-grids, listviews etc.)
    function initKendoGrid(element, isInitialized, context) {
        if (isInitialized) return; //do this only once

        //show info about the selected row (this snippet was taken from the Kendo Grid demo page http://demos.telerik.com/kendo-ui/grid/index)
        function onChange(arg) {
            var selected = $.map(this.select(), function (item) {
                return $(item).text();
            });
            if (selected) {
                console.log("Selected: " + selected.length + " item(s), [" + selected.join(", ") + "]");
            }
        }
        //here we do some extra processing for each customer order-details view (the template is in Views/Home/_Home.cshtml)
        function detailInit(e) {
            if (e) {
                console.log('customerId: ' + e.data.id);
                var detailRow = e.detailRow,
                    id = e.data.id,
                    tabStrip = $('.mithril-tabstrip:not(.modified)'),
                    grid = $('.mithril-detail-grid:not(.modified)'),
                    listView = $('.mithril-customer-address:not(.modified)');
                //To prevent "updating" of already processed detail-grids we add the class "modified" to every detail-grid,
                //tabStrip & listView widget.
                //Without this setting the current widgets would overwrite all others because we can only
                //select "classes" and not "ids".
                //More info on this problem here: http://blog.falafel.com/nested-templates-kendo-ui/
                grid.addClass('modified');
                tabStrip.addClass('modified');
                listView.addClass('modified');

                tabStrip.kendoTabStrip();
                //show contact data of the selected customer
                listView.kendoListView({
                    template: '
Street: ${Address}
ZIP: ${PostalCode}
City: ${City}
Country: ${Country}
',
                    dataSource: {
                        data: [{
                            Address: e.data.address,
                            PostalCode: e.data.postalCode,
                            City: e.data.city,
                            Country: e.data.country
                        }]
                    }
                });

                //initialize the detail grid (the details will be separately received by an extra call.
                //Of course, we could do it via Mithrils 'm.request' method too.)
                grid.kendoGrid({
                    dataSource: {
                        type: 'json',
                        transport: {
                            read: 'http://services.odata.org/Northwind/Northwind.svc/Orders?$format=json'
                        },
                        serverPaging: false,
                        serverSorting: false,
                        serverFiltering: false,
                        pageSize: 10,
                        filter: { field: 'customerId', operator: 'eq', value: id },
                        schema: {
                            model: {
                                id: 'customerId',
                                fields: {
                                    customerId: { editable: false, nullable: false },
                                    productName: { editable: false, nullable: false },
                                    orderDate: { editable: true, nullable: false },
                                    requiredDate: { editable: true, nullable: true },
                                    shippedDate: { editable: true, nullable: true },
                                    shipVia: { editable: true, nullable: true },
                                    freight: { editable: true, nullable: true },
                                    shipName: { editable: true, nullable: true },
                                    shipAddress: { editable: true, nullable: true },
                                    shipCity: { editable: true, nullable: true },
                                    shipRegion: { editable: true, nullable: true },
                                    shipPostalCode: { editable: true, nullable: true },
                                    shipCountry: { editable: true, nullable: true }
                                }
                            },
                            parse: function (response) {
                                var orders = [];
                                for (var i = 0; i < response.value.length; i++) {
                                    var data = response.value[i] ? response.value[i] : null,
                                    order = {
                                        id: data.OrderID,
                                        customerId: data.CustomerID,
                                        orderDate: data.OrderDate ? kendo.toString(new Date(data.OrderDate), "d") : null,
                                        requiredDate: data.RequiredDate ? kendo.toString(new Date(data.RequiredDate), "d") : null,
                                        shippedDate: data.ShippedDate ? kendo.toString(new Date(data.ShippedDate), "d") : null,
                                        shipVia: data.ShipVia,
                                        freight: data.Freight,
                                        shipName: data.ShipName,
                                        shipAddress: data.ShipAddress,
                                        shipCity: data.ShipCity,
                                        shipRegion: data.ShipRegion,
                                        shipPostalCode: data.ShipPostalCode,
                                        shipCountry: data.ShipCountry
                                    };
                                    orders.push(order);
                                };
                                return orders;
                            }
                        }
                    },
                    sortable: true,
                    pageable: true,
                    sizable: true,
                    selectable: true,
                    scrollable: true,
                    editable: false,
                    columns: [
                    //{ field: 'id', title: 'Order ID' },
                    { field: 'orderDate', title: 'Order Date' },
                    { field: 'requiredDate', title: 'Required Date' },
                    { field: 'shippedDate', title: 'Shipped Date' },
                    //{ field: 'shipVia', title: 'Ship Via' },
                    //{ field: 'freight', title: 'Freight' },
                    //{ field: 'shipName', title: 'Shipping Name' },
                    { field: 'shipAddress', title: 'Address' },
                    { field: 'shipCity', title: 'City' },
                    //{ field: 'shipRegion', title: 'Region' },
                    { field: 'shipPostalCode', title: 'Postal Code' },
                    { field: 'shipCountry', title: 'Country' },
                    ]
                });
            }
        }
        //prepare options for the main grid
        var options = {
            dataSource: {
                data: app.vm.customers(), //get data via Mithril's "m.request" (http://lhorie.github.io/mithril/mithril.request.html)
                //alternatively, we could call the service by using pure Kendo functionality
                //for example:
                //(http://docs.telerik.com/kendo-ui/api/javascript/data/datasource)
                //dataSource: {
                //              transport: {
                //                             read: {
                //                                      url: 'service_url',
                //                                      dataType: 'json'  //or 'jsonp' in case of a cross-domain call
                //                              }
                //                      }
                //           }
                pageSize: 10,
                serverPaging: false,
                serverSorting: false,
                schema: {
                    model: { //this will be the model for the grid
                        id: 'id',
                        fields: {
                            name: { editable: false, nullable: false },
                            company: { editable: false, nullable: false },
                            address: { editable: false, nullable: false },
                            city: { editable: true, nullable: true },
                            postalCode: { editable: true, nullable: true },
                            country: { editable: false, nullable: true, type: 'string' },
                            phone: { editable: true, nullable: true, type: 'string' },
                        }
                    },
                    parse: function (response) { //here we process the received data and adjust it to our internal format
                        var customers = [];
                        for (var i = 0; i < response.value.length; i++) {
                        var data = response.value[i] ? response.value[i] : null,
                        customer = {
                                id: data.CustomerID,
                                name: data.CompanyName,
                                address: data.Address,
                                city: data.City,
                                postalCode: data.PostalCode,
                                country: data.Country,
                                phone: data.Phone
                            }
                            customers.push(customer);
                        };
                        console.log(customers);
                        return customers;
                    }
                }
            },
            sortable: true,
            pageable: true,
            groupable:true,
            sizable: true,
            selectable: true,
            scrollable: true,
            filterable: true,
            change: onChange,
            //a template for order details
            //this will get called after we open the detail page (and only once per customer)
            detailTemplate: kendo.template($(".mithril-template").html()),
            detailInit: detailInit, //here we do extra processing of the template for each customer
            editable: {
                confirmation: function (e) {
                    return 'Do you really want to delete the customer?';
                },
                cancelDelete: 'No',
                confirmDelete: 'Yes',
                mode: 'inline'
            },
            columns: [
                    {
                        field: 'id',
                        title: 'ID'
                    },
                    {
                        field: 'name',
                        title: 'Customer'
                    },
                    {
                        field: 'company',
                        title: 'Company'
                    },
                    {
                        field: 'address',
                        title: 'Address'
                    },
                    {
                        field: 'city',
                        title: 'City'
                    },
                    {
                        field: 'postalCode',
                        title: 'Postal Code'
                    },
                    {
                        field: 'country',
                        title: 'Country'
                    },
                    {
                        field: 'phone',
                        title: 'Phone'
                    },
                    {
                        command: [
                            { name: 'edit', text: { edit: 'Edit', cancel: 'Cancel', update: 'OK' } },
                            { name: 'destroy', text: 'Delete' },
                        ],
                        title: ' ',
                        width: '220px'
                    }
            ]
        }
        //inject Kendo Grid with options set above
        $(document).ready(function () {
            var grid = $('#mithril-grid-demo').kendoGrid(options);

        });
    }
    //Create a new HTML element with Mithril
    //
    //One alternative to writing pure JavaScript templates could be
    //the port of React's JSX called MSX: https://github.com/insin/msx
    //****************************************************************************************
    //In "initKendoGrid" we process everything we need to manipulate the grid-structure
    //that relies on classes that do not belong to Mithril.
    //Kendo Grid knows nothing about Mithril and vice-versa and therefore we need some
    //extra functionality to process templates, detail vies etc.
    //More info regarding the property "config" here: http://lhorie.github.io/mithril/mithril.html#persisting-config-data
    app.view = function () {
        return m('div', { id: 'mithril-grid-demo', 'class': 'mithril-grid', config: initKendoGrid });
    };

}(window, Mithril));<commit_msg>'cleanup'<commit_after>(function (global, m) {

    var app = global.app = global.app || {};
    //create a new element and its sub-elements (detail-grids, listviews etc.)
    function initKendoGrid(element, isInitialized, context) {
        if (isInitialized) return; //do this only once

        //show info about the selected row (this snippet was taken from the Kendo Grid demo page http://demos.telerik.com/kendo-ui/grid/index)
        function onChange(arg) {
            var selected = $.map(this.select(), function (item) {
                return $(item).text();
            });
            if (selected) {
                console.log("Selected: " + selected.length + " item(s), [" + selected.join(", ") + "]");
            }
        }
        //here we do some extra processing for each customer order-details view (the template is in Views/Home/_Home.cshtml)
        function detailInit(e) {
            if (e) {
                console.log('customerId: ' + e.data.id);
                var detailRow = e.detailRow,
                    id = e.data.id,
                    tabStrip = $('.mithril-tabstrip:not(.modified)'),
                    grid = $('.mithril-detail-grid:not(.modified)'),
                    listView = $('.mithril-customer-address:not(.modified)');
                //To prevent "updating" of already processed detail-grids we add the class "modified" to every detail-grid,
                //tabStrip & listView widget.
                //Without this setting the current widgets would overwrite all others because we can only
                //select "classes" and not "ids".
                //More info on this problem here: http://blog.falafel.com/nested-templates-kendo-ui/
                grid.addClass('modified');
                tabStrip.addClass('modified');
                listView.addClass('modified');

                tabStrip.kendoTabStrip();
                //show contact data of the selected customer
                listView.kendoListView({
                    template: '
Street: ${Address}
ZIP: ${PostalCode}
City: ${City}
Country: ${Country}
',
                    dataSource: {
                        data: [{
                            Address: e.data.address,
                            PostalCode: e.data.postalCode,
                            City: e.data.city,
                            Country: e.data.country
                        }]
                    }
                });

                //initialize the detail grid (the details will be separately received by an extra call.
                //Of course, we could do it via Mithrils 'm.request' method too.)
                grid.kendoGrid({
                    dataSource: {
                        type: 'json',
                        transport: {
                            read: 'http://services.odata.org/Northwind/Northwind.svc/Orders?$format=json'
                        },
                        serverPaging: false,
                        serverSorting: false,
                        serverFiltering: false,
                        pageSize: 10,
                        filter: { field: 'customerId', operator: 'eq', value: id },
                        schema: {
                            model: {
                                id: 'customerId',
                                fields: {
                                    customerId: { editable: false, nullable: false },
                                    productName: { editable: false, nullable: false },
                                    orderDate: { editable: true, nullable: false },
                                    requiredDate: { editable: true, nullable: true },
                                    shippedDate: { editable: true, nullable: true },
                                    shipVia: { editable: true, nullable: true },
                                    freight: { editable: true, nullable: true },
                                    shipName: { editable: true, nullable: true },
                                    shipAddress: { editable: true, nullable: true },
                                    shipCity: { editable: true, nullable: true },
                                    shipRegion: { editable: true, nullable: true },
                                    shipPostalCode: { editable: true, nullable: true },
                                    shipCountry: { editable: true, nullable: true }
                                }
                            },
                            parse: function (response) {
                                var orders = [];
                                for (var i = 0; i < response.value.length; i++) {
                                    var data = response.value[i] ? response.value[i] : null,
                                    order = {
                                        id: data.OrderID,
                                        customerId: data.CustomerID,
                                        orderDate: data.OrderDate ? kendo.toString(new Date(data.OrderDate), "d") : null,
                                        requiredDate: data.RequiredDate ? kendo.toString(new Date(data.RequiredDate), "d") : null,
                                        shippedDate: data.ShippedDate ? kendo.toString(new Date(data.ShippedDate), "d") : null,
                                        shipVia: data.ShipVia,
                                        freight: data.Freight,
                                        shipName: data.ShipName,
                                        shipAddress: data.ShipAddress,
                                        shipCity: data.ShipCity,
                                        shipRegion: data.ShipRegion,
                                        shipPostalCode: data.ShipPostalCode,
                                        shipCountry: data.ShipCountry
                                    };
                                    orders.push(order);
                                };
                                return orders;
                            }
                        }
                    },
                    sortable: true,
                    pageable: true,
                    sizable: true,
                    selectable: true,
                    scrollable: true,
                    editable: false,
                    columns: [
                    //{ field: 'id', title: 'Order ID' },
                    { field: 'orderDate', title: 'Order Date' },
                    { field: 'requiredDate', title: 'Required Date' },
                    { field: 'shippedDate', title: 'Shipped Date' },
                    //{ field: 'shipVia', title: 'Ship Via' },
                    //{ field: 'freight', title: 'Freight' },
                    //{ field: 'shipName', title: 'Shipping Name' },
                    { field: 'shipAddress', title: 'Address' },
                    { field: 'shipCity', title: 'City' },
                    //{ field: 'shipRegion', title: 'Region' },
                    { field: 'shipPostalCode', title: 'Postal Code' },
                    { field: 'shipCountry', title: 'Country' },
                    ]
                });
            }
        }
        //prepare options for the main grid
        var options = {
            dataSource: {
                data: app.vm.customers(), //get data via Mithril's "m.request" (http://lhorie.github.io/mithril/mithril.request.html)
                //alternatively, we could call the service by using pure Kendo functionality
                //for example:
                //(http://docs.telerik.com/kendo-ui/api/javascript/data/datasource)
                //dataSource: {
                //              transport: {
                //                             read: {
                //                                      url: 'service_url',
                //                                      dataType: 'json'  //or 'jsonp' in case of a cross-domain call
                //                              }
                //                      }
                //           }
                pageSize: 5,
                serverPaging: false,
                serverSorting: false,
                schema: {
                    model: { //this will be the model for the grid
                        id: 'id',
                        fields: {
                            name: { editable: false, nullable: false },
                            company: { editable: false, nullable: false },
                            address: { editable: false, nullable: false },
                            city: { editable: true, nullable: true },
                            postalCode: { editable: true, nullable: true },
                            country: { editable: false, nullable: true, type: 'string' },
                            phone: { editable: true, nullable: true, type: 'string' },
                        }
                    },
                    parse: function (response) { //here we process the received data and adjust it to our internal format
                        var customers = [];
                        for (var i = 0; i < response.value.length; i++) {
                        var data = response.value[i] ? response.value[i] : null,
                        customer = {
                                id: data.CustomerID,
                                name: data.CompanyName,
                                address: data.Address,
                                city: data.City,
                                postalCode: data.PostalCode,
                                country: data.Country,
                                phone: data.Phone
                            }
                            customers.push(customer);
                        };
                        console.log(customers);
                        return customers;
                    }
                }
            },
            sortable: true,
            pageable: true,
            groupable:true,
            sizable: true,
            selectable: true,
            scrollable: true,
            filterable: true,
            change: onChange,
            //a template for order details
            //this will get called after we open the detail page (and only once per customer)
            detailTemplate: kendo.template($(".mithril-template").html()),
            detailInit: detailInit, //here we do extra processing of the template for each customer
            editable: {
                confirmation: function (e) {
                    return 'Do you really want to delete the customer?';
                },
                cancelDelete: 'No',
                confirmDelete: 'Yes',
                mode: 'inline'
            },
            columns: [
                    {
                        field: 'id',
                        title: 'ID'
                    },
                    {
                        field: 'name',
                        title: 'Customer'
                    },
                    {
                        field: 'company',
                        title: 'Company'
                    },
                    {
                        field: 'address',
                        title: 'Address'
                    },
                    {
                        field: 'city',
                        title: 'City'
                    },
                    {
                        field: 'postalCode',
                        title: 'Postal Code'
                    },
                    {
                        field: 'country',
                        title: 'Country'
                    },
                    {
                        field: 'phone',
                        title: 'Phone'
                    },
                    {
                        command: [
                            { name: 'edit', text: { edit: 'Edit', cancel: 'Cancel', update: 'OK' } },
                            { name: 'destroy', text: 'Delete' },
                        ],
                        title: ' ',
                        width: '220px'
                    }
            ]
        }
        //inject Kendo Grid with options set above
        $(document).ready(function () {
            var grid = $('#mithril-grid-demo').kendoGrid(options);

        });
    }
    //Create a new HTML element with Mithril
    //
    //One alternative to writing pure JavaScript templates could be
    //the port of React's JSX called MSX: https://github.com/insin/msx
    //****************************************************************************************
    //In "initKendoGrid" we process everything we need to manipulate the grid-structure
    //that relies on classes that do not belong to Mithril.
    //Kendo Grid knows nothing about Mithril and vice-versa and therefore we need some
    //extra functionality to process templates, detail vies etc.
    //More info regarding the property "config" here: http://lhorie.github.io/mithril/mithril.html#persisting-config-data
    app.view = function () {
        return m('div', { id: 'mithril-grid-demo', 'class': 'mithril-grid', config: initKendoGrid });
    };

}(window, Mithril));<|endoftext|>


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

.controller('HomeController', function($scope) {
    console.log('home page');
  })
  .controller('RegisterController', function($scope, Auth, $window, $location) {

    $scope.register = {
      email: '',
      password: ''
    };

    $scope.registerUser = function() {
      Auth.register($scope.register).then(function(res) {
        if (res.data.token) {
          $window.sessionStorage.token = res.data.token;
          $location.url('/account');
        }
      }, function(err) {
        console.log('Error');
      });
    }

  })
  .controller('LoginController', function($scope, Auth, $window, $location) {

    $scope.loginUser = function() {

      $scope.authString = $scope.login.email + ':' + $scope.login.password;

      Auth.login(btoa($scope.authString)).then(function(res) {
        // if the token exists, store it in session storage and redirect to account page
        if (res.data.token) {
          $window.sessionStorage.token = res.data.token;
          $location.url('/account');
        }
      });
    }
  })
  .controller('AccountController', function($scope, Post) {

    $scope.allPosts = {};
    $scope.newPost = {};
    $scope.updatePost = {};

    $scope.selectedIndex = null;

<<<<<<< HEAD
    $scope.interfaceIsOpen = false;
=======
    $scope.showPost = function(index) {
      $scope.post = $scope.allPosts[index];
      $scope.selectedIndex = index;
    };

    $scope.$on('POSTUPDATED', function(index) {
      $scope.showPost(index - 1);
    });
>>>>>>> 38cf8380bf196e159c49584618c615dacc3980e6

    $scope.newPostControls = {
      interfaceIsOpen: false,
      togglePostInterface: function() {
        this.interfaceIsOpen = !this.interfaceIsOpen;
<<<<<<< HEAD
      }
    };

    $scope.sendPost = function() {
      Post.createPost($scope.newPost).then(function(data) {
        console.log(data);
      });
    };

    $scope.editPost = function() {
      Post.updatePost($scope.updatePost).then(function(data) {
        console.log(data);
      });
    };
    Post.getPost().then(function(res) {
      $scope.allPosts = res.data.posts;
    });
  });
=======
      },
      sendPost: function() {
        Post.createPost(this.newPost).then((data) => {
          // Clear Form
          this.clearPost();
          // Broadcast POST UPDATED
          $rootScope.$broadcast('POSTUPDATED');
          this.togglePostInterface();
          console.log(data);
        }, function(err) {
          console.log('Error');
          console.log(err);
        })
      },
      clearPost: function() {
        this.newPost = {};
      }
    };

    $scope.deletePostControls = {
      delete: function(index) {
        Post.deletePost($scope.allPosts[index]).then(function(data) {
          console.log('Delete Successful');
          $rootScope.$broadcast('POSTUPDATED', index);
        }, function(err) {
          console.log('Failed to delete');
        })
      }
    };

    $scope.updatePostControls = {
      updateIsOpen: false,
      updateNewPost: {},
      togglePostInterface: function() {
        this.updateIsOpen = !this.updateIsOpen;
      },
      getOnePost: function(index) {
        this.updateIsOpen = true;
        $scope.post = $scope.allPosts[index];
        updateNewPost = $scope.post;
        var title = $scope.post.title;
        var desc = $scope.post.content.text;
        $scope.updatePostControls.title = title;
        $scope.updatePostControls.content = desc;
        console.log(title + '  ' + desc);
      },
      updateThePost: function() {
        $scope.post.title = $scope.updatePostControls.title;
        $scope.post.content.text = $scope.updatePostControls.content;
        Post.updatePost($scope.post).then((data) => {
          // Clear Form
          this.clearPost();
          // Broadcast POST UPDATED
          $rootScope.$broadcast('POSTUPDATED');
          this.togglePostInterface();
          console.log(data);
        }, function(err) {
          console.log('Error');
          console.log(err);
        })
      },
      clearPost: function() {
        this.updateNewPost = {};
      }
    }

    $scope.getAllPosts = function() {
      Post.getPost().then(function(res) {
        $scope.allPosts = res.data.posts;
        console.log('POSTS UPDATED');
      });
    }

    // Get all Posts when page first loads
    $scope.getAllPosts();

    $scope.$on('POSTUPDATED', function() {
      $scope.getAllPosts();
    })

  })

// DIRECTIVES
.directive("contenteditable", function() {
  return {
    restrict: "A",
    require: "ngModel",
    link: function(scope, element, attrs, ngModel) {

      function read() {
        ngModel.$setViewValue(element.html());
      }

      ngModel.$render = function() {
        element.html(ngModel.$viewValue || "");
      };

      element.bind("blur keyup change", function() {
        scope.$apply(read);
      });
    }
  };
})
>>>>>>> 38cf8380bf196e159c49584618c615dacc3980e6
<commit_msg>Fixed merge conflit<commit_after>angular.module('MainController', [])

.controller('HomeController', function($scope) {
    console.log('home page');
  })
  .controller('RegisterController', function($scope, Auth, $window, $location) {

    $scope.register = {
      email: '',
      password: ''
    };

    $scope.registerUser = function() {
      Auth.register($scope.register).then(function(res) {
        if (res.data.token) {
          $window.sessionStorage.token = res.data.token;
          $location.url('/account');
        }
      }, function(err) {
        console.log('Error');
      });
    }

  })
  .controller('LoginController', function($scope, Auth, $window, $location) {

    $scope.loginUser = function() {

      $scope.authString = $scope.login.email + ':' + $scope.login.password;

      Auth.login(btoa($scope.authString)).then(function(res) {
        // if the token exists, store it in session storage and redirect to account page
        if (res.data.token) {
          $window.sessionStorage.token = res.data.token;
          $location.url('/account');
        }
      });
    }
  })
  .controller('AccountController', function($scope, Post, $rootScope, Broadcast) {
    // List of all posts
    $scope.allPosts = [];
    // Empty object for updating post
    $scope.updatePost = {};
    //
    $scope.selectedIndex = null;

    // For selecting map/images/other
    $scope.include = {
      url: 'templates/map.html'
    };

    $scope.mediaInclude = {
      url: '',
      showMediaInclude: function(templateUrl) {
        this.url = templateUrl;
      }
    }

    // Show post when clicked in Preview
    $scope.showPost = function(index) {
      $scope.post = $scope.allPosts[index];
      $scope.selectedIndex = index;

      Broadcast.emit('NEWEVENTLOADED', $scope.post);
    };

    // Listen for Map Click Event to Add to NEW POST
    $scope.$on('LocationAdded', function(event, latlng) {
      $scope.newPostControls.newPost.location.coords = latlng;
    });

    // Controls for creating a new post
    $scope.newPostControls = {
      interfaceIsOpen: false,
      newPost: {
        location: {}
      },
      togglePostInterface: function() {
        this.interfaceIsOpen = !this.interfaceIsOpen;
      },
      sendPost: function() {
        Post.createPost(this.newPost).then((data) => {
          // Clear Form
          this.clearPost();
          // Broadcast POST UPDATED
          $rootScope.$broadcast('POSTUPDATED');
          this.togglePostInterface();
          console.log(data);
        }, function(err) {
          console.log('Error');
          console.log(err);
        })
      },
      clearPost: function() {
        this.newPost = {};
      }
    };

    $scope.deletePostControls = {
      delete: function(index) {
        Post.deletePost($scope.allPosts[index]).then(function(data) {
          console.log('Delete Successful');
          $rootScope.$broadcast('POSTUPDATED', index);
        }, function(err) {
          console.log('Failed to delete');
        })
      }
    };

    $scope.updatePostControls = {
      updateIsOpen: false,
      updateNewPost: {},
      togglePostInterface: function() {
        this.updateIsOpen = !this.updateIsOpen;
      },
      getOnePost: function(index) {
        this.updateIsOpen = true;
        $scope.post = $scope.allPosts[index];
        updateNewPost = $scope.post;
        var title = $scope.post.title;
        var desc = $scope.post.content.text;
        $scope.updatePostControls.title = title;
        $scope.updatePostControls.content = desc;
        console.log(title + '  ' + desc);
      },
      updateThePost: function() {
        $scope.post.title = $scope.updatePostControls.title;
        $scope.post.content.text = $scope.updatePostControls.content;
        Post.updatePost($scope.post).then((data) => {
          // Clear Form
          this.clearPost();
          // Broadcast POST UPDATED
          $rootScope.$broadcast('POSTUPDATED');
          this.togglePostInterface();
          console.log(data);
        }, function(err) {
          console.log('Error');
          console.log(err);
        })
      },
      clearPost: function() {
        this.updateNewPost = {};
      }
    }

    $scope.getAllPosts = function() {
      Post.getPost().then(function(res) {
        $scope.allPosts = res.data.posts;
        console.log('POSTS UPDATED');
      });
    }

    // Get all Posts when page first loads
    $scope.getAllPosts();

    $scope.$on('POSTUPDATED', function(index) {
      $scope.showPost(index + 1);
      $scope.getAllPosts();

    })

  })

// DIRECTIVES
.directive("contenteditable", function() {
  return {
    restrict: "A",
    require: "ngModel",
    link: function(scope, element, attrs, ngModel) {

      function read() {
        ngModel.$setViewValue(element.html());
      }

      ngModel.$render = function() {
        element.html(ngModel.$viewValue || "");
      };

      element.bind("blur keyup change", function() {
        scope.$apply(read);
      });
    }
  };
})
<|endoftext|>


<commit_before>/* Conway's Game of Life
    - A React-driven app that creates Conway's cellular automaton based on an initial state.
      https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life. A FreeCodeCamp project.

      RULES
      -----

      - Any live cell with fewer than two live neighbours dies, as if caused by under-population.
      - Any live cell with two or three live neighbours lives on to the next generation.
      - Any live cell with more than three live neighbours dies, as if by over-population.
      - Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

      www.softwareontheshore.com
*/

"use strict";

//React Bootstrap components
const ButtonToolbar = ReactBootstrap.ButtonToolbar;
const Button = ReactBootstrap.Button;

//script globals
var generations = 0;
var boardHeight = 50;
var generateTimer;

const BOARD_HEIGHT = 50;
const BOARD_WIDTH = 70;

const Game = React.createClass({ displayName: "Game",
  propTypes: {
    boardWidth: React.PropTypes.number.isRequired,
    boardHeight: React.PropTypes.number.isRequired
  },

  getInitialState: function getInitialState() {
    return({ board: [], time: 0 });
  },

  componentDidMount: function componentDidMount() {
    this.initiateBoard(200);
  },

  //generates the tiles and gives them a class based on the initial randomized board
  generateBoard: function generateBoard(boardState) {
    let generatedBoard = [];
    let tileKey = 0;
    boardState = boardState ? boardState : [-1];

    for(let j = 0; j < this.props.boardHeight; j++) {
      let id = "";

      for(let k = 0; k < this.props.boardWidth; k++) {
        id = String(j) + "-" + String(k);

        if(boardState.indexOf(id) > -1) {
          generatedBoard.push((
            React.createElement("div", { key: tileKey, id: id, className: "tile alive", onClick: this.changeTile })
          ));
        } else {
          generatedBoard.push((
            React.createElement("div", { key: tileKey, id: id, className: "tile dead", onClick: this.changeTile })
          ));
        }

        tileKey++;
      }
    }
    this.setState({ board: generatedBoard });
  },

  /* Generate an initial board at random when the page loads. Size of the random
    sample controlled by the passed variable */
  initiateBoard: function initiateBoard(sampleSize) {
    let boardState = [];

    for (let i = 0; i < sampleSize; i++) {
      boardState.push( String(Math.floor(Math.random() * (50))) + "-" + String(Math.floor(Math.random() * (70))) );
    }
    this.generateBoard(boardState);
  },

  /* starts the board setting the global interval variable */
  start: function start() {
    let self = this;
    generateTimer = setInterval(function runBoard() {
      self.handleTime();
      self.checkBoard();
    }, 750);
  },

  //pauses the board by clearing the global interval variable
  stop: function stop() {
    clearInterval(generateTimer);
  },

  //resets the board
  clear: function clear() {
    this.initiateBoard(0);
  },

  //allows the user to turn a tile on
  changeTile: function changeTile(event) {
    let target = $("#" + event.target.id);
    console.log(target);
    target.removeClass("tile alive dead old");
    target.addClass("tile alive");
  },

  //uses a global variable to track the generations and then a react.state to update dom
  handleTime: function handleTime() {
    generations++;
    this.setState({ time: generations });
  },

  /* checks the board start and runs it through Conway's algorithm to determine
    all tiles' state and then generates the board based on that state
    TODO: run the algo, update boardstate */
  checkBoard: function checkBoard() {
    let tiles = this.state.board;
    let self = this;

    tiles.forEach(function checkTile(tile){
      let tileID = tile.props.id;
      let tileY = Number(tileID.split("-")[0]);
      let tileX = Number(tileID.split("-")[1]);

      //figure out which function we should send our tile to in order to find neighbours
      let tileNeighbours =
          (tileY === 0 || tileY === self.props.boardHeight - 1 || tileX === 0 || tileX === self.props.boardWidth) ?
          self.findCornerNeighbours(tileID, tileY, tileX) : self.findNeighbours(tileID, tileY, tileX);

    });
  },

  //Return the 4 neighbours of this tile
  findNeighbours: function findNeighbours(tileID, tileY, tileX) {
    let neighbours = [];

    return neighbours;
  },

  //Return 4 neighbours of grid edge cases - wrap around the grid ()[50, 0] left neighbour = [50, 70])
  findCornerNeighbours: function findCornerNeighbours(tileID, tileY, tileX) {
    let neighbours = [];

    return neighbours;
  },

  render: function render() {
    return(
      React.createElement("div", { id: "content", className: "container" },
        React.createElement(ButtonToolbar, { id: "buttons" },
          React.createElement(Button, { id: "start-btn", onClick: this.start }, "Start"),
          React.createElement(Button, { id: "stop-btn", onClick: this.stop }, "Stop"),
          React.createElement(Button, { id: "clear-btn", onClick: this.clear }, "Clear"),
          React.createElement(Button, { id: "generations-btn", disabled: true }, "Generations: " + this.state.time)
        ),
        React.createElement(GameBoard, { board: this.state.board })
      )
    );
  }
});

const GameBoard = React.createClass({ displayName: "GameBoard",
  propTypes: {
    board: React.PropTypes.arrayOf(React.PropTypes.element.isRequired)
  },

  render: function render() {
    let boardNodes = this.props.board;
    return(
      React.createElement("div", { id: "board" }, boardNodes)
    );
  }
});

ReactDOM.render(React.createElement(Game, { boardWidth: BOARD_WIDTH, boardHeight: BOARD_HEIGHT }),
  document.getElementById("main"));
<commit_msg>started edge cases sieve on game-of-life app<commit_after>/* Conway's Game of Life
    - A React-driven app that creates Conway's cellular automaton based on an initial state.
      https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life. A FreeCodeCamp project.

      RULES
      -----

      - Any live cell with fewer than two live neighbours dies, as if caused by under-population.
      - Any live cell with two or three live neighbours lives on to the next generation.
      - Any live cell with more than three live neighbours dies, as if by over-population.
      - Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

      www.softwareontheshore.com
*/

"use strict";

/*
---- REACT BOOTSTRAP COMPONENTS -----
*/
const ButtonToolbar = ReactBootstrap.ButtonToolbar;
const Button = ReactBootstrap.Button;

/*
---- SCRIPT GLOBALS -----
*/
var generations = 0;
var boardHeight = 50;
var generateTimer;

const BOARD_HEIGHT = 50;
const BOARD_WIDTH = 70;

/*
---- CUSTOM REACT COMPONENTS -----
*/
const Game = React.createClass({ displayName: "Game",
  propTypes: {
    boardWidth: React.PropTypes.number.isRequired,
    boardHeight: React.PropTypes.number.isRequired
  },

  getInitialState: function getInitialState() {
    return({ board: [], time: 0 });
  },

  componentDidMount: function componentDidMount() {
    this.initiateBoard(200);
  },

  /*
  ---- GENERATE BOARD FUNCTION -----
      - generates the tiles and gives them a class based on the initial randomized board
  */
  generateBoard: function generateBoard(boardState) {
    let generatedBoard = [];
    let tileKey = 0;
    boardState = boardState ? boardState : [-1];

    for(let j = 0; j < this.props.boardHeight; j++) {
      let id = "";

      for(let k = 0; k < this.props.boardWidth; k++) {
        id = String(j) + "-" + String(k);

        if(boardState.indexOf(id) > -1) {
          generatedBoard.push((
            React.createElement("div", { key: tileKey, id: id, className: "tile alive", onClick: this.changeTile })
          ));
        } else {
          generatedBoard.push((
            React.createElement("div", { key: tileKey, id: id, className: "tile dead", onClick: this.changeTile })
          ));
        }

        tileKey++;
      }
    }
    this.setState({ board: generatedBoard });
  },

  /*
  ---- INITIATE BOARD FUNCTION-----
      - Generate an initial board at random when the page loads. Size of the random
        sample controlled by the passed variable. Also used to clear the board by generating
        an empty sample size. Then calls the rendering of the board.
  */
  initiateBoard: function initiateBoard(sampleSize) {
    let boardState = [];

    for (let i = 0; i < sampleSize; i++) {
      boardState.push( String(Math.floor(Math.random() * (50))) + "-" + String(Math.floor(Math.random() * (70))) );
    }
    this.generateBoard(boardState);
  },

  /*
  ---- START FUNCTION -----
      starts the board setting the global interval variable
  */
  start: function start() {
    let self = this;
    generateTimer = setInterval(function runBoard() {
      self.handleTime();
      self.checkBoard();
    }, 750);
  },

  /*
  ---- STOP FUNCTION -----
      pauses the board by clearing the global interval variable
  */
  stop: function stop() {
    clearInterval(generateTimer);
  },

  /*
  ---- CLEAR FUNCTION -----
      -resets the board by generating a blank sample array
  */
  clear: function clear() {
    this.initiateBoard(0);
  },

  /*
  --- CHANGE TILE FUNCTION -----
      - allows the user to turn the tile on
  */
  changeTile: function changeTile(event) {
    let target = $("#" + event.target.id);
    target.removeClass("tile alive dead old");
    target.addClass("tile alive");
  },

  /*
  ---- HANDLE TIME FUNCTION -----
      uses a global variable to track the generations and then a react.state to update dom
  */
  handleTime: function handleTime() {
    generations++;
    this.setState({ time: generations });
  },

  /*
  ---- CHECK BOARD FUNCTION -----
    - checks the board start and runs it through Conway's algorithm to determine
      all tiles' state and then generates the board based on that state
      TODO: run the algo, update boardstate
  */
  checkBoard: function checkBoard() {
    let tiles = this.state.board;
    let self = this;

    tiles.forEach(function checkTile(tile){
      let tileID = tile.props.id;
      let tileY = Number(tileID.split("-")[0]);
      let tileX = Number(tileID.split("-")[1]);

      //figure out which function we should send our tile to in order to find neighbours
      let tileNeighbours =
          (tileY === 0 || tileY === self.props.boardHeight - 1 || tileX === 0 || tileX === self.props.boardWidth) ?
          self.findEdgeNeighbours(tiles, tileID, tileY, tileX) : self.findNeighbours(tiles, tileID, tileY, tileX);

      tileNeighbours.forEach(function checkNeighbourStatus(tile) {

        //$("#" + tile)
      });

    });
  },

  /*
  ---- FIND NEIGHBOURS FUNCTION -----
      - a function to find the 8 neighbours of a 'normally' placed tile
  */
  findNeighbours: function findNeighbours(tiles, tileID, tileY, tileX) {
    let neighbours = [];

    //capture the horizontal neighbours
    neighbours.push(tileY + "-" + (tileX + 1));
    neighbours.push(tileY + "-" + (tileX - 1));

    //capture the 3 neighbours above and below;
    for(let i = tileX + 1; i > tileX - 2; i--) {
      let neighbourAbove = (tileY - 1) + "-" + i;
      let neighbourBelow = (tileY + 1) + "-" + i;
      neighbours.push(neighbourAbove);
      neighbours.push(neighbourBelow);
    }

    return neighbours;
  },

  /*
  ---- FIND EDGE NEIGHBOURS FUNCTION -----
      - return 8 neighbours of grid edge cases - wrap around the grid ()[50, 0] left neighbour = [50, 70])
  */
  findEdgeNeighbours: function findEdgeNeighbours(tiles, tileID, tileY, tileX) {
    let neighbours = [];
    let self = this;

    //check for top left corner case
    if (tileY === 0 && tileX === 0) {

    }
    //check for top right corner case
    else if (tileY === (boardHeight - 1) && tileX === (boardWidth - 1)) {

    }
    //check for bottom left corner case
    else if (tileY === (boardHeight - 1) && tileX === 0) {

    }
    //check for bottom right corner case
    else if (tileY === (boardHeight - 1) && tileX === (boardWidth - 1)){

    }
    //check for top row case
    else if (tileY === 0) {
      //get horizontal neighbours
      neighbours.push(tileY + "-" + (tileX + 1));
      neighbours.push(tileY + "-" + (tileX - 1));

      //capture the 3 neighbours wrapped above and below;
      for(let i = tileX + 1; i > tileX - 2; i--) {
        let neighbourAbove = (boardHeight - 1) + "-" + i;
        let neighbourBelow = (tileY + 1) + "-" + i;
        neighbours.push(neighbourAbove);
        neighbours.push(neighbourBelow);
      }

      return neighbours;
    }
    //check for bottom row case
    else if (tileY === (boardHeight - 1)) {
      //get horizontal neighbours
      neighbours.push(tileY + "-" + (tileX + 1));
      neighbours.push(tileY + "-" + (tileX - 1));

      //capture the 3 neighbours wrapped below and above;
      for(let i = tileX + 1; i > tileX - 2; i--) {
        let neighbourAbove = (tileY - 1) + "-" + i;
        let neighbourBelow = 0 + "-" + i;
        neighbours.push(neighbourAbove);
        neighbours.push(neighbourBelow);
      }

      return neighbours;
    }
    //check for left column case
    else if (tileX === 0) {
      //tileX = boardWidth - 1

      //get horizontal neighbours
      neighbours.push(tileY + "-" + (tileX + 1));
      neighbours.push(tileY + "-" + (boardWidth - 1));

      //capure the 3 neighbours above and below

    }
    //check for right column case
    else if (tile === (boardWidth - 1)) {
      //tileX = 0;

      //get horizontal neighbours
      neighbours.push(tileY + "-" + 0);
      neighbours.push(tileY + "-" + (tileX - 1));

      //capure the 3 neighbours above and below
    }
    else {
      console.log("Corner Case Error");
      return [];
    }
  },

  render: function render() {
    return(
      React.createElement("div", { id: "content", className: "container" },
        React.createElement(ButtonToolbar, { id: "buttons" },
          React.createElement(Button, { id: "start-btn", onClick: this.start }, "Start"),
          React.createElement(Button, { id: "stop-btn", onClick: this.stop }, "Stop"),
          React.createElement(Button, { id: "clear-btn", onClick: this.clear }, "Clear"),
          React.createElement(Button, { id: "generations-btn", disabled: true }, "Generations: " + this.state.time)
        ),
        React.createElement(GameBoard, { board: this.state.board })
      )
    );
  }
});

const GameBoard = React.createClass({ displayName: "GameBoard",
  propTypes: {
    board: React.PropTypes.arrayOf(React.PropTypes.element.isRequired)
  },

  render: function render() {
    let boardNodes = this.props.board;
    return(
      React.createElement("div", { id: "board" }, boardNodes)
    );
  }
});

ReactDOM.render(React.createElement(Game, { boardWidth: BOARD_WIDTH, boardHeight: BOARD_HEIGHT }),
  document.getElementById("main"));
<|endoftext|>


<commit_before>
import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableHighlight} from 'react-native';
import Chart from 'react-native-chart';
import ModalDropdown from 'react-native-modal-dropdown';

const colorSlices=['red','green','blue', 'black', 'yellow', 'orange','gray', 'silver' ];
let dataMlUsageHrAmPm= [1,3,9,4,8,3,7,9,4,8,3,7];
//let dataMlUsageHrAmPm= {this.state.dataAmPm.slice()};
let dataDayAmPm = [
  ['8a', dataMlUsageHrAmPm[0]],
  ['9a', dataMlUsageHrAmPm[1]],
  ['10a', dataMlUsageHrAmPm[2]],
  ['11a', dataMlUsageHrAmPm[3]],
  ['12p', dataMlUsageHrAmPm[4]],
  ['1p', dataMlUsageHrAmPm[5]],
  ['2p', dataMlUsageHrAmPm[6]],
  ['3p', dataMlUsageHrAmPm[7]],
  ['4p', dataMlUsageHrAmPm[8]],
  ['5p', dataMlUsageHrAmPm[9]],
  ['6p', dataMlUsageHrAmPm[10]],
  ['7p', dataMlUsageHrAmPm[11]],
];
//pm to am
let dataMlUsageHrPmAm= [1,3,9,4,8,3,7,18,4,8,3,7];
let dataDayPmAm = [
  ['8a', dataMlUsageHrPmAm[0]],
  ['9a', dataMlUsageHrPmAm[1]],
  ['10a', dataMlUsageHrPmAm[2]],
  ['11a', dataMlUsageHrPmAm[3]],
  ['12p', dataMlUsageHrPmAm[4]],
  ['1p', dataMlUsageHrPmAm[5]],
  ['2p', dataMlUsageHrPmAm[6]],
  ['3p', dataMlUsageHrPmAm[7]],
  ['4p', dataMlUsageHrPmAm[8]],
  ['5p', dataMlUsageHrPmAm[9]],
  ['6p', dataMlUsageHrPmAm[10]],
  ['7p', dataMlUsageHrPmAm[11]],
];

//weekly
// let dataMlUsageDay= [1,3,9,4,8,3,7];
//change this so it gets input from database
// let dataWeek = [
//   ['S', dataMlUsageDay[0]],
//   ['M', dataMlUsageDay[1]],
//   ['T', dataMlUsageDay[2]],
//   ['W', dataMlUsageDay[3]],
//   ['Th', dataMlUsageDay[4]],
//   ['F', dataMlUsageDay[5]],
//   ['S', dataMlUsageDay[6]],
// ];
//monthly
let dataMlUsageMonth=[1,3,9,4,8,3,7,9,4,8,3,7];
//change this so it gets input from database
let dataMonth = [
  ['Jan', dataMlUsageMonth[0]],
  ['Feb', dataMlUsageMonth[1]],
  ['Mar', dataMlUsageMonth[2]],
  ['Apr', dataMlUsageMonth[3]],
  ['May', dataMlUsageMonth[4]],
  ['Jun', dataMlUsageMonth[5]],
  ['Jul', dataMlUsageMonth[6]],
  ['Aug', dataMlUsageMonth[7]],
  ['Sep', dataMlUsageMonth[8]],
  ['Oct', dataMlUsageMonth[9]],
  ['Nov', dataMlUsageMonth[10]],
  ['Dec', dataMlUsageMonth[11]],
];

export default class MeterGraphs extends Component {
  static get defaultProps() {
    return {
      title: 'MeterGraphs'
    };
  }

  constructor(props) {
    super(props);

    // Initialize state letiables
    this.state = {
      graphList: ['line', 'bar'],
    //graph state to switch rendering
      graphType: 'bar',
      graphshowAxes: true,
      graphTimeList: ['daily(8am>7pm)','daily(8pm>7am)','weekly','monthly'],
      dataArray: dataDayAmPm,
      dataAmPm: [100,300,900,400,800,300,700,900,400,800,300,700]
    };

    this.dropdownRenderRow = this.dropdownRenderRow.bind(this);
    this.viewGraph = this.viewGraph.bind(this);
    this.viewTimeGraph = this.viewTimeGraph.bind(this);
    this.color = 'white';
  }

  render() {
    return (
      <View style={styles.container}>
        <View>
          <Text style={styles.title}>Device Overview</Text>
        </View>
        <ModalDropdown style={styles.dropdown}
        options={this.state.graphList}
        textStyle={styles.dropdownText}
        dropdownStyle={styles.dropdownDropdown1}
        defaultValue='Change Graph Type'
        renderRow={this.dropdownRenderRow}
        onSelect={this.viewGraph}
        />
        <ModalDropdown style={styles.dropdown}
          options={this.state.graphTimeList}
          textStyle={styles.dropdownText}
          dropdownStyle={styles.dropdownDropdown2}
          defaultValue='Change Graph Time'
          renderRow={this.dropdownRenderRow}
          onSelect={this.viewTimeGraph}
        />
        <Chart
          color={'white'}
          axisColor={'white'}
          axisLabelColor={'white'}
          axisLineWidth={1}

          xAxisHeight={40}
          yAxisWidth={19}

          cornerRadius={4}

          data={this.state.dataArray}

          hideHorizontalGridLines={true}
          hideVerticalGridLines={true}

          widthPercent={1}
          verticalGridStep={5}
          horizontalGridStep={2}

          type={this.state.graphType}
          lineWidth={4}

          showDataPoint={false}
          showAxis={this.state.graphshowAxes}

          style={styles.chart}
          labelFontSize={14}

          sliceColors={colorSlices}
        />
      </View>
    );
  }

  dropdownRenderRow(rowData, rowID, highlighted) {
    let evenRow = rowID % 2;
    return (
      <TouchableHighlight underlayColor='cornflowerblue'>
       <View style={[styles.dropdownRow, {backgroundColor: evenRow ? 'rgb(31,58,147)' : 'rgb(31,58,147)'}]}>
          <Text style={[styles.dropdownRowText, highlighted && {color: 'white'}]}>
             {rowData}
          </Text>
        </View>
      </TouchableHighlight>
    );
  }
  viewGraph(index, value) {
    if (value=='bar')
    {
      this.setState({graphType: 'bar'});
      this.setState({graphshowAxes: true});
    }
    if (value=='line')
    {
      this.setState({graphType: 'line'});
      this.setState({graphshowAxes: true});
    }
  }

  viewTimeGraph(index, value) {
    let dataMlReplace = this.state.dataAmPm.slice();
    let dataDayReplace = [
      ['8a', dataMlReplace[0]],
      ['9a', dataMlReplace[1]],
      ['10a', dataMlReplace[2]],
      ['11a', dataMlReplace[3]],
      ['12p', dataMlReplace[4]],
      ['1p', dataMlReplace[5]],
      ['2p', dataMlReplace[6]],
      ['3p', dataMlReplace[7]],
      ['4p', dataMlReplace[8]],
      ['5p', dataMlReplace[9]],
      ['6p', dataMlReplace[10]],
      ['7p', dataMlReplace[11]],
    ];
    if (value=='weekly') {
      this.setState({dataArray: dataDayReplace});
    }
    if (value=='daily(8am>7pm)') {
      this.setState({dataArray: dataDayAmPm });
    }
    if (value=='daily(8pm>7am)') {
      this.setState({dataArray: dataDayPmAm });
    }
    if (value=='monthly') {
      this.setState({dataArray: dataMonth});
    }

  }
}

/*Pseudo-code for getting input from database:
Stringify JSON object
ex. (timeStarted,timeEnded,totalWaterUsed)
eg. (8.23am=>8.45am,10)
//categorize into which hour the event was..ie if user
//had shower from 8:59am until 9:30 then it will be graphed as a 9am event.
//same hour
if (charAt(1)==8 && charAt(5)==a && charAt(9)==8 && charAt(13)==a)
{
  arrayOfTimesAndUsage[[0,0]]=8
  //if 2 digit number (check closed parenthesis position)
  //then
    arrayOfTimesAndUsage[[0,1]]=parseInt(charAt(16)&&charAt(17))
  //else
    arrayOfTimesAndUsage[[0,1]]=parseInt(charAt(16)
}
//^^copy and paste this for different hours and times (am/pm, 1-12)
//could make life a lot easier if we just went off time ended or time started
//or middle between them.
//goes into next hour, choose where more water was used as hour
//goes into multiple hours,
//usageEvents when it goes on for more than a day?
//add up multiple events within same hour, make one piece of data
//
*/

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'column',
    backgroundColor:'rgb(52,152,219)',
  },
  chart: {
    width: 345,
    height: 70,
    margin: 1,
    marginTop: 5,
    marginBottom: 190,
  },
  title: {
    textAlign: 'center',
    color: 'white',
    marginTop: 150,
    fontSize: 20,
    fontWeight: '400',
    marginBottom: 2
  },
  dropdown: {
    margin: 2,
    borderColor:  'rgb(31,58,147)',
    backgroundColor: 'rgb(31,58,147)',
    borderWidth: 1,
    borderRadius: 1,
    width:170,
    height:40,
  },
  dropdownText: {
    marginVertical: 10,
    marginHorizontal: 6,
    fontSize: 14,
    color: 'white',
    textAlign: 'center',
    textAlignVertical: 'center',
  },
  dropdownDropdown1: {
    margin: 8,
    width: 152,
    height: 80,
    borderColor: 'rgb(31,58,147)',
    borderWidth: 2,
    borderRadius: 3,
    backgroundColor: 'rgb(31,58,147)',
  },
  dropdownDropdown2: {
    margin: 8,
    width: 152,
    height: 100,
    borderColor: 'rgb(31,58,147)',
    borderWidth: 2,
    borderRadius: 3,
    backgroundColor: 'rgb(31,58,147)',
  },
  dropdownRow: {
    flexDirection: 'row',
    height: 40,
    alignItems: 'center',
    backgroundColor: 'rgb(31,58,147)'
  },
  dropdownRowText: {
    marginHorizontal: 4,
    fontSize: 12,
    color: 'white',
    textAlignVertical: 'center',
    textAlign: 'center',
  }
});
<commit_msg>Styling Improvements<commit_after>
import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableHighlight} from 'react-native';
import Chart from 'react-native-chart';
import ModalDropdown from 'react-native-modal-dropdown';

const colorSlices=['red','green','blue', 'black', 'yellow', 'orange','gray', 'silver' ];
let dataMlUsageHrAmPm= [1,3,9,4,8,3,7,9,4,8,3,7];
//let dataMlUsageHrAmPm= {this.state.dataAmPm.slice()};
let dataDayAmPm = [
  ['8a', dataMlUsageHrAmPm[0]],
  ['9a', dataMlUsageHrAmPm[1]],
  ['10a', dataMlUsageHrAmPm[2]],
  ['11a', dataMlUsageHrAmPm[3]],
  ['12p', dataMlUsageHrAmPm[4]],
  ['1p', dataMlUsageHrAmPm[5]],
  ['2p', dataMlUsageHrAmPm[6]],
  ['3p', dataMlUsageHrAmPm[7]],
  ['4p', dataMlUsageHrAmPm[8]],
  ['5p', dataMlUsageHrAmPm[9]],
  ['6p', dataMlUsageHrAmPm[10]],
  ['7p', dataMlUsageHrAmPm[11]],
];
//pm to am
let dataMlUsageHrPmAm= [1,3,9,4,8,3,7,18,4,8,3,7];
let dataDayPmAm = [
  ['8a', dataMlUsageHrPmAm[0]],
  ['9a', dataMlUsageHrPmAm[1]],
  ['10a', dataMlUsageHrPmAm[2]],
  ['11a', dataMlUsageHrPmAm[3]],
  ['12p', dataMlUsageHrPmAm[4]],
  ['1p', dataMlUsageHrPmAm[5]],
  ['2p', dataMlUsageHrPmAm[6]],
  ['3p', dataMlUsageHrPmAm[7]],
  ['4p', dataMlUsageHrPmAm[8]],
  ['5p', dataMlUsageHrPmAm[9]],
  ['6p', dataMlUsageHrPmAm[10]],
  ['7p', dataMlUsageHrPmAm[11]],
];

//weekly
// let dataMlUsageDay= [1,3,9,4,8,3,7];
//change this so it gets input from database
// let dataWeek = [
//   ['S', dataMlUsageDay[0]],
//   ['M', dataMlUsageDay[1]],
//   ['T', dataMlUsageDay[2]],
//   ['W', dataMlUsageDay[3]],
//   ['Th', dataMlUsageDay[4]],
//   ['F', dataMlUsageDay[5]],
//   ['S', dataMlUsageDay[6]],
// ];
//monthly
let dataMlUsageMonth=[1,3,9,4,8,3,7,9,4,8,3,7];
//change this so it gets input from database
let dataMonth = [
  ['Jan', dataMlUsageMonth[0]],
  ['Feb', dataMlUsageMonth[1]],
  ['Mar', dataMlUsageMonth[2]],
  ['Apr', dataMlUsageMonth[3]],
  ['May', dataMlUsageMonth[4]],
  ['Jun', dataMlUsageMonth[5]],
  ['Jul', dataMlUsageMonth[6]],
  ['Aug', dataMlUsageMonth[7]],
  ['Sep', dataMlUsageMonth[8]],
  ['Oct', dataMlUsageMonth[9]],
  ['Nov', dataMlUsageMonth[10]],
  ['Dec', dataMlUsageMonth[11]],
];

export default class MeterGraphs extends Component {
  static get defaultProps() {
    return {
      title: 'MeterGraphs'
    };
  }

  constructor(props) {
    super(props);

    // Initialize state letiables
    this.state = {
      graphList: ['line', 'bar'],
    //graph state to switch rendering
      graphType: 'bar',
      graphshowAxes: true,
      graphTimeList: ['daily(8am>7pm)','daily(8pm>7am)','weekly','monthly'],
      dataArray: dataDayAmPm,
      dataAmPm: [100,300,900,400,800,300,700,900,400,800,300,700]
    };

    this.dropdownRenderRow = this.dropdownRenderRow.bind(this);
    this.viewGraph = this.viewGraph.bind(this);
    this.viewTimeGraph = this.viewTimeGraph.bind(this);
    this.color = 'white';
  }

  render() {
    return (
      <View style={styles.container}>
        <View>
          <Text style={styles.title}>Device Overview</Text>
        </View>
        <ModalDropdown style={styles.dropdown}
        options={this.state.graphList}
        textStyle={styles.dropdownText}
        dropdownStyle={styles.dropdownDropdown1}
        defaultValue='Change Graph Type'
        renderRow={this.dropdownRenderRow}
        onSelect={this.viewGraph}
        />
        <ModalDropdown style={styles.dropdown}
          options={this.state.graphTimeList}
          textStyle={styles.dropdownText}
          dropdownStyle={styles.dropdownDropdown2}
          defaultValue='Change Graph Time'
          renderRow={this.dropdownRenderRow}
          onSelect={this.viewTimeGraph}
        />
        <Chart
          color={'white'}
          axisColor={'white'}
          axisLabelColor={'white'}
          axisLineWidth={1}

          xAxisHeight={40}
          yAxisWidth={19}

          cornerRadius={4}

          data={this.state.dataArray}

          hideHorizontalGridLines={true}
          hideVerticalGridLines={true}

          widthPercent={1}
          verticalGridStep={5}
          horizontalGridStep={2}

          type={this.state.graphType}
          lineWidth={4}

          showDataPoint={false}
          showAxis={this.state.graphshowAxes}

          style={styles.chart}
          labelFontSize={14}

          sliceColors={colorSlices}
        />
      </View>
    );
  }

  dropdownRenderRow(rowData, rowID, highlighted) {
    let evenRow = rowID % 2;
    return (
      <TouchableHighlight underlayColor='cornflowerblue'>
       <View style={[styles.dropdownRow, {backgroundColor: evenRow ? 'rgb(31,58,147)' : 'rgb(31,58,147)'}]}>
          <Text style={[styles.dropdownRowText, highlighted && {color: 'white'}]}>
             {rowData}
          </Text>
        </View>
      </TouchableHighlight>
    );
  }
  viewGraph(index, value) {
    if (value=='bar')
    {
      this.setState({graphType: 'bar'});
      this.setState({graphshowAxes: true});
    }
    if (value=='line')
    {
      this.setState({graphType: 'line'});
      this.setState({graphshowAxes: true});
    }
  }

  viewTimeGraph(index, value) {
    let dataMlReplace = this.state.dataAmPm.slice();
    let dataDayReplace = [
      ['8a', dataMlReplace[0]],
      ['9a', dataMlReplace[1]],
      ['10a', dataMlReplace[2]],
      ['11a', dataMlReplace[3]],
      ['12p', dataMlReplace[4]],
      ['1p', dataMlReplace[5]],
      ['2p', dataMlReplace[6]],
      ['3p', dataMlReplace[7]],
      ['4p', dataMlReplace[8]],
      ['5p', dataMlReplace[9]],
      ['6p', dataMlReplace[10]],
      ['7p', dataMlReplace[11]],
    ];
    if (value=='weekly') {
      this.setState({dataArray: dataDayReplace});
    }
    if (value=='daily(8am>7pm)') {
      this.setState({dataArray: dataDayAmPm });
    }
    if (value=='daily(8pm>7am)') {
      this.setState({dataArray: dataDayPmAm });
    }
    if (value=='monthly') {
      this.setState({dataArray: dataMonth});
    }

  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'column',
    backgroundColor:'rgb(52,152,219)',
  },
  chart: {
    width: 345,
    height: 70,
    margin: 1,
    marginTop: 5,
    marginBottom: 190,
  },
  title: {
    textAlign: 'center',
    color: 'white',
    marginTop: 150,
    fontSize: 20,
    fontWeight: '400',
    marginBottom: 2
  },
  dropdown: {
    margin: 2,
    borderColor:  'gray',
    borderWidth: 1,
    borderRadius: 1,
    backgroundColor: 'rgb(31,58,147)',
    width:170,
    height:40,
  },
  dropdownText: {
    marginVertical: 10,
    marginHorizontal: 6,
    fontSize: 14,
    color: 'white',
    textAlign: 'center',
    textAlignVertical: 'center',
  },
  dropdownDropdown1: {
    margin: 8,
    width: 152,
    height: 80,
    borderColor: 'gray',
    borderWidth: 2,
    borderRadius: 3,
    backgroundColor: 'rgb(31,58,147)',
  },
  dropdownDropdown2: {
    margin: 8,
    width: 152,
    height: 165,
    borderColor: 'gray',
    borderWidth: 2,
    borderRadius: 3,
    backgroundColor: 'rgb(31,58,147)',
  },
  dropdownRow: {
    flexDirection: 'row',
    height: 40,
    alignItems: 'center',
    backgroundColor: 'rgb(31,58,147)'
  },
  dropdownRowText: {
    marginHorizontal: 4,
    fontSize: 12,
    color: 'white',
    textAlignVertical: 'center',
    textAlign: 'center',
  }
});
<|endoftext|>


<commit_before>(function() {
  angular
    .module("app.directives")
    .directive("imNavbar", imNavbar);

  function imNavbar() {
    var directive = {
      restrict: "E",
      templateUrl: "navbar.html"
    };

    return directive;
  };
})();
<commit_msg>Implementa listener para alteração no login e simula logout<commit_after>(function() {
  angular
    .module("app.directives")
    .directive("imNavbar", imNavbar);

  function imNavbar() {
    var directive = {
      restrict: "E",
      templateUrl: "navbar.html",
      controller: imNavbarCtrl,
      controllerAs: "vm",
      bindToController: true
    };

    imNavbarCtrl.$inject = ["$rootScope", "$state"];

    function imNavbarCtrl($rootScope, $state) {
      var vm = this;

      vm.isAuthenticated = false;

      vm.signOut = signOut;

      $rootScope.$on("authChanged", updateUser);

      function updateUser(event, isAuthenticated) {
        vm.isAuthenticated = isAuthenticated;
      };

      function signOut() {
        $rootScope.$emit("authChanged", false);
        $state.go("auth");
      };
    };

    return directive;
  };
})();
<|endoftext|>


<commit_before>"use strict";

var WebGMEGlobal = { 'version': 'pre-alpha',
    'SUPPORTS_TOUCH': 'ontouchstart' in window || navigator.msMaxTouchPoints }; //touch device detection}

// let require load all the toplevel needed script and call us on domReady
define(['logManager',
    'bin/getconfig',
    'js/client',
    'clientUtil',
    'js/Utils/GMEConcepts',
    'js/LayoutManager/LayoutManager',
    'js/Decorators/DecoratorManager',
    'js/KeyboardManager/KeyboardManager',
    'js/PanelManager/PanelManager',
    './WebGME.History',
    'js/Utils/METAAspectHelper',
    'js/ConstraintManager/ConstraintManager'], function (logManager,
                                            CONFIG,
                                            Client,
                                            util,
                                            GMEConcepts,
                                            LayoutManager,
                                            DecoratorManager,
                                            KeyboardManager,
                                            PanelManager,
                                            WebGMEHistory,
                                            METAAspectHelper,
                                            ConstraintManager) {

    var _webGMEStart = function () {
        var lm,
            client,
            loadPanels,
            layoutToLoad = util.getURLParameterByName('layout') || 'DefaultLayout',
            commitToLoad = util.getURLParameterByName('commit').toLowerCase(),
            projectToLoad = util.getURLParameterByName('project'),
            objectToLoad = util.getURLParameterByName('obj').toLowerCase(),
            logger = logManager.create('WebGME'),
            selectObject;

        lm = new LayoutManager();
        lm.loadLayout(layoutToLoad, function () {
            var panels = [],
                layoutPanels = lm._currentLayout.panels,
                len = layoutPanels ? layoutPanels.length : 0,
                i;

            client = new Client(CONFIG);

            WebGMEGlobal.ConstraintManager = new ConstraintManager(client);

            WebGMEHistory.setClient(client);

            GMEConcepts.initialize(client);

            METAAspectHelper.initialize(client);

            //hook up branch changed to set read-only mode on panels
            client.addEventListener(client.events.BRANCH_CHANGED, function (__project, branchName) {
                var readOnly = branchName === null || branchName === undefined;
                lm.setPanelReadOnly(readOnly);
            });

            client.decoratorManager = new DecoratorManager();

            for (i = 0; i < len; i += 1) {
                panels.push({'panel': layoutPanels[i].panel,
                    'container': layoutPanels[i].container,
                    'control': layoutPanels[i].control,
                    'params' : {'client': client}});
            }

            //load the panels
            loadPanels(panels);

            //as of now it's a global variable just to make access to it easier
            //TODO: might need to be changed
            WebGMEGlobal.KeyboardManager = KeyboardManager;
            WebGMEGlobal.KeyboardManager.setEnabled(true);
            WebGMEGlobal.PanelManager = new PanelManager();
        });

        loadPanels = function (panels) {
            var p = panels.splice(0, 1)[0];

            lm.loadPanel(p, function () {
                if (panels.length > 0) {
                    loadPanels(panels);
                } else {
                    client.connectToDatabaseAsync({'open': true,
                                                    'project': projectToLoad || CONFIG.project}, function (err) {
                        if (err) {
                            logger.error(err);
                        } else {
                            if (commitToLoad && commitToLoad !== "") {
                                client.selectCommitAsync(commitToLoad, function (err) {
                                    if (err) {
                                        logger.error(err);
                                    } else {
                                        selectObject();
                                    }
                                });
                            } else {
                                selectObject();
                            }
                        }
                    });
                }
            });
        };

        selectObject = function () {
            if (objectToLoad && objectToLoad !== "") {
                setTimeout(function () {
                    client.setSelectedObjectId(objectToLoad);
                }, 1000);
            }
        };
    };

    return {
        start : _webGMEStart
    };
});<commit_msg>'version': 'Demo - 12/16/2013'<commit_after>"use strict";

var WebGMEGlobal = { 'version': 'Demo - 12/16/2013',
    'SUPPORTS_TOUCH': 'ontouchstart' in window || navigator.msMaxTouchPoints }; //touch device detection}

// let require load all the toplevel needed script and call us on domReady
define(['logManager',
    'bin/getconfig',
    'js/client',
    'clientUtil',
    'js/Utils/GMEConcepts',
    'js/LayoutManager/LayoutManager',
    'js/Decorators/DecoratorManager',
    'js/KeyboardManager/KeyboardManager',
    'js/PanelManager/PanelManager',
    './WebGME.History',
    'js/Utils/METAAspectHelper',
    'js/ConstraintManager/ConstraintManager'], function (logManager,
                                            CONFIG,
                                            Client,
                                            util,
                                            GMEConcepts,
                                            LayoutManager,
                                            DecoratorManager,
                                            KeyboardManager,
                                            PanelManager,
                                            WebGMEHistory,
                                            METAAspectHelper,
                                            ConstraintManager) {

    var _webGMEStart = function () {
        var lm,
            client,
            loadPanels,
            layoutToLoad = util.getURLParameterByName('layout') || 'DefaultLayout',
            commitToLoad = util.getURLParameterByName('commit').toLowerCase(),
            projectToLoad = util.getURLParameterByName('project'),
            objectToLoad = util.getURLParameterByName('obj').toLowerCase(),
            logger = logManager.create('WebGME'),
            selectObject;

        lm = new LayoutManager();
        lm.loadLayout(layoutToLoad, function () {
            var panels = [],
                layoutPanels = lm._currentLayout.panels,
                len = layoutPanels ? layoutPanels.length : 0,
                i;

            client = new Client(CONFIG);

            WebGMEGlobal.ConstraintManager = new ConstraintManager(client);

            WebGMEHistory.setClient(client);

            GMEConcepts.initialize(client);

            METAAspectHelper.initialize(client);

            //hook up branch changed to set read-only mode on panels
            client.addEventListener(client.events.BRANCH_CHANGED, function (__project, branchName) {
                var readOnly = branchName === null || branchName === undefined;
                lm.setPanelReadOnly(readOnly);
            });

            client.decoratorManager = new DecoratorManager();

            for (i = 0; i < len; i += 1) {
                panels.push({'panel': layoutPanels[i].panel,
                    'container': layoutPanels[i].container,
                    'control': layoutPanels[i].control,
                    'params' : {'client': client}});
            }

            //load the panels
            loadPanels(panels);

            //as of now it's a global variable just to make access to it easier
            //TODO: might need to be changed
            WebGMEGlobal.KeyboardManager = KeyboardManager;
            WebGMEGlobal.KeyboardManager.setEnabled(true);
            WebGMEGlobal.PanelManager = new PanelManager();
        });

        loadPanels = function (panels) {
            var p = panels.splice(0, 1)[0];

            lm.loadPanel(p, function () {
                if (panels.length > 0) {
                    loadPanels(panels);
                } else {
                    client.connectToDatabaseAsync({'open': true,
                                                    'project': projectToLoad || CONFIG.project}, function (err) {
                        if (err) {
                            logger.error(err);
                        } else {
                            if (commitToLoad && commitToLoad !== "") {
                                client.selectCommitAsync(commitToLoad, function (err) {
                                    if (err) {
                                        logger.error(err);
                                    } else {
                                        selectObject();
                                    }
                                });
                            } else {
                                selectObject();
                            }
                        }
                    });
                }
            });
        };

        selectObject = function () {
            if (objectToLoad && objectToLoad !== "") {
                setTimeout(function () {
                    client.setSelectedObjectId(objectToLoad);
                }, 1000);
            }
        };
    };

    return {
        start : _webGMEStart
    };
});<|endoftext|>


<commit_before>var win = Titanium.UI.currentWindow;

Titanium.include("../db/staticdb.js");

var currentDistance = 2;
var FACTOR = 0.01862;
var currentRegion = null;
var myLocationAnn = null;

var isAndroid = false;
if (Titanium.Platform.name == 'android') {
	isAndroid = true;
}

Ti.Geolocation.preferredProvider = "gps";
if (isIPhone3_2_Plus())
{
	Ti.Geolocation.purpose = "GPS demo";
}
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_HUNDRED_METERS;
Titanium.Geolocation.distanceFilter = 10;

if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}

var km2 = Titanium.UI.createButton({
	title:"2 km",
	height: 11,
	width: "auto"
});

var km5 = Titanium.UI.createButton({
	title:"5 km",
	height: 11,
	width: "auto"
});

var km10 = Titanium.UI.createButton({
	title:"10 km",
	height: 11,
	width: "auto"
});

var back = Titanium.UI.createButton({
	title:"<",
	height: 11,
	width: "auto"
});

var flexSpace = Titanium.UI.createButton({
	systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
});

var toolbar = Titanium.UI.createToolbar({
	items:[back, flexSpace, km2, flexSpace, km5, flexSpace, km10, flexSpace],
	bottom:0,
	height: 15,
	borderTop:true,
	borderBottom:false,
	translucent:true,
	barColor:'#999'
});

var mapview = Titanium.Map.createView({
	mapType: Titanium.Map.STANDARD_TYPE,
	animate:true,
	regionFit:true,
	userLocation:true
});

var updateLocation = function(){
	Titanium.Geolocation.getCurrentPosition(function(e)
		{
			var longitude = e.coords.longitude;
			var latitude = e.coords.latitude;
			currentRegion = {latitude:latitude, longitude:longitude, latitudeDelta:FACTOR, longitudeDelta: FACTOR};
			drawRegion();
		}
	);
};

var activateCurrentLocListener = function() {
	Titanium.Geolocation.addEventListener('location', function() {
		updateLocation();
	});
};

var drawRegion = function(){
	mapview.setLocation(currentRegion);
	var matchedHotels = searchNearBy(currentRegion, currentDistance);
	for (var i=0; i < matchedHotels.length; i++) {
		var annot = Titanium.Map.createAnnotation({
			latitude:matchedHotels[i].hotel.latitude,
	    	longitude:matchedHotels[i].hotel.longitude,
	    	title:matchedHotels[i].hotel.name,
		    subtitle: matchedHotels[i].distance +' km',
	    	pincolor:Titanium.Map.ANNOTATION_RED,
	    	rightButton: Titanium.UI.iPhone.SystemButton.DISCLOSURE,
	    	animate:true,
		});
			mapview.addAnnotation(annot);
	};
}

function isIPhone3_2_Plus()
{
	// add iphone specific tests
	if (Titanium.Platform.name == 'iPhone OS')
	{
		var version = Titanium.Platform.version.split(".");
		var major = parseInt(version[0],10);
		var minor = parseInt(version[1],10);

		// can only test this support on a 3.2+ device
		if (major > 3 || (major == 3 && minor > 1))
		{
			return true;
		}
	}
	return false;
}

back.addEventListener("click", function(e){
	win.container.setActiveTab(1);
});

km2.addEventListener("click", function(e){
	mapview.removeAllAnnotations();
	currentDistance = 2;
	currentRegion.latitudeDelta = currentRegion.longitudeDelta = FACTOR,
	drawRegion();
});

km5.addEventListener("click", function(e){
	mapview.removeAllAnnotations();
	currentDistance = 5;
	currentRegion.latitudeDelta = currentRegion.longitudeDelta = FACTOR * 5,
	drawRegion();
});

km10.addEventListener("click", function(e){
	mapview.removeAllAnnotations();
	currentDistance = 10;
	currentRegion.latitudeDelta = currentRegion.longitudeDelta = FACTOR * 10,
	drawRegion();
});

win.add(mapview);
win.add(toolbar);
updateLocation();<commit_msg>listener test<commit_after>var win = Titanium.UI.currentWindow;

Titanium.include("../db/staticdb.js");

var currentDistance = 2;
var FACTOR = 0.01862;
var currentRegion = null;
var myLocationAnn = null;

var isAndroid = false;
if (Titanium.Platform.name == 'android') {
	isAndroid = true;
}

Ti.Geolocation.preferredProvider = "gps";
if (isIPhone3_2_Plus())
{
	Ti.Geolocation.purpose = "GPS demo";
}
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_HUNDRED_METERS;
Titanium.Geolocation.distanceFilter = 10;

if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}

var km2 = Titanium.UI.createButton({
	title:"2 km",
	height: 11,
	width: "auto"
});

var km5 = Titanium.UI.createButton({
	title:"5 km",
	height: 11,
	width: "auto"
});

var km10 = Titanium.UI.createButton({
	title:"10 km",
	height: 11,
	width: "auto"
});

var back = Titanium.UI.createButton({
	title:"<",
	height: 11,
	width: "auto"
});

var flexSpace = Titanium.UI.createButton({
	systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
});

var toolbar = Titanium.UI.createToolbar({
	items:[back, flexSpace, km2, flexSpace, km5, flexSpace, km10, flexSpace],
	bottom:0,
	height: 15,
	borderTop:true,
	borderBottom:false,
	translucent:true,
	barColor:'#999'
});

var mapview = Titanium.Map.createView({
	mapType: Titanium.Map.STANDARD_TYPE,
	animate:true,
	regionFit:true,
	userLocation:true
});

var updateLocation = function(){
	Titanium.Geolocation.getCurrentPosition(function(e)
		{
			var longitude = e.coords.longitude;
			var latitude = e.coords.latitude;
			currentRegion = {latitude:latitude, longitude:longitude, latitudeDelta:FACTOR, longitudeDelta: FACTOR};
			drawRegion();
		}
	);
};

var activateCurrentLocListener = function() {
	Titanium.Geolocation.addEventListener('location', function() {
		updateLocation();
	});
};

var drawRegion = function(){
	mapview.setLocation(currentRegion);
	var matchedHotels = searchNearBy(currentRegion, currentDistance);
	for (var i=0; i < matchedHotels.length; i++) {
		var annot = Titanium.Map.createAnnotation({
			latitude:matchedHotels[i].hotel.latitude,
	    	longitude:matchedHotels[i].hotel.longitude,
	    	title:matchedHotels[i].hotel.name,
		    subtitle: matchedHotels[i].distance +' km',
	    	pincolor:Titanium.Map.ANNOTATION_RED,
	    	rightButton: Titanium.UI.iPhone.SystemButton.DISCLOSURE,
	    	id: matchedHotels[i].hotel.id,
	    	animate:true,
		});
			mapview.addAnnotation(annot);
	};
}

function isIPhone3_2_Plus()
{
	// add iphone specific tests
	if (Titanium.Platform.name == 'iPhone OS')
	{
		var version = Titanium.Platform.version.split(".");
		var major = parseInt(version[0],10);
		var minor = parseInt(version[1],10);

		// can only test this support on a 3.2+ device
		if (major > 3 || (major == 3 && minor > 1))
		{
			return true;
		}
	}
	return false;
}

back.addEventListener("click", function(e){
	win.container.setActiveTab(1);
});

km2.addEventListener("click", function(e){
	mapview.removeAllAnnotations();
	currentDistance = 2;
	currentRegion.latitudeDelta = currentRegion.longitudeDelta = FACTOR,
	drawRegion();
});

km5.addEventListener("click", function(e){
	mapview.removeAllAnnotations();
	currentDistance = 5;
	currentRegion.latitudeDelta = currentRegion.longitudeDelta = FACTOR * 5,
	drawRegion();
});

km10.addEventListener("click", function(e){
	mapview.removeAllAnnotations();
	currentDistance = 10;
	currentRegion.latitudeDelta = currentRegion.longitudeDelta = FACTOR * 10,
	drawRegion();
});

mapview.addEventListener("click", function(e){
	if(e.clicksource === 'rightButton') {
		alert("id:"+e.annotation.id);

		var style = Ti.UI.iPhone.MODAL_TRANSITION_STYLE_PARTIAL_CURL;
		var presentation = Ti.UI.iPhone.MODAL_PRESENTATION_FULLSCREEN;
		var w = Ti.UI.createWindow({
			url: "map/hotel_detail.js",
			currentPin: {map: mapview, annot: e.annotation}
		});

		w.open({
			modal:true,
			modalTransitionStyle:style,
			modalStyle:presentation,
			navBarHidden:true
		});
	}
});

win.add(mapview);
win.add(toolbar);
updateLocation();<|endoftext|>