<commit_before>(function () {
      "use strict";
    //Creating a global object for utilities and user selections
    window.agenda42 = {};
    agenda42.utils= { month : [{name:"Jan", dayNumber : 31},
        {name:"Feb", dayNumber : 28}, {name:"Mar", dayNumber : 31},
        {name:"Apr", dayNumber : 30}, {name:"May", dayNumber : 31},
        {name:"Jun", dayNumber : 30}, {name:"Jul", dayNumber : 31},
        {name:"Aug", dayNumber : 31}, {name:"Sep", dayNumber : 30},
        {name:"Oct", dayNumber : 31}, {name:"Nov", dayNumber : 30},
        {name:"Dec", dayNumber : 31}],
        hideExtraDayButtons : function() {
            var buttons = $( "#calendar").find("a");
            for(var i = 0; i <= 30  ; i++){
                if(i < agenda42.utils.month[agenda42.selections.date.getMonth()].dayNumber){
                    buttons.eq(i).css("display", "block");
                } else {
                    buttons.eq(i).css("display", "none");
                }
            }

        }
    };
    agenda42.webService = {
        baseURI : "http://10.33.33.4:8080/agenda/resources/agenda/",
        ownerID : "testJeremie"
    };

    //DOM is ready
    $(document).ready(function(){
        //Init selected values and month view
        agenda42.selections = {
            date : new Date()
        };
        //Display correct numbers of buttons and month name
        $( "#monthDisplay").text(agenda42.utils.month[agenda42.selections.date.getMonth()].name
            + " " +agenda42.selections.date.getFullYear());
        agenda42.utils.hideExtraDayButtons();

        //Init Calendar buttons
        var $myCalendarButtons = $( "#calendar" ).find( "a" );
        $myCalendarButtons.on("tap", function(){
            //Sets selected date
            agenda42.selections.date.setDate( $(this).text() );
            //Navigation
            $.mobile.changePage( "#day", { transition: "slide" });
        });

        //Fill day page
        $( "#day").on("pagebeforeshow",function(){

            //clears events display and selection
            $( "#dayResults").empty();
            agenda42.selections.selectedEvent = undefined;
            //Display correct date
            $( "#day" ).find( "div:first" ).find( "h1" ).html( agenda42.selections.date.toLocaleDateString());

            var date = agenda42.selections.date;
            $.mobile.loading( "show" );
            $.ajax({
                // the URL for the request
                url: agenda42.webService.baseURI + "events/" +
                    agenda42.webService.ownerID + "/" +date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(),

                // whether this is a POST or GET request
                type: "GET",

                //Enable CORS
                crossDomain : true,

                // the type of data we expect back
                dataType : "json",
                contentType: "application/json",

                // code to run if the request succeeds;
                // the response is passed to the function
                success: function( results ) {
                    var $results = $( "#dayResults" );

                    for (var i = 0; i < results.length; i++ ) {
                        var $newEventCollapsible = $( "
" +
                            "
"+results[i].name + "
" +
                            "
" + results[i].description + "
" +
                            "
 " );
                        $newEventCollapsible.bind('expand',function(){
                            agenda42.selections.selectedEvent = agenda42.selections.results[parseInt(this.id.substring(5))];
                        });

                        $results.append( $newEventCollapsible );
                    }
                    $results.collapsibleset( "refresh" );
                    agenda42.selections.results = results;
                },

                // code to run if the request fails; the raw request and
                // status codes are passed to the function
                error: function( xhr, status ) {
                    alert( "Server appears to be unreachable.\n Check your connection" );
                },

                // code to run regardless of success or failure
                complete: function( xhr, status ) {
                    $.mobile.loading( "hide" );
                }
            });
        });

        //Fill edit event page
        $( "#eventEdit").on("pagebeforeshow",function(){
            var selectedEvent = agenda42.selections.selectedEvent;
            // If no event has been selected in the first place => new event
            if(selectedEvent === undefined) {
                $( "#eventEditHeader").html( "New event" );
                //Reset the values to default
                $("#eventName").val("");
                var date = new Date();
                //date.setSeconds(0);
                $("#eventBeginDate").val(date.toJSON().slice(0,10));
                var $eventDuration = $("#eventDuration");
                $eventDuration.val(60);
                try{$eventDuration.slider("refresh")}catch(e){}
                $("#eventBeginTime").val(date.toLocaleTimeString.slice(0,5));
                var $eventAlarm = $("#eventAlarm");
                try{$eventAlarm.val('off');}catch (e){}
                $( "#eventDescription").val("");
                $( "#eventPlace").val("");
            }
            else{
                // Set the event data we're editing
                // Display correct header
                $( "#eventEditHeader").html( "Edit event" );
                //Parsing date(to ensure support across all browsers)
                var s = agenda42.selections.selectedEvent.beginDate;
                var a = s.split(/[^0-9]/);
                var date = new Date (a[0],a[1]-1,a[2],a[3],a[4],a[5]) || new Date();

                //Display event info
                $( "#eventName").val(selectedEvent.name);
                $( "#eventBeginDate").val(date.toJSON().slice(0,10));

                var $eventDuration = $("#eventDuration");
                $eventDuration.val(selectedEvent.duration);
                try{
                    $eventDuration.slider("refresh");
                }catch (e){}
                $( "#eventBeginTime").val(date.toLocaleTimeString().slice(0,5));

                var $eventAlarm = $("#eventAlarm");
                if(selectedEvent.alert){
                    $eventAlarm.val('on');
                }else{
                    $eventAlarm.val('off');
                }
                try{$eventAlarm.slider("refresh")}catch (e){}
                $( "#eventDescription").val(selectedEvent.description);
                $( "#eventPlace").val(selectedEvent.place);
            }
        });
        //Init new event action click
        $( "#newEventAction" ).on("tap", function(){
            //Removing previous event selection
            agenda42.selections.selectedEvent = undefined;
        });

        //Init the saveEvent click
        $( "#saveEvent").on("tap", function(){
            $.mobile.loading( "show" );
            //Build data to send
            var data = agenda42.selections.selectedEvent || {};
            data.name = $( "#eventName" ).val();
            data.duration = $( "#eventDuration" ).val();
            data.alert = $( "#eventAlarm" ).val()==="on";
            data.place = $( "#eventPlace" ).val();
            data.description = $( "#eventDescription" ).val();
            data.ownerID = agenda42.webService.ownerID;
            var date = new Date(
                $( "#eventBeginDate" ).val() + "T"
                + $( "#eventBeginTime" ).val()
            );
            data.beginDate = date.getFullYear()+"-"+(date.getMonth()+1) +"-"+date.getDate()+"-"
                + (date.getHours()+ date.getTimezoneOffset()/60) +"-"+date.getMinutes();
            $.ajax({
                // the URL for the request
                url: agenda42.webService.baseURI + ((agenda42.selections.selectedEvent === undefined)? "createEvent":"modifyEvent"),

                // whether this is a POST or GET request
                type: (agenda42.selections.selectedEvent ===undefined)? "POST":"PUT",
                data: JSON.stringify(data),

                //Enable CORS
                //crossDomain : true,

                // the type of data we expect back
                dataType : "json",
                contentType: "application/json",

                // code to run if the request succeeds;
                // the response is passed to the function
                success: function( results ) {
                },
                // code to run if the request fails; the raw request and
                // status codes are passed to the function
                error: function( xhr, status ) {
                    alert( "The server appears to be unreachable.\n Check your connection");
                },
                // code to run regardless of success or failure
                complete: function() {
                    $.mobile.loading( "hide" );
                    $.mobile.changePage( "#day", { transition: "slidedown" });
                    if($( "#eventAlarm" ).val()==="on"){
                        navigator.notification.alert(
                            'You wanted an alert',  // message
                            function(){},           // callback
                            'Agenda42 - Alert',     // title
                            'Done'                  // buttonName
                        );
                    };
                }
            });
        });

        //Init the deleteEvent click
        $( "#deleteEventAction").on("tap", function(){
            if(agenda42.selections.selectedEvent === undefined){
                // display info to user that he needs to select an event first
                alert("Please pick an event first");
            }
            else {
                $.mobile.loading( "show" );
                $.ajax({
                    // the URL for the request
                    url: agenda42.webService.baseURI + "deleteEvent",
                    //Type of request
                    type: "DELETE",
                    data: JSON.stringify(agenda42.selections.selectedEvent),
                    //Enable CORS
                    crossDomain : true,
                    // the type of data we expect back
                    contentType: "application/json",
                    // code to run if the request succeeds;
                    // the response is passed to the function
                    success: function( results ) {
                    },
                    // code to run if the request fails; the raw request and
                    // status codes are passed to the function
                    error: function( xhr, status ) {
                        alert( "The server appears to be unreachable.\n Check your connection");
                    },
                    // code to run regardless of success or failure
                    complete: function() {
                        $.mobile.loading( "hide" );
                        $.mobile.changePage( "#day", { transition: "slidedown" });
                    }
                });
            }
        });

        // Init next month button
        $( "#nextMonth").on("tap", function(){
            var date = agenda42.selections.date;
            date.setMonth(date.getMonth() + 1);
            $( "#monthDisplay").text(agenda42.utils.month[date.getMonth()].name + " " +date.getFullYear());
            //determines number of buttons and wether to show or hide buttons
            agenda42.utils.hideExtraDayButtons();
        });
        // Init prev month button
        $( "#prevMonth").on("tap", function(){
            var date = agenda42.selections.date;
            date.setMonth(date.getMonth() - 1);
            $( "#monthDisplay").text(agenda42.utils.month[date.getMonth()].name + " " +date.getFullYear());
            //determines number of buttons and wether to show or hide buttons
            agenda42.utils.hideExtraDayButtons();
        });
    });

 })();<commit_msg>eventBeginTime issue fixed<commit_after>(function () {
      "use strict";
    //Creating a global object for utilities and user selections
    window.agenda42 = {};
    agenda42.utils= { month : [{name:"Jan", dayNumber : 31},
        {name:"Feb", dayNumber : 28}, {name:"Mar", dayNumber : 31},
        {name:"Apr", dayNumber : 30}, {name:"May", dayNumber : 31},
        {name:"Jun", dayNumber : 30}, {name:"Jul", dayNumber : 31},
        {name:"Aug", dayNumber : 31}, {name:"Sep", dayNumber : 30},
        {name:"Oct", dayNumber : 31}, {name:"Nov", dayNumber : 30},
        {name:"Dec", dayNumber : 31}],
        hideExtraDayButtons : function() {
            var buttons = $( "#calendar").find("a");
            for(var i = 0; i <= 30  ; i++){
                if(i < agenda42.utils.month[agenda42.selections.date.getMonth()].dayNumber){
                    buttons.eq(i).css("display", "block");
                } else {
                    buttons.eq(i).css("display", "none");
                }
            }

        }
    };
    agenda42.webService = {
        baseURI : "http://10.33.33.4:8080/agenda/resources/agenda/",
        ownerID : "testJeremie"
    };

    //DOM is ready
    $(document).ready(function(){
        //Init selected values and month view
        agenda42.selections = {
            date : new Date()
        };
        //Display correct numbers of buttons and month name
        $( "#monthDisplay").text(agenda42.utils.month[agenda42.selections.date.getMonth()].name
            + " " +agenda42.selections.date.getFullYear());
        agenda42.utils.hideExtraDayButtons();

        //Init Calendar buttons
        var $myCalendarButtons = $( "#calendar" ).find( "a" );
        $myCalendarButtons.on("tap", function(){
            //Sets selected date
            agenda42.selections.date.setDate( $(this).text() );
            //Navigation
            $.mobile.changePage( "#day", { transition: "slide" });
        });

        //Fill day page
        $( "#day").on("pagebeforeshow",function(){

            //clears events display and selection
            $( "#dayResults").empty();
            agenda42.selections.selectedEvent = undefined;
            //Display correct date
            $( "#day" ).find( "div:first" ).find( "h1" ).html( agenda42.selections.date.toLocaleDateString());

            var date = agenda42.selections.date;
            $.mobile.loading( "show" );
            $.ajax({
                // the URL for the request
                url: agenda42.webService.baseURI + "events/" +
                    agenda42.webService.ownerID + "/" +date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(),

                // whether this is a POST or GET request
                type: "GET",

                //Enable CORS
                crossDomain : true,

                // the type of data we expect back
                dataType : "json",
                contentType: "application/json",

                // code to run if the request succeeds;
                // the response is passed to the function
                success: function( results ) {
                    var $results = $( "#dayResults" );

                    for (var i = 0; i < results.length; i++ ) {
                        var $newEventCollapsible = $( "
" +
                            "
"+results[i].name + "
" +
                            "
" + results[i].description + "
" +
                            "
 " );
                        $newEventCollapsible.bind('expand',function(){
                            agenda42.selections.selectedEvent = agenda42.selections.results[parseInt(this.id.substring(5))];
                        });

                        $results.append( $newEventCollapsible );
                    }
                    $results.collapsibleset( "refresh" );
                    agenda42.selections.results = results;
                },

                // code to run if the request fails; the raw request and
                // status codes are passed to the function
                error: function( xhr, status ) {
                    alert( "Server appears to be unreachable.\n Check your connection" );
                },

                // code to run regardless of success or failure
                complete: function( xhr, status ) {
                    $.mobile.loading( "hide" );
                }
            });
        });

        //Fill edit event page
        $( "#eventEdit").on("pagebeforeshow",function(){
            var selectedEvent = agenda42.selections.selectedEvent;
            // If no event has been selected in the first place => new event
            if(selectedEvent === undefined) {
                $( "#eventEditHeader").html( "New event" );
                //Reset the values to default
                $("#eventName").val("");
                var date = new Date();
                //date.setSeconds(0);
                $("#eventBeginDate").val(date.toJSON().slice(0,10));
                var $eventDuration = $("#eventDuration");
                $eventDuration.val(60);
                try{$eventDuration.slider("refresh")}catch(e){}
                $("#eventBeginTime").val(date.toLocaleTimeString().slice(0,5));
                var $eventAlarm = $("#eventAlarm");
                try{$eventAlarm.val('off');}catch (e){}
                $( "#eventDescription").val("");
                $( "#eventPlace").val("");
            }
            else{
                // Set the event data we're editing
                // Display correct header
                $( "#eventEditHeader").html( "Edit event" );
                //Parsing date(to ensure support across all browsers)
                var s = agenda42.selections.selectedEvent.beginDate;
                var a = s.split(/[^0-9]/);
                var date = new Date (a[0],a[1]-1,a[2],a[3],a[4],a[5]) || new Date();

                //Display event info
                $( "#eventName").val(selectedEvent.name);
                $( "#eventBeginDate").val(date.toJSON().slice(0,10));

                var $eventDuration = $("#eventDuration");
                $eventDuration.val(selectedEvent.duration);
                try{
                    $eventDuration.slider("refresh");
                }catch (e){}
                $( "#eventBeginTime").val(date.toLocaleTimeString().slice(0,5));

                var $eventAlarm = $("#eventAlarm");
                if(selectedEvent.alert){
                    $eventAlarm.val('on');
                }else{
                    $eventAlarm.val('off');
                }
                try{$eventAlarm.slider("refresh")}catch (e){}
                $( "#eventDescription").val(selectedEvent.description);
                $( "#eventPlace").val(selectedEvent.place);
            }
        });
        //Init new event action click
        $( "#newEventAction" ).on("tap", function(){
            //Removing previous event selection
            agenda42.selections.selectedEvent = undefined;
        });

        //Init the saveEvent click
        $( "#saveEvent").on("tap", function(){
            $.mobile.loading( "show" );
            //Build data to send
            var data = agenda42.selections.selectedEvent || {};
            data.name = $( "#eventName" ).val();
            data.duration = $( "#eventDuration" ).val();
            data.alert = $( "#eventAlarm" ).val()==="on";
            data.place = $( "#eventPlace" ).val();
            data.description = $( "#eventDescription" ).val();
            data.ownerID = agenda42.webService.ownerID;
            var date = new Date(
                $( "#eventBeginDate" ).val() + "T"
                + $( "#eventBeginTime" ).val()
            );
            data.beginDate = date.getFullYear()+"-"+(date.getMonth()+1) +"-"+date.getDate()+"-"
                + (date.getHours()+ date.getTimezoneOffset()/60) +"-"+date.getMinutes();
            $.ajax({
                // the URL for the request
                url: agenda42.webService.baseURI + ((agenda42.selections.selectedEvent === undefined)? "createEvent":"modifyEvent"),

                // whether this is a POST or GET request
                type: (agenda42.selections.selectedEvent ===undefined)? "POST":"PUT",
                data: JSON.stringify(data),

                //Enable CORS
                //crossDomain : true,

                // the type of data we expect back
                dataType : "json",
                contentType: "application/json",

                // code to run if the request succeeds;
                // the response is passed to the function
                success: function( results ) {
                },
                // code to run if the request fails; the raw request and
                // status codes are passed to the function
                error: function( xhr, status ) {
                    alert( "The server appears to be unreachable.\n Check your connection");
                },
                // code to run regardless of success or failure
                complete: function() {
                    $.mobile.loading( "hide" );
                    $.mobile.changePage( "#day", { transition: "slidedown" });
                    if($( "#eventAlarm" ).val()==="on"){
                        navigator.notification.alert(
                            'You wanted an alert',  // message
                            function(){},           // callback
                            'Agenda42 - Alert',     // title
                            'Done'                  // buttonName
                        );
                    };
                }
            });
        });

        //Init the deleteEvent click
        $( "#deleteEventAction").on("tap", function(){
            if(agenda42.selections.selectedEvent === undefined){
                // display info to user that he needs to select an event first
                alert("Please pick an event first");
            }
            else {
                $.mobile.loading( "show" );
                $.ajax({
                    // the URL for the request
                    url: agenda42.webService.baseURI + "deleteEvent",
                    //Type of request
                    type: "DELETE",
                    data: JSON.stringify(agenda42.selections.selectedEvent),
                    //Enable CORS
                    crossDomain : true,
                    // the type of data we expect back
                    contentType: "application/json",
                    // code to run if the request succeeds;
                    // the response is passed to the function
                    success: function( results ) {
                    },
                    // code to run if the request fails; the raw request and
                    // status codes are passed to the function
                    error: function( xhr, status ) {
                        alert( "The server appears to be unreachable.\n Check your connection");
                    },
                    // code to run regardless of success or failure
                    complete: function() {
                        $.mobile.loading( "hide" );
                        $.mobile.changePage( "#day", { transition: "slidedown" });
                    }
                });
            }
        });

        // Init next month button
        $( "#nextMonth").on("tap", function(){
            var date = agenda42.selections.date;
            date.setMonth(date.getMonth() + 1);
            $( "#monthDisplay").text(agenda42.utils.month[date.getMonth()].name + " " +date.getFullYear());
            //determines number of buttons and wether to show or hide buttons
            agenda42.utils.hideExtraDayButtons();
        });
        // Init prev month button
        $( "#prevMonth").on("tap", function(){
            var date = agenda42.selections.date;
            date.setMonth(date.getMonth() - 1);
            $( "#monthDisplay").text(agenda42.utils.month[date.getMonth()].name + " " +date.getFullYear());
            //determines number of buttons and wether to show or hide buttons
            agenda42.utils.hideExtraDayButtons();
        });
    });

 })();<|endoftext|>


<commit_before>$( document ).ready(function() {
	//on page load, graph by time is showing
	getData(crimesByTime);

	$('.js-show-day').click(function(){
		$('.js-show-time').removeClass('is-active');
		$(this).addClass('is-active');
		getData(crimesByWeekday);
	});

	$('.js-show-time').click(function(){
		$('.js-show-day').removeClass('is-active');
		$(this).addClass('is-active');
		getData(crimesByTime);
	});

});

var getData = function(graphType){
	$('#loader').removeClass('is-hidden');
	$('#chartdiv').addClass('is-hidden');
	$.ajax({
		type: "GET",
		cache: false,
		url: "https://data.seattle.gov/resource/3k2p-39jp.json?$where=within_circle(incident_location, 47.595146, -122.331601, 1609.34)",
		})
	.done(function(data){
		$('#loader').addClass('is-hidden');
		$('#chartdiv').removeClass('is-hidden');
		//send data from api to either the weekday or time bar graphs
		graphType(data);
	});
}

var crimesByWeekday = function(data){
	var dayOfWeek = {
		'Mon': 0,
		'Tue': 0,
		'Wed': 0,
		'Thu': 0,
		'Fri': 0,
		'Sat': 0,
		'Sun': 0,
	};
	for(var i=0; i<data.length; i++){
		var thisDate = (data[i].event_clearance_date);
		//separate date from date and time
		var thisDay = thisDate.substring(0, 10);
		//get day of week name from date
		var dayName = String(Date.parse(thisDay)).substring(0, 3);

		dayOfWeek[dayName]++;
	}

	getValues(dayOfWeek, 'day');

	//AMChart for day of week
	var chart = AmCharts.makeChart("chartdiv", {
	  "type": "serial",
		"theme": "dark",
	    "dataProvider": [
	{
	        "day": "Monday",
	        "crime": dayOfWeek['Mon']
	    },
	{
	        "day": "Tuesday",
	        "crime": dayOfWeek['Tue']
	    }, {
	        "day": "Wednesday",
	        "crime": dayOfWeek['Wed']
	    }, {
	        "day": "Thursday",
	        "crime": dayOfWeek['Thu']
	    }, {
	        "day": "Friday",
	        "crime": dayOfWeek['Fri']
	    }, {
	        "day": "Saturday",
	        "crime": dayOfWeek['Sat']
	    }, {
	        "day": "Sunday",
	        "crime": dayOfWeek['Sun']
	    }],
	    "valueAxes": [{
      "gridColor":"#FFFFFF",
			"gridAlpha": 0.2,
			"dashLength": 0
	    }],
	    "gridAboveGraphs": true,
	    "startDuration": 1,
	    "graphs": [{
	        "balloonText": "[[category]]: [[value]]",
	        "fillAlphas": 0.8,
	        "lineAlpha": 0.2,
	        "type": "column",
	        "valueField": "crime"
	    }],
	    "chartCursor": {
	        "categoryBalloonEnabled": false,
	        "cursorAlpha": 0,
	        "zoomable": false
	    },
	    "categoryField": "day",
	    "categoryAxis": {
	        "gridPosition": "start",
	        "gridAlpha": 0,
	         "tickPosition":"start",
	         "tickLength":20
	    },
		"exportConfig":{
		  "menuTop": 0,
		  "menuItems": [{
	      "icon": '/lib/3/images/export.png',
	      "format": 'png'
	      }]
		}
	});
}

var crimesByTime = function(data){
	var timeOfDay = {
		'00': 0,
		'01': 0,
		'02': 0,
		'03': 0,
		'04': 0,
		'05': 0,
		'06': 0,
		'07': 0,
		'08': 0,
		'09': 0,
		'10': 0,
		'11': 0,
		'12': 0,
		'13': 0,
		'14': 0,
		'15': 0,
		'16': 0,
		'17': 0,
		'18': 0,
		'19': 0,
		'20': 0,
		'21': 0,
		'22': 0,
		'23': 0
	};
	for(var i=0; i<data.length; i++){
		var thisDate = (data[i].event_clearance_date);
		//separate time from date and time
		var thisTime = thisDate.substring(11, 13);

		timeOfDay[thisTime]++;

	}

	getValues(timeOfDay, 'time');

	//AMChart for time
	var chart = AmCharts.makeChart("chartdiv", {
	  "type": "serial",
		"theme": "dark",
	    "dataProvider": [
	{
	        "time": "12am",
	        "crime": timeOfDay['00']
	    },
	{
	        "time": "1am",
	        "crime": timeOfDay['01']
	    }, {
	        "time": "2am",
	        "crime": timeOfDay['02']
	    }, {
	        "time": "3am",
	        "crime": timeOfDay['03']
	    }, {
	        "time": "4am",
	        "crime": timeOfDay['04']
	    }, {
	        "time": "5am",
	        "crime": timeOfDay['05']
	    }, {
	        "time": "6am",
	        "crime": timeOfDay['06']
	    }, {
	        "time": "7am",
	        "crime": timeOfDay['07']
	    }, {
	        "time": "8am",
	        "crime": timeOfDay['08']
	    },
	    {
	        "time": "9am",
	        "crime": timeOfDay['09']
	    },
	    {
	        "time": "10am",
	        "crime": timeOfDay['10']
	    },
	    {
	        "time": "11am",
	        "crime": timeOfDay['11']
	    },
	    {
	        "time": "12pm",
	        "crime": timeOfDay['12']
	    },
	    {
	        "time": "1pm",
	        "crime": timeOfDay['13']
	    },
	    {
	        "time": "2pm",
	        "crime": timeOfDay['14']
	    },
	    {
	        "time": "3pm",
	        "crime": timeOfDay['15']
	    },
	    {
	        "time": "4pm",
	        "crime": timeOfDay['16']
	    },
	    {
	        "time": "5pm",
	        "crime": timeOfDay['17']
	    },
	    {
	        "time": "6pm",
	        "crime": timeOfDay['18']
	    },
	    {
	        "time": "7pm",
	        "crime": timeOfDay['19']
	    },
	    {
	        "time": "8pm",
	        "crime": timeOfDay['20']
	    },
	    {
	        "time": "9pm",
	        "crime": timeOfDay['21']
	    },
	    {
	        "time": "10pm",
	        "crime": timeOfDay['22']
	    },
	    {
	        "time": "11pm",
	        "crime": timeOfDay['23']
	    }],
	    "valueAxes": [{
      "gridColor":"#FFFFFF",
			"gridAlpha": 0.2,
			"dashLength": 0
	    }],
	    "gridAboveGraphs": true,
	    "startDuration": 1,
	    "graphs": [{
	        "balloonText": "[[category]]: [[value]]",
	        "fillAlphas": 0.8,
	        "lineAlpha": 0.2,
	        "type": "column",
	        "valueField": "crime"
	    }],
	    "chartCursor": {
	        "categoryBalloonEnabled": false,
	        "cursorAlpha": 0,
	        "zoomable": false
	    },
	    "categoryField": "time",
	    "categoryAxis": {
	        "gridPosition": "start",
	        "gridAlpha": 0,
	         "tickPosition":"start",
	         "tickLength":20
	    },
		"exportConfig":{
		  "menuTop": 0,
		  "menuItems": [{
	      "icon": '/lib/3/images/export.png',
	      "format": 'png'
	      }]
		}
	});
}

var getValues = function(thisObj, objType){
	var max = 0;
	var min = 100;
	for (var prop in thisObj) {
		if(thisObj[prop] > max){
			var max = thisObj[prop];
			var maxProp = prop;
		}
	}
	for (var prop in thisObj) {
		if(thisObj[prop] < min){
			var min = thisObj[prop];
			var minProp = prop;
		}
	}
	if(objType === 'time'){
		var valueMost = convertTime(maxProp);
		var valueMin = convertTime(minProp);
	} else {
		var valueMost = maxProp;
		var valueMin = minProp;
	}

	//replace spans in second div with relevant information
	$('.js-type').text(objType);
	$('.js-d-most').text(valueMost);
	$('.js-d-least').text(valueMin);

}

var convertTime = function(tProperty){
	if(tProperty === 0){
		return "12am";
	} else if(tProperty > 12){
		return tProperty - 12 + "pm";
	}else{
		return tProperty + "am";
	}
}<commit_msg>naming change<commit_after>$( document ).ready(function() {
	//on page load, graph by time is showing
	getData(crimesByTime);

	$('.js-show-day').click(function(){
		$('.js-show-time').removeClass('is-active');
		$(this).addClass('is-active');
		getData(crimesByWeekday);
	});

	$('.js-show-time').click(function(){
		$('.js-show-day').removeClass('is-active');
		$(this).addClass('is-active');
		getData(crimesByTime);
	});

});

var getData = function(graphType){
	$('#loader').removeClass('is-hidden');
	$('#chartdiv').addClass('is-hidden');
	$.ajax({
		type: "GET",
		url: "https://data.seattle.gov/resource/3k2p-39jp.json?$where=within_circle(incident_location, 47.595146, -122.331601, 1609.34)",
		})
	.done(function(data){
		$('#loader').addClass('is-hidden');
		$('#chartdiv').removeClass('is-hidden');
		//send data from api to either the weekday or time bar graphs
		graphType(data);
	});
}

var crimesByWeekday = function(data){
	var dayOfWeek = {
		'Mon': 0,
		'Tue': 0,
		'Wed': 0,
		'Thu': 0,
		'Fri': 0,
		'Sat': 0,
		'Sun': 0,
	};
	for(var i=0; i<data.length; i++){
		var thisDate = (data[i].event_clearance_date);
		//separate date from date and time
		var thisDay = thisDate.substring(0, 10);
		//get day of week name from date
		var dayName = String(Date.parse(thisDay)).substring(0, 3);

		dayOfWeek[dayName]++;
	}

	getValues(dayOfWeek, 'day');

	//AMChart for day of week
	var chart = AmCharts.makeChart("chartdiv", {
	  "type": "serial",
		"theme": "dark",
	    "dataProvider": [
	{
	        "day": "Monday",
	        "crime": dayOfWeek['Mon']
	    },
	{
	        "day": "Tuesday",
	        "crime": dayOfWeek['Tue']
	    }, {
	        "day": "Wednesday",
	        "crime": dayOfWeek['Wed']
	    }, {
	        "day": "Thursday",
	        "crime": dayOfWeek['Thu']
	    }, {
	        "day": "Friday",
	        "crime": dayOfWeek['Fri']
	    }, {
	        "day": "Saturday",
	        "crime": dayOfWeek['Sat']
	    }, {
	        "day": "Sunday",
	        "crime": dayOfWeek['Sun']
	    }],
	    "valueAxes": [{
      "gridColor":"#FFFFFF",
			"gridAlpha": 0.2,
			"dashLength": 0
	    }],
	    "gridAboveGraphs": true,
	    "startDuration": 1,
	    "graphs": [{
	        "balloonText": "[[category]]: [[value]]",
	        "fillAlphas": 0.8,
	        "lineAlpha": 0.2,
	        "type": "column",
	        "valueField": "crime"
	    }],
	    "chartCursor": {
	        "categoryBalloonEnabled": false,
	        "cursorAlpha": 0,
	        "zoomable": false
	    },
	    "categoryField": "day",
	    "categoryAxis": {
	        "gridPosition": "start",
	        "gridAlpha": 0,
	         "tickPosition":"start",
	         "tickLength":20
	    },
		"exportConfig":{
		  "menuTop": 0,
		  "menuItems": [{
	      "icon": '/lib/3/images/export.png',
	      "format": 'png'
	      }]
		}
	});
}

var crimesByTime = function(data){
	var timeOfDay = {
		'00': 0,
		'01': 0,
		'02': 0,
		'03': 0,
		'04': 0,
		'05': 0,
		'06': 0,
		'07': 0,
		'08': 0,
		'09': 0,
		'10': 0,
		'11': 0,
		'12': 0,
		'13': 0,
		'14': 0,
		'15': 0,
		'16': 0,
		'17': 0,
		'18': 0,
		'19': 0,
		'20': 0,
		'21': 0,
		'22': 0,
		'23': 0
	};
	for(var i=0; i<data.length; i++){
		var thisDate = (data[i].event_clearance_date);
		//separate time from date and time
		var thisTime = thisDate.substring(11, 13);

		timeOfDay[thisTime]++;

	}

	getValues(timeOfDay, 'time');

	//AMChart for time
	var chart = AmCharts.makeChart("chartdiv", {
	  "type": "serial",
		"theme": "dark",
	    "dataProvider": [
	{
	        "time": "12am",
	        "crime": timeOfDay['00']
	    },
	{
	        "time": "1am",
	        "crime": timeOfDay['01']
	    }, {
	        "time": "2am",
	        "crime": timeOfDay['02']
	    }, {
	        "time": "3am",
	        "crime": timeOfDay['03']
	    }, {
	        "time": "4am",
	        "crime": timeOfDay['04']
	    }, {
	        "time": "5am",
	        "crime": timeOfDay['05']
	    }, {
	        "time": "6am",
	        "crime": timeOfDay['06']
	    }, {
	        "time": "7am",
	        "crime": timeOfDay['07']
	    }, {
	        "time": "8am",
	        "crime": timeOfDay['08']
	    },
	    {
	        "time": "9am",
	        "crime": timeOfDay['09']
	    },
	    {
	        "time": "10am",
	        "crime": timeOfDay['10']
	    },
	    {
	        "time": "11am",
	        "crime": timeOfDay['11']
	    },
	    {
	        "time": "12pm",
	        "crime": timeOfDay['12']
	    },
	    {
	        "time": "1pm",
	        "crime": timeOfDay['13']
	    },
	    {
	        "time": "2pm",
	        "crime": timeOfDay['14']
	    },
	    {
	        "time": "3pm",
	        "crime": timeOfDay['15']
	    },
	    {
	        "time": "4pm",
	        "crime": timeOfDay['16']
	    },
	    {
	        "time": "5pm",
	        "crime": timeOfDay['17']
	    },
	    {
	        "time": "6pm",
	        "crime": timeOfDay['18']
	    },
	    {
	        "time": "7pm",
	        "crime": timeOfDay['19']
	    },
	    {
	        "time": "8pm",
	        "crime": timeOfDay['20']
	    },
	    {
	        "time": "9pm",
	        "crime": timeOfDay['21']
	    },
	    {
	        "time": "10pm",
	        "crime": timeOfDay['22']
	    },
	    {
	        "time": "11pm",
	        "crime": timeOfDay['23']
	    }],
	    "valueAxes": [{
      "gridColor":"#FFFFFF",
			"gridAlpha": 0.2,
			"dashLength": 0
	    }],
	    "gridAboveGraphs": true,
	    "startDuration": 1,
	    "graphs": [{
	        "balloonText": "[[category]]: [[value]]",
	        "fillAlphas": 0.8,
	        "lineAlpha": 0.2,
	        "type": "column",
	        "valueField": "crime"
	    }],
	    "chartCursor": {
	        "categoryBalloonEnabled": false,
	        "cursorAlpha": 0,
	        "zoomable": false
	    },
	    "categoryField": "time",
	    "categoryAxis": {
	        "gridPosition": "start",
	        "gridAlpha": 0,
	         "tickPosition":"start",
	         "tickLength":20
	    },
		"exportConfig":{
		  "menuTop": 0,
		  "menuItems": [{
	      "icon": '/lib/3/images/export.png',
	      "format": 'png'
	      }]
		}
	});
}

var getValues = function(thisObj, objType){
	var max = 0;
	var min = 100;
	for (var prop in thisObj) {
		if(thisObj[prop] > max){
			var max = thisObj[prop];
			var maxProp = prop;
		}
	}
	for (var prop in thisObj) {
		if(thisObj[prop] < min){
			var min = thisObj[prop];
			var minProp = prop;
		}
	}
	if(objType === 'time'){
		var valueMost = convertTime(maxProp);
		var valueMin = convertTime(minProp);
	} else {
		var valueMost = maxProp;
		var valueMin = minProp;
	}

	//replace spans in second div with relevant information
	$('.js-type').text(objType);
	$('.js-d-most').text(valueMost);
	$('.js-d-least').text(valueMin);

}

var convertTime = function(tProperty){
	if(tProperty === 0){
		return "12am";
	} else if(tProperty > 12){
		return tProperty - 12 + "pm";
	}else{
		return tProperty + "am";
	}
}<|endoftext|>


<commit_before>var conn;

$(function() {
  renderButton();
  loadWebSockets();

  $('.search-form').submit(function(e) {
    e.preventDefault();
    reloadResults();
  });

  $('body').on('click', '.update', function(e) {
    e.preventDefault();

    var form = $(this).find('form');
    var icon = $(this).find('.fa');
    $.post(form.attr('action'), form.serialize(), function(data) {
      if (data.Error) {
        alert(data.Message);
      } else {
        icon.toggleClass('fa-check');
        icon.toggleClass('fa-plus');
        $('.queue').load('/rooms/' + room + '/queue');
        reloadResults();
      }
    });
  });
});

function reloadResults() {
  var form = $('.search-form');
  if (form.find('input[name="search"]').val() !== '') {
    var res = $('.results');
    res.load(form.attr('action'), form.serialize());
  }
}

function loadWebSockets() {
  if (window["WebSocket"] && typeof(room) !== 'undefined' && room != '') {
    conn = new WebSocket("ws://" + host + "/rooms/" + room + "/ws");
    conn.onclose = function(evt) {
      // Something
    }
    conn.onmessage = function(evt) {
      if (evt.data === "pop") {
        $('.queue').load('/rooms/' + room + '/queue');
        reloadResults();
        return;
      }

      if (evt.data === "playing") {
        $('.now-playing').load('/rooms/' + room + '/now');
        return;
      }
    }
  } else {
    // You ain't got WebSockets, brah
  }
}

function onSignIn(googleUser) {
  var idToken = googleUser.getAuthResponse().id_token;
  verifyToken(idToken);
}

function verifyToken(token, first, last) {
  $.ajax({
    url: '/verifyToken',
    type: 'post',
    data: {
      token: token,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function(data) {
       console.log(data);
    }
  })
}

function renderButton() {
  gapi.signin2.render('g-signin', {
    'scope': 'profile email',
    'width': 240,
    'height': 50,
    'theme': 'dark',
    'onsuccess': onSignIn
    //'onfailure': onFailure
  });
}
<commit_msg>Scroll to the end when you add a new song<commit_after>var conn;

$(function() {
  renderButton();
  loadWebSockets();

  $('.search-form').submit(function(e) {
    e.preventDefault();
    reloadResults();
  });

  $('body').on('click', '.update', function(e) {
    e.preventDefault();

    var form = $(this).find('form');
    var icon = $(this).find('.fa');
    $.post(form.attr('action'), form.serialize(), function(data) {
      if (data.Error) {
        alert(data.Message);
      } else {
        icon.toggleClass('fa-check');
        icon.toggleClass('fa-plus');
        reloadQueue(true);
        reloadResults();
      }
    });
  });
});

function reloadResults() {
  var form = $('.search-form');
  if (form.find('input[name="search"]').val() !== '') {
    var res = $('.results');
    res.load(form.attr('action'), form.serialize());
  }
}

function reloadQueue(scroll) {
  $('.queue').load('/rooms/' + room + '/queue', function() {
    if (scroll) {
      var q = $('.queue').get(0);
      q.scrollLeft = q.scrollWidth;
    }
  });
}

function loadWebSockets() {
  if (window["WebSocket"] && typeof(room) !== 'undefined' && room != '') {
    conn = new WebSocket("ws://" + host + "/rooms/" + room + "/ws");
    conn.onclose = function(evt) {
      // Something
    }
    conn.onmessage = function(evt) {
      if (evt.data === "pop") {
        reloadQueue(false);
        reloadResults();
        return;
      }

      if (evt.data === "playing") {
        $('.now-playing').load('/rooms/' + room + '/now');
        return;
      }
    }
  } else {
    // You ain't got WebSockets, brah
  }
}

function onSignIn(googleUser) {
  var idToken = googleUser.getAuthResponse().id_token;
  verifyToken(idToken);
}

function verifyToken(token, first, last) {
  $.ajax({
    url: '/verifyToken',
    type: 'post',
    data: {
      token: token,
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function(data) {
       console.log(data);
    }
  })
}

function renderButton() {
  gapi.signin2.render('g-signin', {
    'scope': 'profile email',
    'width': 240,
    'height': 50,
    'theme': 'dark',
    'onsuccess': onSignIn
    //'onfailure': onFailure
  });
}
<|endoftext|>


<commit_before>$('#compute').on('click', function(e){
  compute(
    $('#sourceInput').text(),
    function(codes){
      $('#sourceOutput').text(codes.source);
      $('#ASTOutput').text(codes.AST);
      $('#errorOutput').text(codes.errors);
    }
  ); //TODO: Can we pipe this at some point?
});

var outputPanes = $('#sourceOutput, #ASTOutput, #errorOutput');
var paneButtons = $('BUTTON#sourcePane, BUTTON#ASTPane, BUTTON#errorPane')
paneButtons.on('click', function(e){
  outputPanes.hide();
  $('#' + $(e.target).attr('data-pane')).show();
});

function compute(oldSource, callback){
  var tolerant = [];

  var AST = esprima.parse(oldSource, {tolerant:tolerant});
  AST = getGoofy(AST);

  var newSource = escodegen.generate(AST);
  callback({
    source:newSource,
    AST:JSON.stringify(AST,null, 4),
    errors:JSON.stringify(tolerant,null, 4)
  });
}

function getGoofy(AST){

  for (var i = 0; i < AST.body.length; i++){
    var body = AST.body[i];
    if (body.type === 'FunctionDeclaration'){
      body.id.name = getWord('V');
    }
  }

  return AST;
}

function getWord(partOfSpeech){
  //start at random spot in array then wrap around looking
  var r = Math.floor(Math.random() * __words.length);
  var i = r;
  while (i++){
    var word = __words[i];
    if (word[1] == partOfSpeech){
      return word[0];
    }

    if (i >= __words.length){
      i = 0;
    }
    else {
      if (i == (r - 1)){
        return 'nothing'; //End of wrap around loop
      }
    }
  }
}
<commit_msg>Start recursively checking bodies. Cheap variable declaration name change.<commit_after>$('#compute').on('click', function(e){
  compute(
    $('#sourceInput').text(),
    function(codes){
      $('#sourceOutput').text(codes.source);
      $('#ASTOutput').text(codes.AST);
      $('#errorOutput').text(codes.errors);
    }
  ); //TODO: Can we pipe this at some point?
});

var outputPanes = $('#sourceOutput, #ASTOutput, #errorOutput');
var paneButtons = $('BUTTON#sourcePane, BUTTON#ASTPane, BUTTON#errorPane')
paneButtons.on('click', function(e){
  outputPanes.hide();
  $('#' + $(e.target).attr('data-pane')).show();
});

function compute(oldSource, callback){
  var tolerant = [];

  var AST = esprima.parse(oldSource, {tolerant:tolerant});
  AST = getGoofy(AST);

  var newSource = escodegen.generate(AST);
  callback({
    source:newSource,
    AST:JSON.stringify(AST,null, 4),
    errors:JSON.stringify(tolerant,null, 4)
  });
}

function getGoofy(AST){

  for (var i = 0; i < AST.body.length; i++){
    var body = AST.body[i];
    goofBody(body);
  }

  return AST;
}

function goofBody(body){
  if (Array.isArray(body)){
    for(var i = 0; i < body.length; i++){
      return goofBody(body[i]);
    }
  }

  if (body.type === 'BlockStatement'){
    return goofBody(body.body);
  }

  if (body.type === 'FunctionDeclaration'){
    body.id.name = getWord('V');
    return goofBody(body.body);
  }

  if (body.type === 'VariableDeclaration'){
    for (var i = 0; i < body.declarations.length; i++){
      body.declarations[i].id.name = getWord('N');
    }

    return body;
  }
}

function getWord(partOfSpeech){
  //start at random spot in array then wrap around looking
  var r = Math.floor(Math.random() * __words.length);
  var i = r;
  while (i++){
    var word = __words[i];
    if (word[1] == partOfSpeech){
      return word[0];
    }

    if (i >= __words.length){
      i = 0;
    }
    else {
      if (i == (r - 1)){
        return 'nothing'; //End of wrap around loop
      }
    }
  }
}
<|endoftext|>


<commit_before>var input = document.getElementById("input");
var button = document.getElementById("button");
var todo = document.getElementById("todo");
var completed = document.getElementById("completed");

input.addEventListener("keyup", function (e) {
    if (e.keyCode === 13) button.click();
});

button.addEventListener("click", function () {
    if (input.value.trim()) {
        var inputValueWrapper = document.createElement("span");
        var inputValue = document.createTextNode(input.value.trim());
        var todoItem = document.createElement("li");
        var todoButtons = document.createElement("div");
        var editButton = document.createElement("button");
        var pencilIcon = document.createElement("i");
        var deleteButton = document.createElement("button");
        var trashIcon = document.createElement("i");
        var doneButton = document.createElement("button");
        var checkIcon = document.createElement("i");

        todoItem.classList.add("todo-item");
        todoButtons.classList.add("todo-buttons");
        editButton.classList.add("button", "button--edit");
        pencilIcon.classList.add("fa", "fa-pencil");
        deleteButton.classList.add("button", "button--delete");
        trashIcon.classList.add("fa", "fa-trash");
        doneButton.classList.add("button", "button--done");
        checkIcon.classList.add("fa", "fa-check");

        editButton.appendChild(pencilIcon);
        deleteButton.appendChild(trashIcon);
        doneButton.appendChild(checkIcon);
        todoButtons.appendChild(editButton);
        todoButtons.appendChild(deleteButton);
        todoButtons.appendChild(doneButton);
        inputValueWrapper.appendChild(inputValue);
        todoItem.appendChild(inputValueWrapper);
        todoItem.appendChild(todoButtons);
        todo.prepend(todoItem);

        input.value = "";

        editButton.addEventListener("click", function () {
            var item = this.parentNode.parentNode;
            var todoEditWrapper = document.createElement("div");
            var todoEdit = document.createElement("input");
            var todoEditUpdateButton = document.createElement("button");
            var todoEditPlusIcon = document.createElement("i");
            todoEditWrapper.classList.add("todo-editWrapper");
            todoEditUpdateButton.classList.add("button", "button--update");
            todoEditPlusIcon.classList.add("fa", "fa-plus");
            todoEdit.type = "text";
            todoEdit.classList.add("todo-edit");
            todoEdit.value = item.childNodes[0].textContent;
            todoEditUpdateButton.appendChild(todoEditPlusIcon);
            todoEditWrapper.appendChild(todoEdit);
            todoEditWrapper.appendChild(todoEditUpdateButton);
            inputValueWrapper.style.display = "none";
            item.prepend(todoEditWrapper);
            todoEdit.focus();
            todoButtons.removeChild(editButton);
            item.style.paddingRight = "95px";

            function todoEditDone() {
                if (todoEdit.value.trim()) {
                    inputValueWrapper.textContent = todoEdit.value.trim();
                    inputValueWrapper.removeAttribute("style");
                    item.removeChild(todoEditWrapper);
                    todoButtons.prepend(editButton);
                    item.style.paddingRight = "135px";
                }
            }
            todoEditUpdateButton.addEventListener("click", todoEditDone);
            todoEdit.addEventListener("keyup", function (e) {
                if (e.keyCode === 13) {
                    todoEditDone();
                }
            });
        });

        deleteButton.addEventListener("click", function () {
            var item = this.parentNode.parentNode;
            var parent = item.parentNode;
            parent.removeChild(item);
        });

        doneButton.addEventListener("click", function () {
            var parentId = this.parentNode.parentNode.parentNode.id;
            parentId === "todo" ? completed.prepend(todoItem) : todo.appendChild(todoItem);
        });
    }
});<commit_msg>es5 -> es6<commit_after>const input = document.getElementById("input");
const button = document.getElementById("button");
const todo = document.getElementById("todo");
const completed = document.getElementById("completed");

input.addEventListener("keyup", e => {
    if (e.keyCode === 13) button.click();
});

button.addEventListener("click", () => {
    if (input.value.trim()) {
        const inputValueWrapper = document.createElement("span");
        const inputValue = document.createTextNode(input.value.trim());
        const todoItem = document.createElement("li");
        const todoButtons = document.createElement("div");
        const editButton = document.createElement("button");
        const pencilIcon = document.createElement("i");
        const deleteButton = document.createElement("button");
        const trashIcon = document.createElement("i");
        const doneButton = document.createElement("button");
        const checkIcon = document.createElement("i");

        todoItem.classList.add("todo-item");
        todoButtons.classList.add("todo-buttons");
        editButton.classList.add("button", "button--edit");
        pencilIcon.classList.add("fa", "fa-pencil");
        deleteButton.classList.add("button", "button--delete");
        trashIcon.classList.add("fa", "fa-trash");
        doneButton.classList.add("button", "button--done");
        checkIcon.classList.add("fa", "fa-check");

        editButton.appendChild(pencilIcon);
        deleteButton.appendChild(trashIcon);
        doneButton.appendChild(checkIcon);
        todoButtons.appendChild(editButton);
        todoButtons.appendChild(deleteButton);
        todoButtons.appendChild(doneButton);
        inputValueWrapper.appendChild(inputValue);
        todoItem.appendChild(inputValueWrapper);
        todoItem.appendChild(todoButtons);
        todo.prepend(todoItem);

        input.value = "";

        editButton.addEventListener("click", function () {
            const item = this.parentNode.parentNode;
            const todoEditWrapper = document.createElement("div");
            const todoEdit = document.createElement("input");
            const todoEditUpdateButton = document.createElement("button");
            const todoEditPlusIcon = document.createElement("i");
            todoEditWrapper.classList.add("todo-editWrapper");
            todoEditUpdateButton.classList.add("button", "button--update");
            todoEditPlusIcon.classList.add("fa", "fa-plus");
            todoEdit.type = "text";
            todoEdit.classList.add("todo-edit");
            todoEdit.value = item.childNodes[0].textContent;
            todoEditUpdateButton.appendChild(todoEditPlusIcon);
            todoEditWrapper.appendChild(todoEdit);
            todoEditWrapper.appendChild(todoEditUpdateButton);
            inputValueWrapper.style.display = "none";
            item.prepend(todoEditWrapper);
            todoEdit.focus();
            todoButtons.removeChild(editButton);
            item.style.paddingRight = "95px";

            const todoEditDone = () => {
                if (todoEdit.value.trim()) {
                    inputValueWrapper.textContent = todoEdit.value.trim();
                    inputValueWrapper.removeAttribute("style");
                    item.removeChild(todoEditWrapper);
                    todoButtons.prepend(editButton);
                    item.style.paddingRight = "135px";
                }
            }
            todoEditUpdateButton.addEventListener("click", todoEditDone);
            todoEdit.addEventListener("keyup", (e) => {
                if (e.keyCode === 13)
                    todoEditDone();
            });
        });

        deleteButton.addEventListener("click", function () {
            const item = this.parentNode.parentNode;
            const parent = item.parentNode;
            parent.removeChild(item);
        });

        doneButton.addEventListener("click", function () {
            const parentId = this.parentNode.parentNode.parentNode.id;
            parentId === "todo" ? completed.prepend(todoItem) : todo.appendChild(todoItem);
        });
    }
});<|endoftext|>


<commit_before>var $ = function(selector) { return document.querySelectorAll(selector); };
var fst = function(list) { return list[0]; }
var canvas = fst($("canvas"));
var draw = canvas.getContext("2d");
var ta = fst($("textarea"));
var out = fst($("code"));
var writer = format(out);
var events = {
  Öshift13:run, // shift + enter
  Ö9:indentSelection, // tab
  Öshift9:function(text, bounds){ indentSelection(text, bounds, true); }, // shift + tab
  Öselection9:indentSelection, // select text + tab
  Öshiftselection9:function(text, bounds){ indentSelection(text, bounds, true); }, // shift + select text + tab
  Öshift8:out.clear // shift + backspace KLUDGE: format(out) has to be called before this
};
var config = {
  indentation: 2
}

window.addEventListener("error", log);

polyfills();

//a.addEventListener("mouseup", inputWatch(ta)); // mouse selection
ta.addEventListener("keydown", inputWatch(ta)); // detect tab
//ta.addEventListener("keypress", inputWatch(ta)); // detect tab

function KeyEvent(shift, ctrl, alt, selection, charcode, value, extras) {
  this.shift = shift;
  this.ctrl = ctrl;
  this.alt = alt;
  this.selection = selection;
  this.charCode = charcode;
  this.value = value;
  this.extras = extras;
}
KeyEvent.prototype.toString = function() {
  var self = this;
  return "Ö" + Object.keys(this).map(function(key) {
    var not = ["toString", "value", "extras"];
    var ret = (self[key] === true && key) || self[key];
    return !~not.indexOf(key) && ret || "";
  }).join("");
}

function inputWatch(field) {
  var notifyId;
  var inputs = [];
  return function(e) {
    e = e || window.event;
    var charCode = (e.which instanceof Number) ? e.which : e.keyCode;
    var value = field.value, isSelection = false, extras, ke;
    if(field.selectionStart < field.selectionEnd) {
      isSelection = true;
    }
    extras = [field.selectionStart, field.selectionEnd];
    ke = new KeyEvent(e.shiftKey, e.ctrlKey, e.altKey, isSelection, charCode, value, extras);
// log(ke.toString());
    inputs.push(ke);
    if(events[ke.toString()])
      e.preventDefault();
    if(notifyId)
      window.clearTimeout(notifyId);
    notifyId = window.setTimeout(runFunction, 60, inputs); // let me type :)
  }
}

function runFunction(inputs) {
  var shortcutFunction;
  inputs.forEach(function(keyevent) {
    shortcutFunction = events[ keyevent.toString() ];
    shortcutFunction && window.setTimeout(shortcutFunction, 0, keyevent.value, keyevent.extras);
  });
  emptyArray(inputs);
}

function emptyArray(list) {
  list.forEach(function(item) { return item = null; });
  list.length = 0;
}

function indentSelection(text, bounds, invert) {
/* fixed issues:
1. shift+tab at end of line deletes text - should indent if possible or return
2. shift at end of all text indent line - should insert spaces
3. shift+tab at end of all text throws an error
4. shift+tab somewhere in a line throws when reverse indentation is not possible
test text:
fff
 fff
fff
*/
  // from http://jsbin.com/ijedi
  var indentation, newText;
  var spaces = " ".repeat(config.indentation || 2);
  var numberOfIndents = spaces.length;
  var start = bounds[0];
  var end = bounds[1];
  var singleSelection = start === end;
  var removeSpace = new RegExp("^(\\s{1," + numberOfIndents + "})","mg");
  var addSpace = /^(?=.+)/mg;///^(?=[^\S\n]|.+)/mg;///^(?=.+)/mg;///^(?=.+|\s)/mg;///^.?/mg;
  var empty = /^\s*$/g;
  var affectedLines = 0;
  // extend the selection start until the previous new line
  start = text.lastIndexOf("\n", (singleSelection && invert) ? start-1 : start );
  // if there isn't a new line before,
  // then extend the selection until the beginning of the text
  if(start === -1)
    start = 0;
  // if the selection starts with a new line,
  // remove it from the selection
  if (text.charAt(start) === "\n")
    start += 1;

  // if the selection ends with a new line,
  // remove it from the selection
  if (text.charAt(end - 1) === "\n")
    end -= 1;
  // extend the selection end until the next new line
  end = text.indexOf("\n", end);
  // if there isn't a new line after,
  // then extend the selection end until the end of the text
  if (end === -1)
    end = text.length;
  // get text to indent
  indentation = text.substring(start, end);

  // test if the indendation selection is empty
  // note: or singleSelection could be used here to implement normal tab behavior
  if(empty.test(indentation) || singleSelection) {
    affectedLines = 1;
    // fix for 1. shift+tab at end of line deletes text - should indent if possible or return
    // note this is also runs for shift+tab in the middle of the last line
    if( invert && !empty.test(text.substring(Math.min(start, end)-numberOfIndents, end)) ) {
      var line = text.substring(Math.min(start, end), end);
      // test if reverse identation is possible (abort if it means deletetion of text) and return if not
      if(line.length === 0 || !empty.test(text.substring(bounds[0]-numberOfIndents, bounds[0])) )
        return;
    }

    if(invert) {
      indentation = ""; // nothing to indent
      start = bounds[0] - numberOfIndents; // "loose" n chars
      end = bounds[0]
    } else {
      indentation = spaces;
      start = end = bounds[0];
    }
  } else {
    // test if reverse identation is possible and return if not
    if(invert && !removeSpace.test(indentation))
      return;
    // count number of affected lines
    affectedLines = invert ? indentation.match(removeSpace).length : indentation.match(addSpace).length;
    // add two spaces/backspaces before new lines
    indentation = invert ? indentation.replace(removeSpace, "") : indentation.replace(addSpace, spaces);
  }
  // rebuild the textarea content
//log("start length:", text.length);
  newText = text.substring(0, start);
  newText += indentation;
  newText += text.substring(end);
//log("end length:", newText.length);
  ta.value = newText;
  if(singleSelection) {
    start = end = bounds[0] + (invert ? -numberOfIndents : numberOfIndents);
  } else {
    // add/substract end after indentation
    invert ? (end -= affectedLines*numberOfIndents) : (end += affectedLines*numberOfIndents);
  }
  // reselect text
  selectText(start, end);
}

function selectText(start, end) {
  ta.setSelectionRange(start, end || start);
}

function run(code) {
  out.clear();
  try {
    eval(code);
  } catch(e) {
    log(e);
  }
}

function log() {
  var args = Array.prototype.slice.call(arguments, 0).concat([null]);
  var isScrolledToBottom = out.scrollHeight - out.clientHeight < out.scrollTop + 2; // allow 1px inaccuracy
  args.forEach(writer);
  // scroll to bottom if isScrolledToBottom
  if(isScrolledToBottom)
    out.scrollTop = out.scrollHeight - out.clientHeight;
}

function singleForEach(obj, fnname) {
  return function(item, i, all) {
    obj[fnname](item);
  }
}

function createElement(name, value) {
  var html = document.createElement(name);
  html.innerHTML = value;
  return html;
}

function format(o) {
  o.clear = function() { out.innerHTML = ""; }
  return function(msg) {
    var f, html;
    if(msg === null) {
      html = createElement("br", msg);
    } else {
      f = classify(msg);
      html = createElement("span", f.value);
      window.setTimeout(function(){ setClasses(html, f.cls); }, 600);
    }
    o.appendChild(html);
  }
  function setClasses(html, cls) {
    if(cls.length)
      cls.forEach(singleForEach(html.classList, "add"));
  }
  function classify(msg) {
    var ret = { cls: [], value: "" };
    switch(typeof msg) {
      case "object":
        ret.value = JSON.stringify(msg, stringifyHostObject);
        ret.cls.push("obj");
        break;
      case "number":
        ret.value = msg;
        ret.cls.push("num");
        break;
      case "boolean":
        ret.value = msg;
        ret.cls.push(msg.toString());
        break;
      default:
        ret.value = msg;
    }
    return ret;
  }
  function stringifyHostObject(key, value) {
    if (value instanceof Event) {
      return { type: value.type, name: value.name, message: value.message };
    }
    if(value instanceof Error) {
      return { name: value.toString(), category: value.category, filename: value.filename, line: value.lineNumber, stack: value.stack };
    }
    return value;
  }
}

function polyfills() {
  // from https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js
  if(!String.prototype.repeat) {
    String.prototype.repeat = function(times) {
      return repeat(this, times);
    };
    function repeat(s, times) {
      if (times < 1) return '';
      if (times % 2) return repeat(s, times - 1) + s;
      var half = repeat(s, times / 2);
      return half + half;
    };
  }
}<commit_msg>fixed bug in createElement()<commit_after>var $ = function(selector) { return document.querySelectorAll(selector); };
var fst = function(list) { return list[0]; }
var canvas = fst($("canvas"));
var draw = canvas.getContext("2d");
var ta = fst($("textarea"));
var out = fst($("code"));
var writer = format(out);
var events = {
  Öshift13:run, // shift + enter
  Ö9:indentSelection, // tab
  Öshift9:function(text, bounds){ indentSelection(text, bounds, true); }, // shift + tab
  Öselection9:indentSelection, // select text + tab
  Öshiftselection9:function(text, bounds){ indentSelection(text, bounds, true); }, // shift + select text + tab
  Öshift8:out.clear // shift + backspace KLUDGE: format(out) has to be called before this
};
var config = {
  indentation: 2
}

window.addEventListener("error", log);

polyfills();

//a.addEventListener("mouseup", inputWatch(ta)); // mouse selection
ta.addEventListener("keydown", inputWatch(ta)); // detect tab
//ta.addEventListener("keypress", inputWatch(ta)); // detect tab

function KeyEvent(shift, ctrl, alt, selection, charcode, value, extras) {
  this.shift = shift;
  this.ctrl = ctrl;
  this.alt = alt;
  this.selection = selection;
  this.charCode = charcode;
  this.value = value;
  this.extras = extras;
}
KeyEvent.prototype.toString = function() {
  var self = this;
  return "Ö" + Object.keys(this).map(function(key) {
    var not = ["toString", "value", "extras"];
    var ret = (self[key] === true && key) || self[key];
    return !~not.indexOf(key) && ret || "";
  }).join("");
}

function inputWatch(field) {
  var notifyId;
  var inputs = [];
  return function(e) {
    e = e || window.event;
    var charCode = (e.which instanceof Number) ? e.which : e.keyCode;
    var value = field.value, isSelection = false, extras, ke;
    if(field.selectionStart < field.selectionEnd) {
      isSelection = true;
    }
    extras = [field.selectionStart, field.selectionEnd];
    ke = new KeyEvent(e.shiftKey, e.ctrlKey, e.altKey, isSelection, charCode, value, extras);
// log(ke.toString());
    inputs.push(ke);
    if(events[ke.toString()])
      e.preventDefault();
    if(notifyId)
      window.clearTimeout(notifyId);
    notifyId = window.setTimeout(runFunction, 60, inputs); // let me type :)
  }
}

function runFunction(inputs) {
  var shortcutFunction;
  inputs.forEach(function(keyevent) {
    shortcutFunction = events[ keyevent.toString() ];
    shortcutFunction && window.setTimeout(shortcutFunction, 0, keyevent.value, keyevent.extras);
  });
  emptyArray(inputs);
}

function emptyArray(list) {
  list.forEach(function(item) { return item = null; });
  list.length = 0;
}

function indentSelection(text, bounds, invert) {
/* fixed issues:
1. shift+tab at end of line deletes text - should indent if possible or return
2. shift at end of all text indent line - should insert spaces
3. shift+tab at end of all text throws an error
4. shift+tab somewhere in a line throws when reverse indentation is not possible
test text:
fff
 fff
fff
*/
  // from http://jsbin.com/ijedi
  var indentation, newText;
  var spaces = " ".repeat(config.indentation || 2);
  var numberOfIndents = spaces.length;
  var start = bounds[0];
  var end = bounds[1];
  var singleSelection = start === end;
  var removeSpace = new RegExp("^(\\s{1," + numberOfIndents + "})","mg");
  var addSpace = /^(?=.+)/mg;///^(?=[^\S\n]|.+)/mg;///^(?=.+)/mg;///^(?=.+|\s)/mg;///^.?/mg;
  var empty = /^\s*$/g;
  var affectedLines = 0;
  // extend the selection start until the previous new line
  start = text.lastIndexOf("\n", (singleSelection && invert) ? start-1 : start );
  // if there isn't a new line before,
  // then extend the selection until the beginning of the text
  if(start === -1)
    start = 0;
  // if the selection starts with a new line,
  // remove it from the selection
  if (text.charAt(start) === "\n")
    start += 1;

  // if the selection ends with a new line,
  // remove it from the selection
  if (text.charAt(end - 1) === "\n")
    end -= 1;
  // extend the selection end until the next new line
  end = text.indexOf("\n", end);
  // if there isn't a new line after,
  // then extend the selection end until the end of the text
  if (end === -1)
    end = text.length;
  // get text to indent
  indentation = text.substring(start, end);

  // test if the indendation selection is empty
  // note: or singleSelection could be used here to implement normal tab behavior
  if(empty.test(indentation) || singleSelection) {
    affectedLines = 1;
    // fix for 1. shift+tab at end of line deletes text - should indent if possible or return
    // note this is also runs for shift+tab in the middle of the last line
    if( invert && !empty.test(text.substring(Math.min(start, end)-numberOfIndents, end)) ) {
      var line = text.substring(Math.min(start, end), end);
      // test if reverse identation is possible (abort if it means deletetion of text) and return if not
      if(line.length === 0 || !empty.test(text.substring(bounds[0]-numberOfIndents, bounds[0])) )
        return;
    }

    if(invert) {
      indentation = ""; // nothing to indent
      start = bounds[0] - numberOfIndents; // "loose" n chars
      end = bounds[0]
    } else {
      indentation = spaces;
      start = end = bounds[0];
    }
  } else {
    // test if reverse identation is possible and return if not
    if(invert && !removeSpace.test(indentation))
      return;
    // count number of affected lines
    affectedLines = invert ? indentation.match(removeSpace).length : indentation.match(addSpace).length;
    // add two spaces/backspaces before new lines
    indentation = invert ? indentation.replace(removeSpace, "") : indentation.replace(addSpace, spaces);
  }
  // rebuild the textarea content
//log("start length:", text.length);
  newText = text.substring(0, start);
  newText += indentation;
  newText += text.substring(end);
//log("end length:", newText.length);
  ta.value = newText;
  if(singleSelection) {
    start = end = bounds[0] + (invert ? -numberOfIndents : numberOfIndents);
  } else {
    // add/substract end after indentation
    invert ? (end -= affectedLines*numberOfIndents) : (end += affectedLines*numberOfIndents);
  }
  // reselect text
  selectText(start, end);
}

function selectText(start, end) {
  ta.setSelectionRange(start, end || start);
}

function run(code) {
  out.clear();
  try {
    eval(code);
  } catch(e) {
    log(e);
  }
}

function log() {
  var args = Array.prototype.slice.call(arguments, 0).concat([null]);
  var isScrolledToBottom = out.scrollHeight - out.clientHeight < out.scrollTop + 2; // allow 1px inaccuracy
  args.forEach(writer);
  // scroll to bottom if isScrolledToBottom
  if(isScrolledToBottom)
    out.scrollTop = out.scrollHeight - out.clientHeight;
}

function singleForEach(obj, fnname) {
  return function(item, i, all) {
    obj[fnname](item);
  }
}

function createElement(name, value) {
  var html = document.createElement(name);
  if(value !== undefined)
    html.innerHTML = value;
  return html;
}

function format(o) {
  o.clear = function() { out.innerHTML = ""; }
  return function(msg) {
    var f, html;
    if(msg === null) {
      html = createElement("br");
    } else {
      f = classify(msg);
      html = createElement("span", f.value);
      window.setTimeout(function(){ setClasses(html, f.cls); }, 600);
    }
    o.appendChild(html);
  }
  function setClasses(html, cls) {
    if(cls.length)
      cls.forEach(singleForEach(html.classList, "add"));
  }
  function classify(msg) {
    var ret = { cls: [], value: "" };
    switch(typeof msg) {
      case "object":
        ret.value = JSON.stringify(msg, stringifyHostObject);
        ret.cls.push("obj");
        break;
      case "number":
        ret.value = msg;
        ret.cls.push("num");
        break;
      case "boolean":
        ret.value = msg;
        ret.cls.push(msg.toString());
        break;
      default:
        ret.value = msg;
    }
    return ret;
  }
  function stringifyHostObject(key, value) {
    if (value instanceof Event) {
      return { type: value.type, name: value.name, message: value.message };
    }
    if(value instanceof Error) {
      return { name: value.toString(), category: value.category, filename: value.filename, line: value.lineNumber, stack: value.stack };
    }
    return value;
  }
}

function polyfills() {
  // from https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js
  if(!String.prototype.repeat) {
    String.prototype.repeat = function(times) {
      return repeat(this, times);
    };
    function repeat(s, times) {
      if (times < 1) return '';
      if (times % 2) return repeat(s, times - 1) + s;
      var half = repeat(s, times / 2);
      return half + half;
    };
  }
}<|endoftext|>


<commit_before>var fn = null;

angular.module('wordBaseHack', [])
    .controller('wordBaseController', function () {

    var that = this;

    // SERIALISTS missing

    that.puzzle = [
        'PDEIPDHDIL',
        'GLTVNEYTEF',
        'NAYORGMIWO',
        'TNSLULNPER',
        'IGISNOWDTA',
        'SRTIASAFNR',
        'OADWLPOLEV',
        'UNBLOCLYIO',
        'ARVIAOIASR',
        'IOSARTPLTE',
        'PLTOICSXYL',
        'AEIMNTEDNM',
        'TSRAHILALO'];

    that.startFromBottom = false;

    var WIDTH = that.puzzle[0].length;
    var HEIGHT = that.puzzle.length;

    for (var i = 0; i < HEIGHT; i++) {
        that.puzzle[i] = that.puzzle[i].split('');
        for (var j = 0; j < WIDTH; j++) {
            that.puzzle[i][j] = {
                letter: that.puzzle[i][j],
                highlighted: false
            }
        }
    }

    function init (dictionary, formableWords) {
        that.dictionary = dictionary;
        that.formableWords = formableWords
        console.log('READY!');
    }

    that.words = [];

    that.getWordFromSequence = function (sequence) {
        return sequence.map(function (object) {
            return object.letter;
        }).join('');
    };

    function resetHighlighting () {
        for (var i = 0; i < HEIGHT; i++) {
            for (var j = 0; j < WIDTH; j++) {
                that.puzzle[i][j].highlighted = false;
            }
        }
    }

    that.highlightLetters = function (sequence) {
        resetHighlighting();
        sequence.forEach(function (item) {
            that.puzzle[item.row][item.col].highlighted = true;
        });
    }

    that.findWordsFromCell = function (i, j) {
        resetHighlighting();
        var words = [];
        var count = 0;
        function traverse(currPuzzle, currSeq, i, j) {
            count++;
            if (i < 0 || i >= HEIGHT ||
                j < 0 ||
                j >= WIDTH) {
                return;
            }
            if (currPuzzle[i][j] === '*') {
                return;
            }
            currSeq.push({
                letter: currPuzzle[i][j].letter,
                row: i,
                col: j
            });
            currPuzzle[i][j].letter = '*';
            var puzzle = _.cloneDeep(currPuzzle);
            var currentWord = that.getWordFromSequence(currSeq);
            if (that.dictionary[currentWord]) {
                words.push(currSeq);
            }
            if (!that.formableWords[currentWord]) {
                return;
            }
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i - 1, j - 1);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i - 1, j);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i - 1, j + 1);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i, j - 1);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i, j + 1);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i + 1, j - 1);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i + 1, j);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i + 1, j + 1);
        }

        traverse(_.cloneDeep(that.puzzle), [], i, j);

        words.sort(function (a, b) {
            return b.length - a.length;
        });

        that.words = words;
    }

    that.computeProgress = function (word) {
        var startRow = word[0].row;
        var maxDistance = 0;
        var minDistance = 0;
        word.forEach(function (obj) {
            var difference = startRow - obj.row;
            var differenceA = Math.max(difference, 0);
            if (differenceA > maxDistance) {
                maxDistance = differenceA;
            }
            var differenceB = Math.min(difference, 0);
            if (differenceB < minDistance) {
                minDistance = differenceB;
            }
        });
        return Math.abs(that.startFromBottom ? maxDistance : minDistance);
    }

    $(function () {
        $.get('data/words.json', function (data) {
            var dictionary = {};
            var formableWords = {};
            data.forEach(function (word) {
                dictionary[word] = true;
                for (var i = 1; i < word.length; i++) {
                    formableWords[word.slice(0, i)] = true;
                }
            });
            init(dictionary, formableWords);
        });
    });
});
<commit_msg>Extract out traversed symbol<commit_after>var fn = null;

const TRAVERSED_SYMBOL = '*';

angular.module('wordBaseHack', [])
    .controller('wordBaseController', function () {

    var that = this;

    // SERIALISTS missing

    that.puzzle = [
        'PDEIPDHDIL',
        'GLTVNEYTEF',
        'NAYORGMIWO',
        'TNSLULNPER',
        'IGISNOWDTA',
        'SRTIASAFNR',
        'OADWLPOLEV',
        'UNBLOCLYIO',
        'ARVIAOIASR',
        'IOSARTPLTE',
        'PLTOICSXYL',
        'AEIMNTEDNM',
        'TSRAHILALO'];

    that.startFromBottom = false;

    var WIDTH = that.puzzle[0].length;
    var HEIGHT = that.puzzle.length;

    for (var i = 0; i < HEIGHT; i++) {
        that.puzzle[i] = that.puzzle[i].split('');
        for (var j = 0; j < WIDTH; j++) {
            that.puzzle[i][j] = {
                letter: that.puzzle[i][j],
                highlighted: false
            }
        }
    }

    function init (dictionary, formableWords) {
        that.dictionary = dictionary;
        that.formableWords = formableWords
        console.log('READY!');
    }

    that.words = [];

    that.getWordFromSequence = function (sequence) {
        return sequence.map(function (object) {
            return object.letter;
        }).join('');
    };

    function resetHighlighting () {
        for (var i = 0; i < HEIGHT; i++) {
            for (var j = 0; j < WIDTH; j++) {
                that.puzzle[i][j].highlighted = false;
            }
        }
    }

    that.highlightLetters = function (sequence) {
        resetHighlighting();
        sequence.forEach(function (item) {
            that.puzzle[item.row][item.col].highlighted = true;
        });
    }

    that.findWordsFromCell = function (i, j) {
        resetHighlighting();
        var words = [];
        var count = 0;
        function traverse(currPuzzle, currSeq, i, j) {
            count++;
            if (i < 0 || i >= HEIGHT ||
                j < 0 ||
                j >= WIDTH) {
                return;
            }
            if (currPuzzle[i][j] === TRAVERSED_SYMBOL) {
                return;
            }
            currSeq.push({
                letter: currPuzzle[i][j].letter,
                row: i,
                col: j
            });
            currPuzzle[i][j].letter = TRAVERSED_SYMBOL;
            var puzzle = _.cloneDeep(currPuzzle);
            var currentWord = that.getWordFromSequence(currSeq);
            if (that.dictionary[currentWord]) {
                words.push(currSeq);
            }
            if (!that.formableWords[currentWord]) {
                return;
            }
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i - 1, j - 1);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i - 1, j);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i - 1, j + 1);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i, j - 1);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i, j + 1);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i + 1, j - 1);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i + 1, j);
            traverse(_.cloneDeep(puzzle), _.cloneDeep(currSeq), i + 1, j + 1);
        }

        traverse(_.cloneDeep(that.puzzle), [], i, j);

        words.sort(function (a, b) {
            return b.length - a.length;
        });

        that.words = words;
    }

    that.computeProgress = function (word) {
        var startRow = word[0].row;
        var maxDistance = 0;
        var minDistance = 0;
        word.forEach(function (obj) {
            var difference = startRow - obj.row;
            var differenceA = Math.max(difference, 0);
            if (differenceA > maxDistance) {
                maxDistance = differenceA;
            }
            var differenceB = Math.min(difference, 0);
            if (differenceB < minDistance) {
                minDistance = differenceB;
            }
        });
        return Math.abs(that.startFromBottom ? maxDistance : minDistance);
    }

    $(function () {
        $.get('data/words.json', function (data) {
            var dictionary = {};
            var formableWords = {};
            data.forEach(function (word) {
                dictionary[word] = true;
                for (var i = 1; i < word.length; i++) {
                    formableWords[word.slice(0, i)] = true;
                }
            });
            init(dictionary, formableWords);
        });
    });
});
<|endoftext|>


<commit_before>/**
 * General description of what this file does
 * window.yogiipsum
 *
 * Created by Spencer Sanchez
 * 2013-09-01
 *
 * JS dependencies:
 *		jQuery
 *		Zurb Foundation 4
 *
 * internals:
 *		yogiipsum.global
 *		yogiipsum.analytics
 *		yogiipsum.phrases
 *
 */

(function(ns, window, $, undefined){
	/** @exports ns as window.yogiipsum */
	"use strict";

	/**
	 *
	 * yogiipsum.global
	 *
	 * Actions and event bindings not spcific to any larger component
	 *
	 */
	ns.global = {

		_bindEvents: function () {
			var that = this;

			$('input[type="submit"]').click(function(event){
				event.preventDefault();
				return false;
			});
		},

		init: function () {
			this._bindEvents();
		}
	};

	/**
	 *
	 * yogiipsum.analytics
	 *
	 * handles most of the google analytics functionality for the site
	 *
	 */
	ns.analytics = {
		_bindEvents: function () {
			var that = this;

			/* send off an event when generate is clicked including current vals */
			$('#generate').click(function(){
				that.trackEvent('User Action', 'generate ipsum');
			});

			/* the next two fire events when changing options */
			$('input').filter('[type="radio"]').each(function(){
				$(this).click(function(){
					that.trackEvent('User Action', this.name + ' to: ' + this.value);
				});
			});
			$('#numParagraphs').change(function(){
				that.trackEvent('User Action', 'num paragraphs to: ' + this.value);
			});
		},

		/* returns a pipe-delimeted string of name/val pairs for the user-changable controls */
		_serialize: function () {
			var vals = [];
			$('input').filter(':checked').add('#numParagraphs').each(function(){
				vals.push('|', this.name, '=', this.value);
			});
			return vals.join('');
		},

		/* Generic function to send and event to GA. Label is always form config. */
		trackEvent: function ( eventname, action ) {
			if ( window._gaq !== undefined ) {
				window._gaq.push( ['_trackEvent', eventname, action, this._serialize()] );
			}
		},

		init: function () {
			this._bindEvents();
		}
	};

	/**
	 *
	 * yogiipsum.phrases
	 *
	 * Load and set up action for generating ipsum text
	 *
	 */
	ns.phrases = {
		phrases: [],

		_bindEvents: function () {
			var that = this;
			$('#generate').click(function(){
				that._setPhrases( that._getPhrases() );
				$(this).blur();
			});
		},

		_getPhrases: function () {
			var i, j, x, y, z,
				jumbled = !document.getElementById('jumble').checked,
				num = document.getElementById('numParagraphs').value,
				wrappers = document.getElementById('wrappers').checked,
				str = document.getElementById('itAintOver').checked? "It ain't over 'til it's over. ": "";

			for (i=0; i<num; i++) {
				// random number of phrases for this paragraph
				z = Math.floor( Math.random() * this.phrases.length/4) + 1;

				for (j=0; j<z; j++) {
					x = Math.floor( Math.random() * this.phrases.length);
					y = jumbled? x: Math.floor( Math.random() * this.phrases.length);
					str += this.phrases[x].a + this.phrases[y].b;
				}
				str += "\n\n";
			}
			str = str.substr(0, str.length - 2);

			if (wrappers) {
				str = "
" + str.replace(/\n\n/g, "
\n\n
") + "
";
			}

			return str;
		},

		_loadPhrases: function () {
			var that = this;
			$.getJSON('phrases.json', function(json, textStatus) {
				var x = Math.floor( Math.random() * json.phrases.length);
				that.phrases = json.phrases;
				that._setPhrases( json.phrases[x].a + json.phrases[x].b );
			});
		},

		_setPhrases: function (str) {
			$('#ipsum').val( str );
		},

		init: function () {
			this._loadPhrases();
			this._bindEvents();
		}
	};

	/**
	 *
	 * yogiipsum.init
	 *
	 * Start the app, calling the init's of any sub-namespaces and
	 * kicking off the main Foundation script
	 *
	 */
	ns.init = function () {
		ns.global.init();
		ns.phrases.init();
		ns.analytics.init();
		$(document).foundation();
	};

	$(function(){
		ns.init();
	});

})(this.yogiipsum = this.yogiipsum || {}, this, jQuery, undefined);
<commit_msg>global openWindow utility and handler<commit_after>/**
 * General description of what this file does
 * window.yogiipsum
 *
 * Created by Spencer Sanchez
 * 2013-09-01
 *
 * JS dependencies:
 *		jQuery
 *		Zurb Foundation 4
 *
 * internals:
 *		yogiipsum.global
 *		yogiipsum.analytics
 *		yogiipsum.phrases
 *
 */

(function(ns, window, $, undefined){
	/** @exports ns as window.yogiipsum */
	"use strict";

	/**
	 *
	 * yogiipsum.global
	 *
	 * Actions and event bindings not spcific to any larger component
	 *
	 */
	ns.global = {

		_bindEvents: function () {
			var that = this;

			// control external links to new windows tagged with class 'external'
			$('a').filter('.external').click(function(event){
				event.preventDefault();
				that.openWindow( this.href );
			});
		},

		// Opens a new window with passed url. Width and height are optionally
		// passed in. Menubar and toolbar are explicitly set to off.
		openWindow: function (url, width, height) {
			width = typeof width === 'undefined' ? 550 : width;
			height = typeof height === 'undefined' ? 400 : height;
			window.open(url, 'kid', 'width='+ width +',height='+ height +',menubar=no,toolbar=no');
		},

		init: function () {
			this._bindEvents();
		}
	};

	/**
	 *
	 * yogiipsum.analytics
	 *
	 * handles most of the google analytics functionality for the site
	 *
	 */
	ns.analytics = {
		_bindEvents: function () {
			var that = this;

			// send off an event when generate is clicked including current vals
			$('#generate').click(function(){
				that.trackEvent('User Action', 'generate ipsum');
			});

			// the next two fire events when changing options
			$('input').filter('[type="radio"]').each(function(){
				$(this).click(function(){
					that.trackEvent('User Action', this.name + ' to: ' + this.value);
				});
			});
			$('#numParagraphs').change(function(){
				that.trackEvent('User Action', 'num paragraphs to: ' + this.value);
			});
		},

		// returns a pipe-delimeted string of name/val pairs for the user-changable controls
		_serialize: function () {
			var vals = [];
			$('input').filter(':checked').add('#numParagraphs').each(function(){
				vals.push('|', this.name, '=', this.value);
			});
			return vals.join('');
		},

		// Generic function to send and event to GA. Label is always form config.
		trackEvent: function ( eventname, action ) {
			if ( window._gaq !== undefined ) {
				window._gaq.push( ['_trackEvent', eventname, action, this._serialize()] );
			}
		},

		init: function () {
			this._bindEvents();
		}
	};

	/**
	 *
	 * yogiipsum.phrases
	 *
	 * Load and set up action for generating ipsum text
	 *
	 */
	ns.phrases = {
		phrases: [],

		_bindEvents: function () {
			var that = this;
			$('#generate').click(function(){
				that._setPhrases( that._getPhrases() );
				$(this).blur();
			});
		},

		_getPhrases: function () {
			var i, j, x, y, z,
				jumbled = !document.getElementById('jumble').checked,
				num = document.getElementById('numParagraphs').value,
				wrappers = document.getElementById('wrappers').checked,
				str = document.getElementById('itAintOver').checked? "It ain't over 'til it's over. ": "";

			for (i=0; i<num; i++) {
				// random number of phrases for this paragraph
				z = Math.floor( Math.random() * this.phrases.length/4) + 1;

				for (j=0; j<z; j++) {
					x = Math.floor( Math.random() * this.phrases.length);
					y = jumbled? x: Math.floor( Math.random() * this.phrases.length);
					str += this.phrases[x].a + this.phrases[y].b;
				}
				str += "\n\n";
			}
			str = str.substr(0, str.length - 2);

			if (wrappers) {
				str = "
" + str.replace(/\n\n/g, "
\n\n
") + "
";
			}

			return str;
		},

		_loadPhrases: function () {
			var that = this;
			$.getJSON('phrases.json', function(json, textStatus) {
				var x = Math.floor( Math.random() * json.phrases.length);
				that.phrases = json.phrases;
				that._setPhrases( json.phrases[x].a + json.phrases[x].b );
			});
		},

		_setPhrases: function (str) {
			$('#ipsum').val( str );
		},

		init: function () {
			this._loadPhrases();
			this._bindEvents();
		}
	};

	/**
	 *
	 * yogiipsum.init
	 *
	 * Start the app, calling the init's of any sub-namespaces and
	 * kicking off the main Foundation script
	 *
	 */
	ns.init = function () {
		ns.global.init();
		ns.phrases.init();
		ns.analytics.init();
		$(document).foundation();
	};

	$(function(){
		ns.init();
	});

})(this.yogiipsum = this.yogiipsum || {}, this, jQuery, undefined);
<|endoftext|>


<commit_before>/*global $ */
'use strict';

//---Objects---//

//Player Class
function Player(name){
	this.name = name;
	this.stump = new TreeStump();
}

//ask for number of players and each players name
function startGame(){
		var numberOfPlayers = prompt('How many players do we have?'),playerName = '',player = {};
		//sanity check
		console.log('num of players is ' + numberOfPlayers);
		for (var i = 0; i < numberOfPlayers; i++) {
			playerName = prompt('What is this player '+ (i+1) +'\'s name?');
			player[i] = new Player(playerName);
			players.push(player[i]);
		}
		return players;
	}

//Makes a list of the players
function listPlayers(){
	var list = [],playerName,playerBox;
	for (var i = 0; i < players.length; i++) {
		playerName = players[i].name;
		playerBox = '
'+playerName+'
';
		list.push(playerBox);
	}
	return list;
}

//?build the score treestump?
function scoreCard(){
	//card is an array of acorn spaces. acorn is individual colored acorns
	var card = [],acorn;
	//get the number of players
	for(var j = 0; j < players[j].length; j++){
		//get the number of acorn spaces
		for (var k = 0; k < players[j].stump.playerStump.length; k++) {
			//
			card += players[j].stump.playerStump.length;
		}
	}
	return card;
}

//Spinner Class.
//Represents the spin wheel.
//Returns: id, name, instruction, and action of spin result
function Spinner() {
	//Array to represent the game spinner
	this.wheel = [
		{
			id: 0,
			name: 'Sneaky Squire',
			// verb: placeholderFunction(),
			instruction: 'You get to Steal an Acorn from another user!',
			action: 'steal'
		},
		{
			id: 1,
			name: 'Sleepy Squire',
			// verb: placeholderFunction(),
			instruction: 'Oh no! You lose your turn because you were sleeping. :(',
			action: 'skip'
		},
		{
			id: 2,
			name: 'Wind Storm',
			// verb: placeholderFunction(),
			instruction: 'A strong wind storm blew all your acorns away. Tough break.',
			action: 'clear'
		},
		{
			id: 3,
			name: 'Green',
            color:'green',
            //verb: addColorSquare(this.color),
			instruction: 'You get a Green Acorn'
		},
		{
			id: 4,
			name: 'Blue',
			color:'blue',
			// verb: placeholderFunction(),
			instruction: 'You get a Blue Acorn'
		},
		{
			id: 5,
			name: 'Red',
			color:'red',
			// verb: placeholderFunction(),
			instruction: 'You get a Red Acorn'
		},
		{
			id: 6,
			name: 'Purple',
			color:'purple',
			// verb: placeholderFunction(),
			instruction: 'You get a Purple Acorn'
		},
		{
			id: 7,
			name: 'Yellow',
			color:'yellow',
			// verb: placeholderFunction(),
			instruction: 'You get a Yellow Acorn'
		},
		{
			id: 8,
			name: 'Pick One',
			// verb: placeholderFunction(),
			instruction: 'You get to pick an Acorn',
			action: 'pick_one'
		},
		{
			id: 9,
			name: 'Pick Two',
			// verb: placeholderFunction(),
			instruction: 'You get to pick Two Acorns',
			action: 'pick_two'
		}
    ];

	//Spin the Wheel function. Returns a representation of landing on a color or event
	this.spin = function () {
		//get a random number
        var i = Math.floor((Math.random()*this.wheel.length));
        //feed that number to the wheel array to pull an individual item
        var result = this.wheel[i];
        return result;
    };
}

//function to check is player already has the acorn color in their stump
function acornCheck(player, result){
	for (var k = players[player].stump.playerStump.length - 1; k >= 0; k--) {
		//console.log(players[player].stump.playerStump[i]);
		if(players[player].stump.playerStump[k].color === result.color){
			if(players[player].stump.playerStump[k].isEmpty === true){
				players[player].stump.playerStump[k].isEmpty = false;
			}else{
				console.log('You already have this Acorn!');
			}
		}
	};
}

//Game Piece Class
function TreeStump() {
	var empty = Boolean(true);
	this.playerStump = [
		{
			color: 'red',
			isEmpty: empty
		},
		{
			color: 'blue',
			isEmpty: empty
		},
		{
			color: 'yellow',
			isEmpty: empty
		},
		{
			color: 'green',
			isEmpty: empty
		},
		{
			color: 'purple',
			isEmpty: empty
		}
	];

	//display in html
	$('.playerBox').html('
playerCard
');
}

//---Declare Variables---//

//holds the list of players
var players = [],
	spinner = new Spinner()
;

//Begin the game by asking the number of players and their name
startGame();

$(document).ready(function(){
	//make the players name visible
	$('.player_table').append(listPlayers());
	//who's turn is it?
	for(var j = 0; j < players.length;j++){
		//print who's turn it is
		$('.player_turn_information').html('It is player: '+ players[j].name +'\'s turn.');
		//1. when a user clicks Spin the Wheel, pick a random wheelElement
		$('#spin_button').click(function(){
			var result = spinner.spin();
			$('.spin_action_result').html(result.instruction);
			//2. check to see if the wheelElement is a Color or Event
			var colorOrAction = result.hasOwnProperty('color');
			if(colorOrAction){
				//sanity check
				console.log(result.color);
				console.log(players[j].name);
				//3. if it is a Color, check to see if the users treeStump already has the Color
				acornCheck(j,result);
			}
		});
		return;
	}
});

//3a. add color to treeStump if it doesn't exist, else skip turn
//3b. check to see if the active players treeStump is full.  if so, they win. else move to next player
//4. if it is an Event, check to see which Event it is
//4a. if event is Sneaky Squire - steal an Acorn from another player
//4a_A  bring up list of every player containing thier Acorns
//4a_B  When the active Player selects an Acorn from another list, add it to thier treeStump
//4a_C  check to see if treeStump is full. if so, they win End turn
//5. if event is Sleepy Squire - skip turn
//6. if event is Wind Storm - remove all Acorns from active Players list

<commit_msg>removed playerCard function<commit_after>/*global $ */
'use strict';

//---Objects---//

//Player Class
function Player(name){
	this.name = name;
	this.stump = new TreeStump();
}

//ask for number of players and each players name
function startGame(){
		var numberOfPlayers = prompt('How many players do we have?'),playerName = '',player = {};
		//sanity check
		console.log('num of players is ' + numberOfPlayers);
		for (var i = 0; i < numberOfPlayers; i++) {
			playerName = prompt('What is this player '+ (i+1) +'\'s name?');
			player[i] = new Player(playerName);
			players.push(player[i]);
		}
		return players;
	}

//Makes a list of the players
function listPlayers(){
	var list = [],playerName,playerBox;
	for (var i = 0; i < players.length; i++) {
		playerName = players[i].name;
		playerBox = '
'+playerName+'
';
		list.push(playerBox);
	}
	return list;
}

//Spinner Class.
//Represents the spin wheel.
//Returns: id, name, instruction, and action of spin result
function Spinner() {
	//Array to represent the game spinner
	this.wheel = [
		{
			id: 0,
			name: 'Sneaky Squire',
			// verb: placeholderFunction(),
			instruction: 'You get to Steal an Acorn from another user!',
			action: 'steal'
		},
		{
			id: 1,
			name: 'Sleepy Squire',
			// verb: placeholderFunction(),
			instruction: 'Oh no! You lose your turn because you were sleeping. :(',
			action: 'skip'
		},
		{
			id: 2,
			name: 'Wind Storm',
			// verb: placeholderFunction(),
			instruction: 'A strong wind storm blew all your acorns away. Tough break.',
			action: 'clear'
		},
		{
			id: 3,
			name: 'Green',
            color:'green',
            //verb: addColorSquare(this.color),
			instruction: 'You get a Green Acorn'
		},
		{
			id: 4,
			name: 'Blue',
			color:'blue',
			// verb: placeholderFunction(),
			instruction: 'You get a Blue Acorn'
		},
		{
			id: 5,
			name: 'Red',
			color:'red',
			// verb: placeholderFunction(),
			instruction: 'You get a Red Acorn'
		},
		{
			id: 6,
			name: 'Purple',
			color:'purple',
			// verb: placeholderFunction(),
			instruction: 'You get a Purple Acorn'
		},
		{
			id: 7,
			name: 'Yellow',
			color:'yellow',
			// verb: placeholderFunction(),
			instruction: 'You get a Yellow Acorn'
		},
		{
			id: 8,
			name: 'Pick One',
			// verb: placeholderFunction(),
			instruction: 'You get to pick an Acorn',
			action: 'pick_one'
		},
		{
			id: 9,
			name: 'Pick Two',
			// verb: placeholderFunction(),
			instruction: 'You get to pick Two Acorns',
			action: 'pick_two'
		}
    ];

	//Spin the Wheel function. Returns a representation of landing on a color or event
	this.spin = function () {
		//get a random number
        var i = Math.floor((Math.random()*this.wheel.length));
        //feed that number to the wheel array to pull an individual item
        var result = this.wheel[i];
        return result;
    };
}

//function to check is player already has the acorn color in their stump
function acornCheck(player, result){
	for (var k = players[player].stump.space.length - 1; k >= 0; k--) {
		if(players[player].stump.space[k].color === result.color){
			if(players[player].stump.space[k].isEmpty === true){
				players[player].stump.space[k].isEmpty = false;
			}else{
				console.log('You already have this Acorn!');
			}
		}
	};
}

//Game Piece Class
function TreeStump() {
	var empty = Boolean(true);
	this.space = [
		{
			color: 'red',
			isEmpty: empty
		},
		{
			color: 'blue',
			isEmpty: empty
		},
		{
			color: 'yellow',
			isEmpty: empty
		},
		{
			color: 'green',
			isEmpty: empty
		},
		{
			color: 'purple',
			isEmpty: empty
		}
	];

	//display in html
	$('.playerBox').html('
playerCard
');
}

//---Declare Variables---//

//holds the list of players
var players = [],
	spinner = new Spinner()
;

//Begin the game by asking the number of players and their name
startGame();

$(document).ready(function(){
	//make the players name visible
	$('.player_table').append(listPlayers());
	//who's turn is it?
	for(var j = 0; j < players.length;j++){
		//print who's turn it is
		$('.player_turn_information').html('It is player: '+ players[j].name +'\'s turn.');
		//1. when a user clicks Spin the Wheel, pick a random wheelElement
		$('#spin_button').click(function(){
			var result = spinner.spin();
			$('.spin_action_result').html(result.instruction);
			//2. check to see if the wheelElement is a Color or Event
			var colorOrAction = result.hasOwnProperty('color');
			if(colorOrAction){
				//sanity check
				console.log(result.color);
				console.log(players[j].name);
				//3. if it is a Color, check to see if the users treeStump already has the Color
				acornCheck(j,result);
			}
		});
		return;
	}
});

//3a. add color to treeStump if it doesn't exist, else skip turn
//3b. check to see if the active players treeStump is full.  if so, they win. else move to next player
//4. if it is an Event, check to see which Event it is
//4a. if event is Sneaky Squire - steal an Acorn from another player
//4a_A  bring up list of every player containing thier Acorns
//4a_B  When the active Player selects an Acorn from another list, add it to thier treeStump
//4a_C  check to see if treeStump is full. if so, they win End turn
//5. if event is Sleepy Squire - skip turn
//6. if event is Wind Storm - remove all Acorns from active Players list

<|endoftext|>