<commit_before>app.config(function($routeProvider, $locationProvider){

	$locationProvider.html5Mode(false);

	$routeProvider
		.when('/login', {
			controller: 'loginController',
			templateUrl: SETTINGS.views() + 'login.html',
			resolve: {
				isLoggedIn: checkLogin
			}
		})
		.when('/', {
			controller: 'homeController',
			templateUrl: SETTINGS.views() + 'home.html',
			resolve: {
				isLoggedIn: checkLogin
			}
		})
		.when('/cart', {
			controller: 'cartController',
			templateUrl: SETTINGS.views() + 'cart.html',
			resolve: {
				isLoggedIn: checkLogin
				//exists : checkPage
			}
		})
		.when('/checkout', {
			controller: 'checkoutController',
			templateUrl: SETTINGS.views() + 'checkout.html',
			resolve: {
				isLoggedIn: checkLogin
				//exists : checkPage
			}
		})
		.when('/checkout/success', {
			controller: 'successController',
			templateUrl: SETTINGS.views() + 'success.html',
			resolve: {
				isLoggedIn: checkLogin
				//exists : checkPage
			}
		})
		.when('/invoice', {
			controller: 'invoiceController',
			templateUrl: SETTINGS.views() + 'invoice.html',
			resolve: {
				isLoggedIn: checkLogin
				//exists : checkPage
			}
		})
		.when('/:category*/p/:product', {
			controller: 'productController',
			templateUrl: SETTINGS.views() + 'product.html',
			resolve: {
				isLoggedIn: checkLogin,
				exists : function(check) {return check.category()}
			}
		})
		.when('/:category*', {
			controller: 'categoryController',
			templateUrl: SETTINGS.views() + 'category.html',
			resolve: {
				isLoggedIn: checkLogin,
				exists : function(check) {return check.category()}
			}
		})

		// .when('/:page/:subpage', {
		// 	controller: 'pageController',
		// 	templateUrl: SETTINGS.views() + 'page.html',
		// 	resolve: {
		// 		isLoggedIn: checkLogin,
		// 		exists : function(check) {return check.category()}
		// 	}
		// })
		.when('/404', {
			controller: 'homeController',
			templateUrl: SETTINGS.views() + 'home.html',
			resolve: {
				isLoggedIn: checkLogin
			}
		})
		.otherwise({
			redirectTo: '/404'
		});
});

checkLogin = function() {
	if (USER.admin) {
		console.log('You\'re loggen in as admin');
	}
	else {
		console.log("You are nobody");
	}
}

app.factory('check', function($location, $routeParams, api) {
	return {
		category : function(path) {
			console.log($location.path())
			api.post("checkpage", path).then(function(response) {
				console.log(response);
			});
		},
		product : function(path) {
			api.post("checkpage", path).then(function(response) {
				console.log(response);
			})
		}
	}
	// if ($routeParams.page != "login" || $routeParams.page != "404") {
	// 	$location.path("/404");
	// }
})

app.run(function($rootScope, $location) {
    $rootScope.$on( "$routeChangeStart", function(event, next, current) {
      if (!USER.admin) {
        // no logged user, redirect to /login
        if ( next.templateUrl === "partials/login.html") {
        } else {
          $location.path("/login");
        }
      }
    });
  });
<commit_msg>ADD: new routes and authentication<commit_after>app.config(function($routeProvider, $locationProvider){

	$locationProvider.html5Mode(false);

	$routeProvider
		.when('/', {
			controller: 'homeController',
			templateUrl: SETTINGS.views() + 'home.html',
			resolve: {
			}
		})
		.when('/login', {
			controller: 'loginController',
			templateUrl: SETTINGS.views() + 'login.html',
			resolve: {
			}
		})
		.when('/cart', {
			controller: 'cartController',
			templateUrl: SETTINGS.views() + 'cart.html',
			resolve: {
				//exists : checkPage
			}
		})
		.when('/checkout', {
			controller: 'checkoutController',
			templateUrl: SETTINGS.views() + 'checkout.html',
			resolve: {
				//exists : checkPage
			}
		})
		.when('/checkout/success', {
			controller: 'successController',
			templateUrl: SETTINGS.views() + 'success.html',
			resolve: {
				//exists : checkPage
			}
		})
		.when('/invoice', {
			controller: 'invoiceController',
			templateUrl: SETTINGS.views() + 'invoice.html',
			resolve: {
				//exists : checkPage
			}
		})
		.when('/admin', {
			controller: 'ordersController',
			templateUrl: SETTINGS.views() + 'admin.html',
			resolve: {
				//exists : function() {return check.admin()}
			}
		})
		.when('/admin/orders', {
			controller: 'ordersController',
			templateUrl: SETTINGS.views() + 'orders.html',
			resolve: {
				//exists : function() {return check.admin()}
			}
		})
		.when('/admin/orders/:order_id', {
			controller: 'orderDetailController',
			templateUrl: SETTINGS.views() + 'orderDetail.html',
			resolve: {
				//exists : function() {return check.admin()}
			}
		})
		.when('/:category*/p/:product', {
			controller: 'productController',
			templateUrl: SETTINGS.views() + 'product.html',
			resolve: {
			//	exists : function() {return check.category()}
			}
		})
		.when('/:category*', {
			controller: 'categoryController',
			templateUrl: SETTINGS.views() + 'category.html',
			resolve: {
				//exists : function() {return check.category()}
			}
		})

		// .when('/:page/:subpage', {
		// 	controller: 'pageController',
		// 	templateUrl: SETTINGS.views() + 'page.html',
		// 	resolve: {
		// 		isLoggedIn: checkLogin,
		// 		exists : function(check) {return check.category()}
		// 	}
		// })
		.when('/404', {
			controller: 'homeController',
			templateUrl: SETTINGS.views() + 'home.html',
			resolve: {
//				isLoggedIn: checkLogin
			}
		})
		.otherwise({
			redirectTo: '/404'
		});
});

app.service('check', function($location, $routeParams, api, auth) {
	return {
		category : function(path) {
			console.log($location.path())
			api.post("checkpage", path).then(function(response) {
				console.log(response);
			});
		},
		product : function(path) {
			api.post("checkpage", path).then(function(response) {
				console.log(response);
			})
		},
		admin : function() {
			if (auth.user.admin) {
				api.post("checklogin", auth).then(function (response) {
					console.log(response)
				})
			}
		}
	}
	// if ($routeParams.page != "login" || $routeParams.page != "404") {
	// 	$location.path("/404");
	// }
})

app.run(function($rootScope, $location, auth, api) {
    $rootScope.$on( "$routeChangeStart", function(event, next, current) {
    	auth.get();
		if (next.controller == "adminController" || next.controller == "ordersController" || next.controller == "orderDetailController") {
			if(!auth.user.admin) {
				$location.path("/");
			}

			api.post("checklogin", auth.user.cred.session).then(function (response) {
				console.log(response)
				if (response != "1")
					$location.path("/")
			})

		}
      if (!USER.admin) {
        // no logged user, redirect to /login
        if ( next.templateUrl === "partials/login.html") {
        } else {
          $location.path("/login");
        }
      }
    });
  });

app.directive('showtab',
    function () {
        return {
            link: function (scope, element, attrs) {
                element.click(function(e) {
                    e.preventDefault();
                    $(element).tab('show');
                });
            }
        };
    });
<|endoftext|>


<commit_before>"use strict;"

var Gameboard = require('./gameboard'),
    Modes = require('./constants').Modes,
    PresetLevels = require('./constants').PresetLevels,
    PresetSetups = require('./constants').PresetSetups,
    DimValidator = require('./validators').BoardDimensions,
    MineValidator = require('./validators').MineCount,
    VERSION = require('./constants').VERSION,
    MAX_GRID_DIMENSIONS = require('./constants').MAX_GRID_DIMENSIONS,
    MINEABLE_SPACES_MULTIPLIER = require('./constants').MINEABLE_SPACES_MULTIPLIER,

    mineableSpaces = function(dim) { return ~~(Math.pow(dim, 2) * MINEABLE_SPACES_MULTIPLIER); },
    disableOption = function($el, undo) {
        if (undo == null) undo = false;
        $el[undo ? 'removeClass' : 'addClass']('disabled');
        $el.find("input").prop('readonly', !undo);
    },
    enableOption = function($el) { return disableOption($el, true); };

$(function(){

    var $possibleMines = $("#mine-count").siblings(".advice").find("span"),
        PRESET_PANEL_SELECTOR = "ul.preset > li:not(:has(label[for$='-mode']))",
        CUSTOM_PANEL_SELECTOR = "ul.custom > li:not(:has(label[for$='-mode']))";

    // setting initial value
    $possibleMines.html(mineableSpaces($("#dimensions").attr("placeholder")));
    $("#dimensions").siblings(".advice").find("span").html(MAX_GRID_DIMENSIONS + " x " + MAX_GRID_DIMENSIONS);

    $("#preset-mode").on('click', function() { enableOption($(PRESET_PANEL_SELECTOR)); disableOption($(CUSTOM_PANEL_SELECTOR)); }).click();
    $("#custom-mode").on('click', function() { enableOption($(CUSTOM_PANEL_SELECTOR)); disableOption($(PRESET_PANEL_SELECTOR)); });

    $.each($("label[for^='level-']"), function(_, label) {
        var level = $(label).attr('for').substring('level-'.length).toUpperCase(),
            dims = PresetSetups[level].dimensions,
            mines = PresetSetups[level].mines,
            $advice = $(label).find('.advice');
        $advice.html(" (" + dims + " x " + dims + ", " + mines + " mines)");
    });

    // onkeyup when choosing gameboard dimensions,
    // neighboring input should mirror new value,
    // and total possible mineable squares (dimensions ^ 2 -1)
    // be filled into a <span> below.
    $("#dimensions").on('keyup', function() {
        var $this = $(this);
        // update the 'mirror' <input>...
        $('#dimensions-mirror').val($this.val());
        // ...and the possible number of mines.
        $possibleMines.html(mineableSpaces($this.val()) + '.');
    });

    $("form").on("submit", function() {

        var mode = $("[name=mode-select]:checked").val(),
            gameOptions = {};

        if (mode === Modes.PRESET) {
            var level = $("[name=preset-level]:checked").val(),
                setup = Object.keys(PresetLevels)
                              .filter(function(pl) { return PresetLevels[pl] === level; })
                              .pop();
            gameOptions.isCustom = false;
            gameOptions.dimensions = PresetSetups[setup].dimensions;
            gameOptions.mines = PresetSetups[setup].mines;
        } else {
            // Modes.CUSTOM...
            gameOptions.isCustom = true;

            var d = $("#dimensions").val() || +$("#dimensions").attr("placeholder"),
                m = $("#mine-count").val() || +$("#mine-count").attr("placeholder");

            try {
                gameOptions.dimensions = DimValidator.validate(d) ? +d : 9;
                gameOptions.mines = MineValidator.validate(m, mineableSpaces(gameOptions.dimensions)) ? m : 1;
            } catch (e) {
                console.log("e: %o", e);
                $("#validation-warnings").html(e.message).show();
                return false;
            }
            // set the desired color theme...
            gameOptions.theme = $("#color-theme").val();
        }

        // set up <header> content...
        $("#mines-display").find("span").html(gameOptions.mines);
        $(".version").html(VERSION);

        window.gameboard = new Gameboard(gameOptions).render();

        $("#validation-warnings").hide();
        $("#options-card").hide();
        $("#board-card").fadeIn();

        return false;
    });

    $("#board-card").on("click", "a.replay", function() {
        // temporary, brute-force fix...
        // TODO: reset form and toggle visibility on the sections...
        window.location.reload();
    });

});<commit_msg>Focus first field on clicking of custom mode.<commit_after>"use strict;"

var Gameboard = require('./gameboard'),
    Modes = require('./constants').Modes,
    PresetLevels = require('./constants').PresetLevels,
    PresetSetups = require('./constants').PresetSetups,
    DimValidator = require('./validators').BoardDimensions,
    MineValidator = require('./validators').MineCount,
    VERSION = require('./constants').VERSION,
    MAX_GRID_DIMENSIONS = require('./constants').MAX_GRID_DIMENSIONS,
    MINEABLE_SPACES_MULTIPLIER = require('./constants').MINEABLE_SPACES_MULTIPLIER,

    mineableSpaces = function(dim) { return ~~(Math.pow(dim, 2) * MINEABLE_SPACES_MULTIPLIER); },
    disableOption = function($el, undo) {
        if (undo == null) undo = false;
        $el[undo ? 'removeClass' : 'addClass']('disabled');
        $el.find("input").prop('readonly', !undo);
    },
    enableOption = function($el) { return disableOption($el, true); };

$(function(){

    var $possibleMines = $("#mine-count").siblings(".advice").find("span"),
        PRESET_PANEL_SELECTOR = "ul.preset > li:not(:has(label[for$='-mode']))",
        CUSTOM_PANEL_SELECTOR = "ul.custom > li:not(:has(label[for$='-mode']))";

    // setting initial value
    $possibleMines.html(mineableSpaces($("#dimensions").attr("placeholder")));
    $("#dimensions").siblings(".advice").find("span").html(MAX_GRID_DIMENSIONS + " x " + MAX_GRID_DIMENSIONS);

    $("#preset-mode").on('click', function() { enableOption($(PRESET_PANEL_SELECTOR)); disableOption($(CUSTOM_PANEL_SELECTOR)); }).click();
    $("#custom-mode").on('click', function() { enableOption($(CUSTOM_PANEL_SELECTOR)); disableOption($(PRESET_PANEL_SELECTOR)); $("#dimensions").focus(); });

    $.each($("label[for^='level-']"), function(_, label) {
        var level = $(label).attr('for').substring('level-'.length).toUpperCase(),
            dims = PresetSetups[level].dimensions,
            mines = PresetSetups[level].mines,
            $advice = $(label).find('.advice');
        $advice.html(" (" + dims + " x " + dims + ", " + mines + " mines)");
    });

    // onkeyup when choosing gameboard dimensions,
    // neighboring input should mirror new value,
    // and total possible mineable squares (dimensions ^ 2 -1)
    // be filled into a <span> below.
    $("#dimensions").on('keyup', function() {
        var $this = $(this);
        // update the 'mirror' <input>...
        $('#dimensions-mirror').val($this.val());
        // ...and the possible number of mines.
        $possibleMines.html(mineableSpaces($this.val()) + '.');
    });

    $("form").on("submit", function() {

        var mode = $("[name=mode-select]:checked").val(),
            gameOptions = {};

        if (mode === Modes.PRESET) {
            var level = $("[name=preset-level]:checked").val(),
                setup = Object.keys(PresetLevels)
                              .filter(function(pl) { return PresetLevels[pl] === level; })
                              .pop();
            gameOptions.isCustom = false;
            gameOptions.dimensions = PresetSetups[setup].dimensions;
            gameOptions.mines = PresetSetups[setup].mines;
        } else {
            // Modes.CUSTOM...
            gameOptions.isCustom = true;

            var d = $("#dimensions").val() || +$("#dimensions").attr("placeholder"),
                m = $("#mine-count").val() || +$("#mine-count").attr("placeholder");

            try {
                gameOptions.dimensions = DimValidator.validate(d) ? +d : 9;
                gameOptions.mines = MineValidator.validate(m, mineableSpaces(gameOptions.dimensions)) ? m : 1;
            } catch (e) {
                console.log("e: %o", e);
                $("#validation-warnings").html(e.message).show();
                return false;
            }
            // set the desired color theme...
            gameOptions.theme = $("#color-theme").val();
        }

        // set up <header> content...
        $("#mines-display").find("span").html(gameOptions.mines);
        $(".version").html(VERSION);

        window.gameboard = new Gameboard(gameOptions).render();

        $("#validation-warnings").hide();
        $("#options-card").hide();
        $("#board-card").fadeIn();

        return false;
    });

    $("#board-card").on("click", "a.replay", function() {
        // temporary, brute-force fix...
        // TODO: reset form and toggle visibility on the sections...
        window.location.reload();
    });

});<|endoftext|>


<commit_before>(function() {
    var WEBATHENA_HOST = "https://webathena.mit.edu";
    var REALM = "ATHENA.MIT.EDU";
    var PRINCIPAL = [ "moira", "moira7.mit.edu" ];

    var LOGIN_ACTION = "Log In with Webathena";
    var LOGIN_ONGOING = "Logging In...";

    var OPTION_SPLIT = "In addition";
    var OPTION_REPLACE = "Instead";
    var OPTION_REPLACE_MULTIPLE = "Instead of ";

    // Currently logged-in user. (string)
    var username;

    // Ordered list of enabled mailboxes. (list of objects)
    var mailboxes;

    // Index of mailbox to replace, or -1 to split. (integer)
    var boxToReplace;

    /*
     * Query the server.
     *
     * @param endpoint endpoint to call, e.g. "/user/reset"
     * @param method method, "GET" or "PUT"
     * @param callback function to call on success; passed the
     *     JSON-decoded response as a single parameter
     */
    function apiquery( endpoint, method, callback ) {
        console.log( "Query to: " + endpoint );
        $.ajax({
            type: method,
            url: "./api/v1/" + endpoint + "?webathena=" +
                btoa( sessionStorage.getItem( "webathena" ) ),
        }).done( function( response ) {
            callback( JSON.parse( response ) );
        }).fail( function ( jqXHR ) {
            alert( "API Error", jqXHR.statusText, "danger" );
            console.log( "Request to API failed:" );
            console.log( jqXHR );
        });
    };

    /*
     * Display a visual alert to the user.
     *
     * @param title text to prefix the message in bold, or empty
     * @param message the message to display; text only
     * @param type one of "danger", "warning", "info", "success"; controls the
     *        color of the alert
     * @param an optional tag, added as a class, to allow for batch dismissal
     *        via $( ".tag" ).alert( "close" );
     */
    function alert( title, message, type, tag ) {
        var element = $( "#alert" ).clone();

        element.prop( "id", "" );
        element.find( ".error-title" ).text( title );
        element.find( ".error-text" ).text( message );

        if ( typeof( tag ) !== "undefined" ) element.addClass( tag );
        element.addClass( "alert-" + type );
        element.removeClass( "hidden" );
        $( "#alert" ).after( element );
    }

    /*
     * Update the UI element displaying the "Instead"/"In addition" message.
     */
    function updateSplitUI() {
        if ( boxToReplace == -1 )
            $( "#split-option" ).text( OPTION_SPLIT );
        else if ( mailboxes.length == 1 )
            $( "#split-option" ).text( OPTION_REPLACE );
        else {
            var humanTypes = { "EXCHANGE" : "Exchange",
                               "IMAP" : "IMAP",
                               "SMTP" : "External" }
            var type = mailboxes[ boxToReplace ].type;
            $( "#split-option" ).text( OPTION_REPLACE_MULTIPLE +
                humanTypes[ type ] );
        }
    }

    /*
     * Helper function to show or hide the entry for a single mailbox.
     *
     * @param selector jQuery selector for the mailbox's line
     * @param mailbox object describing mailbox, from server response
     * @param split true iff mail is being split
     */
    function mailboxentry( selector, mailbox, split ) {
        if ( mailbox == null ) {
            $( selector ).hide();
            return;
        }

        $( selector ).show();
        $( selector ).find( ".fwdaddr" ).text( mailbox.address );
        if ( split )
            $( selector ).find( ".del" ).show();
        else
            $( selector ).find( ".del" ).hide();
    }

    /*
     * Helper function to guess URL of email provider given an email address.
     *
     * @param address address to examine
     */
    function guessprovider( address ) {
        var suffix = address.split("@")[1];
        return "https://www." + suffix + "/";
    }

    /*
     * Refresh the UI with a de-stringified (dictionary) response from the
     * server.
     *
     * @param response data from server
     */
    function updateui( response ) {
        console.log( response );
        // update lastmod UI elements
        $( "#lastmod-time" ).timeago( "update", response.modtime );
        $( "#lastmod-user" ).text( response.modby );

        // extract three mailboxes from response data
        var exchange = null;
        var imap = null;
        var smtp = null;
        for ( var i = 0; i < response.boxes.length; i++ ) {
            if ( !response.boxes[i].enabled )
                continue;

            if ( response.boxes[i].type == "EXCHANGE" )
                exchange = response.boxes[i];
            else if ( response.boxes[i].type == "IMAP" )
                imap = response.boxes[i];
            else if ( response.boxes[i].type == "SMTP" )
                smtp = response.boxes[i];
        }

        // populate global list of mailboxes, in fixed order
        mailboxes = new Array();
        for ( var i = 0; i < response.boxes.length; i++ ) {
            if ( response.boxes[i].enabled == false )    continue;
            if ( response.boxes[i].type == "EXCHANGE" )
                mailboxes = mailboxes.concat( [ response.boxes[i] ] );
        }
        for ( var i = 0; i < response.boxes.length; i++ ) {
            if ( response.boxes[i].enabled == false )    continue;
            if ( response.boxes[i].type == "IMAP" )
                mailboxes = mailboxes.concat( [ response.boxes[i] ] );
        }
        for ( var i = 0; i < response.boxes.length; i++ ) {
            if ( response.boxes[i].enabled == false )    continue;
            if ( response.boxes[i].type == "SMTP" )
                mailboxes = mailboxes.concat( [ response.boxes[i] ] );
        }

        // determine if split mailboxes are in use
        var split = ( mailboxes.length > 1 );

        // update UI to display or hide three mailboxes
        mailboxentry( "#exchange", exchange, split );
        mailboxentry( "#imap", imap, split );
        mailboxentry( "#external", smtp, split );

        // initialize splitting UI
        boxToReplace = 0;
        updateSplitUI();

        $( "#new-address" ).val("");
    }

    /*
     * Update the UI to reflect that the user is logged in.
     *
     * @param session r.session returned by Webathena
     */
    function logmein( session ) {
        username = session.cname.nameString[0];
	// Dismiss earlier login errors
	$( ".alert-login" ).alert( "close" );

	// Put email address into relevant divs
	$( ".thisuser" ).text( username + "@mit.edu" );

	// Disable login button, just in case
	$( "#login" ).attr( "disabled", true);
	$( "#login" ).text( LOGIN_ONGOING );

	// Query to load results from API
        apiquery( username, "GET", function( response ) {
            updateui( response );
	    $( "#landing" ).addClass( "hidden" );
	    $( "#app" ).removeClass( "hidden" );
	});
    }

    /* Reset Page on Load */
    $( ".timeago" ).timeago();
    $( "#split-option" ).tooltip();

    var login = $( "#login" );
    login.attr( "disabled", false );
    login.text( LOGIN_ACTION );
    $( "#landing" ).removeClass( "hidden" );

    var session = JSON.parse( sessionStorage.getItem( "webathena" ) );
    if ( session !== null ) {
	console.log( "Loading session from storage..." );
	logmein( session );
    }

    /* Button Handlers */
    login.click( function( event ) {
        event.preventDefault();
	login.attr( "disabled", true );
        login.text( LOGIN_ONGOING );

        WinChan.open({
            url: WEBATHENA_HOST + "/#!request_ticket_v1",
            relay_url: WEBATHENA_HOST + "/relay.html",
            params: {
                realm: REALM,
                principal: PRINCIPAL
            }
        }, function( err, r ) {
            if ( err ) {
                login.attr( "disabled", false );
                login.text( LOGIN_ACTION );

                console.log( "Webathena returned err: " + err );
                if ( err.indexOf( "closed window" ) != -1 ) {
                    // User closed Webathena window. Take no action.
                } else {
                    alert( "Achtung!",
                           "An error occurred while communicating with Webathena.",
                           "danger", "alert-login" );
                }
                return;
            }
            if ( r.status !== "OK" ) {
                login.attr( "disabled", false );
                login.text( LOGIN_ACTION );

                console.log( "Webathena returned r (" + r.status + "}:");
                console.log( r );
                if ( r.status == "DENIED" ) {
                    alert( "Login Failed.",
                           "I need \"mailing lists and groups\" access in order " +
                           "to change your forwarding settings.",
                           "warning", "alert-login");
                } else {
                    alert( "Achtung!",
                           "An error occurred while communicating with Webathena.",
                           "danger", "alert-login" );
                }
                return;
            }

            // Success! Put session information into a cookie and update UI
            console.log( "Login succeeded." );
            sessionStorage.setItem( "webathena", JSON.stringify( r.session ) );
            logmein( r.session );
        });
    });

    $( "#split-option" ).click( function( event ) {
        event.preventDefault();

        boxToReplace++;
        if ( boxToReplace >= mailboxes.length )
            if ( mailboxes.length == 1 )    // only one forwarder
                boxToReplace = -1;          // go back to "in addition"
            else                    // multiple forwarders
                boxToReplace = 0;   // only cycle through "instead"s

        updateSplitUI();
    });

    $( "#restore-default" ).click( function( event ) {
        event.preventDefault();
        apiquery( username + "/reset", "PUT", updateui );
    });

    $( "#update-form" ).submit( function( event ) {
        event.preventDefault();

        var newAddress = $( "#new-address" ).val();
        usedAddress = false;

        var query = username + "/";

        if ( newAddress.match(/@EXCHANGE\.MIT\.EDU$/i) ||
             newAddress.match(/@PO.*\.MIT\.EDU$/i) ) {
            query += newAddress + "/";
            usedAddress = true;
        }

        for ( var i = 0; i < mailboxes.length; i++ ) {
            if ( i != boxToReplace )
                query += mailboxes[i].address + "/";
        }

        if ( !usedAddress )
            query += newAddress + "/";
        query = query.substring( 0, query.length - 1 ); // trim trailing slash
        apiquery( query, "PUT", updateui );
    });

    $( "#exchange" ).find( ".del" ).click( function( event ) {
        event.preventDefault();

        var addr = "";
        for ( var i = 0; i < mailboxes.length; i++ )
            if ( mailboxes[i].type != "EXCHANGE" ) {
                apiquery( username + "/" + mailboxes[i].address,
                    "PUT", updateui );
                return
            }
    });
    $( "#imap" ).find( ".del" ).click( function( event ) {
        event.preventDefault();

        var addr = "";
        for ( var i = 0; i < mailboxes.length; i++ )
            if ( mailboxes[i].type != "IMAP" ) {
                apiquery( username + "/" + mailboxes[i].address,
                    "PUT", updateui );
                return
            }
    });
    $( "#exernal" ).find( ".del" ).click( function( event ) {
        event.preventDefault();

        var addr = "";
        for ( var i = 0; i < mailboxes.length; i++ )
            if ( mailboxes[i].type != "SMTP" ) {
                apiquery( username + "/" + mailboxes[i].address,
                    "PUT", updateui );
                return
            }
    });
})();
<commit_msg>Clean up app.js<commit_after>(function() {
    var WEBATHENA_HOST = "https://webathena.mit.edu";
    var REALM = "ATHENA.MIT.EDU";
    var PRINCIPAL = [ "moira", "moira7.mit.edu" ];

    var LOGIN_ACTION = "Log In with Webathena";
    var LOGIN_ONGOING = "Logging In...";

    var OPTION_SPLIT = "In addition";
    var OPTION_REPLACE = "Instead";
    var OPTION_REPLACE_MULTIPLE = "Instead of ";

    // Object representing Webathena session
    var session;

    // Currently logged-in user. (string)
    var username;

    // Ordered list of enabled mailboxes. (list of objects)
    var mailboxes;

    // Index of mailbox to replace, or -1 to split. (integer)
    var boxToReplace;

    /*
     * Query the server.
     *
     * @param endpoint endpoint to call, e.g. "/user/reset"
     * @param method method, "GET" or "PUT"
     * @param callback function to call on success; passed the
     *     JSON-decoded response as a single parameter
     */
    function apiQuery( endpoint, method, callback ) {
        console.log( "Query to: " + endpoint );
        $.ajax({
            type: method,
            url: "./api/v1/" + endpoint + "?webathena=" +
                btoa( sessionStorage.getItem( "webathena" ) ),
        }).done( function( response ) {
            callback( JSON.parse( response ) );
        }).fail( function ( jqXHR ) {
            alert( "API Error", jqXHR.statusText, "danger" );
            console.log( "Request to API failed:" );
            console.log( jqXHR );
        });
    };

    /*
     * Display a visual alert to the user.
     *
     * @param title text to prefix the message in bold, or empty
     * @param message the message to display; text only
     * @param type one of "danger", "warning", "info", "success"; controls the
     *        color of the alert
     * @param an optional tag, added as a class, to allow for batch dismissal
     *        via $( ".tag" ).alert( "close" );
     */
    function alert( title, message, type, tag ) {
        var element = $( "#alert" ).clone();

        element.prop( "id", "" );
        element.find( ".error-title" ).text( title );
        element.find( ".error-text" ).text( message );

        if ( typeof( tag ) !== "undefined" ) element.addClass( tag );
        element.addClass( "alert-" + type );
        element.removeClass( "hidden" );
        $( "#alert" ).after( element );
    }

    /*
     * Update the UI element displaying the "Instead"/"In addition" message.
     */
    function updateSplitUI() {
        if ( boxToReplace == -1 )
            $( "#split-option" ).text( OPTION_SPLIT );
        else if ( mailboxes.length == 1 )
            $( "#split-option" ).text( OPTION_REPLACE );
        else {
            var humanTypes = { "EXCHANGE" : "Exchange",
                               "IMAP" : "IMAP",
                               "SMTP" : "External" }
            var type = mailboxes[ boxToReplace ].type;
            $( "#split-option" ).text( OPTION_REPLACE_MULTIPLE +
                humanTypes[ type ] );
        }
    }

    /*
     * Helper function to show or hide the entry for a single mailbox.
     *
     * @param selector jQuery selector for the mailbox's line
     * @param mailbox object describing mailbox, from server response
     */
    function updateMailboxUI( selector, mailbox ) {
        if ( mailbox == null ) {    // mailbox is hidden
            $( selector ).hide();
            return;
        }

        // otherwise, show mailbox
        $( selector ).show();
        $( selector ).find( ".fwdaddr" ).text( mailbox.address );

        // only show delete button if multiple mailboxes in use
        if ( mailboxes.length == 1 )
            $( selector ).find( ".del" ).hide();
        else
            $( selector ).find( ".del" ).show();
    }

    /*
     * Helper function to guess URL of email provider given an email address.
     *
     * @param address address to examine
     */
    function guessprovider( address ) {
        var suffix = address.split("@")[1];
        return "https://www." + suffix + "/";
    }

    /*
     * Refresh the UI with a de-stringified (dictionary) response from the
     * server.
     *
     * @param response JSON data from server
     */
    function updateUI( response ) {
        // update lastmod UI elements
        $( "#lastmod-time" ).timeago( "update", response.modtime );
        $( "#lastmod-user" ).text( response.modby );

        // extract three mailboxe types from response
        var exchange = null;
        var imap = null;
        var smtp = null;
        for ( var i = 0; i < response.boxes.length; i++ ) {
            if ( !response.boxes[i].enabled )
                continue;

            if ( response.boxes[i].type == "EXCHANGE" )
                exchange = response.boxes[i];
            else if ( response.boxes[i].type == "IMAP" )
                imap = response.boxes[i];
            else if ( response.boxes[i].type == "SMTP" )
                smtp = response.boxes[i];
        }

        // populate global list of mailboxes, in same order as UI list
        mailboxes = new Array();
        for ( var i = 0; i < response.boxes.length; i++ ) {
            if ( response.boxes[i].enabled == false )    continue;
            if ( response.boxes[i].type == "EXCHANGE" )
                mailboxes = mailboxes.concat( [ response.boxes[i] ] );
        }
        for ( var i = 0; i < response.boxes.length; i++ ) {
            if ( response.boxes[i].enabled == false )    continue;
            if ( response.boxes[i].type == "IMAP" )
                mailboxes = mailboxes.concat( [ response.boxes[i] ] );
        }
        for ( var i = 0; i < response.boxes.length; i++ ) {
            if ( response.boxes[i].enabled == false )    continue;
            if ( response.boxes[i].type == "SMTP" )
                mailboxes = mailboxes.concat( [ response.boxes[i] ] );
        }

        // determine if split mailboxes are in use
        var split = ( mailboxes.length > 1 );

        // update UI to display or hide each kind of mailbox
        updateMailboxUI( "#exchange", exchange );
        updateMailboxUI( "#imap", imap );
        updateMailboxUI( "#external", smtp );

        // initialize split/replace UI
        boxToReplace = 0;
        updateSplitUI();

        $( "#new-address" ).val("");
    }

    /*
     * Update the UI to reflect that the user is logged in.
     *
     * @param session r.session returned by Webathena
     */
    function logmein( session ) {
        username = session.cname.nameString[0];
        // Dismiss earlier login errors
        $( ".alert-login" ).alert( "close" );

        // Put email address into relevant divs
        $( ".thisuser" ).text( username + "@mit.edu" );

        // Disable login button, just in case
        $( "#login" ).attr( "disabled", true);
        $( "#login" ).text( LOGIN_ONGOING );

        // Query to load results from API
            apiQuery( username, "GET", function( response ) {
                updateUI( response );
                $( "#landing" ).addClass( "hidden" );
                $( "#app" ).removeClass( "hidden" );
        });
    }

    /* On Load: Initialize Page */
    $( ".timeago" ).timeago();
    $( "#split-option" ).tooltip();

    var login = $( "#login" );
    login.attr( "disabled", false );
    login.text( LOGIN_ACTION );
    $( "#landing" ).removeClass( "hidden" );

    session = JSON.parse( sessionStorage.getItem( "webathena" ) );
    if ( session !== null ) {
        console.log( "Loading session from storage..." );
        logmein( session );
    }

    /* Button Handlers */
    login.click( function( event ) {
        event.preventDefault();
	login.attr( "disabled", true );
        login.text( LOGIN_ONGOING );

        WinChan.open({
            url: WEBATHENA_HOST + "/#!request_ticket_v1",
            relay_url: WEBATHENA_HOST + "/relay.html",
            params: {
                realm: REALM,
                principal: PRINCIPAL
            }
        }, function( err, r ) {
            if ( err ) {
                login.attr( "disabled", false );
                login.text( LOGIN_ACTION );

                console.log( "Webathena returned err: " + err );
                if ( err.indexOf( "closed window" ) != -1 ) {
                    // User closed Webathena window. Take no action.
                } else {
                    alert( "Achtung!",
                           "An error occurred while communicating with Webathena.",
                           "danger", "alert-login" );
                }
                return;
            }
            if ( r.status !== "OK" ) {
                login.attr( "disabled", false );
                login.text( LOGIN_ACTION );

                console.log( "Webathena returned r (" + r.status + "}:");
                console.log( r );
                if ( r.status == "DENIED" ) {
                    alert( "Login Failed.",
                           "I need \"mailing lists and groups\" access in order " +
                           "to change your forwarding settings.",
                           "warning", "alert-login");
                } else {
                    alert( "Achtung!",
                           "An error occurred while communicating with Webathena.",
                           "danger", "alert-login" );
                }
                return;
            }

            // Success! Put session information into a cookie and update UI
            console.log( "Login succeeded." );
            sessionStorage.setItem( "webathena", JSON.stringify( r.session ) );
            logmein( r.session );
        });
    });

    $( "#split-option" ).click( function( event ) {
        event.preventDefault();

        boxToReplace++;
        if ( boxToReplace >= mailboxes.length )
            if ( mailboxes.length == 1 )    // only one forwarder
                boxToReplace = -1;          // go back to split
            else                    // multiple forwarders
                boxToReplace = 0;   // only cycle through replacements

        updateSplitUI();
    });

    $( "#restore-default" ).click( function( event ) {
        event.preventDefault();
        apiQuery( username + "/reset", "PUT", updateUI );
    });

    $( "#update-form" ).submit( function( event ) {
        event.preventDefault();

        var newAddress = $( "#new-address" ).val();
        usedAddress = false;

        var query = username + "/";

        if ( newAddress.match(/@EXCHANGE\.MIT\.EDU$/i) ||
             newAddress.match(/@PO.*\.MIT\.EDU$/i) ) {
            query += newAddress + "/";
            usedAddress = true;
        }

        for ( var i = 0; i < mailboxes.length; i++ ) {
            if ( i != boxToReplace )
                query += mailboxes[i].address + "/";
        }

        if ( !usedAddress )
            query += newAddress + "/";
        query = query.substring( 0, query.length - 1 ); // trim trailing slash
        apiQuery( query, "PUT", updateUI );
    });

    var del = function( type ) {
        return function( event ) {
            event.preventDefault();

            var addr = "";
            for ( var i = 0; i < mailboxes.length; i++ )
                if ( mailboxes[i].type != "EXCHANGE" ) {
                    apiQuery( username + "/" + mailboxes[i].address,
                        "PUT", updateUI );
                    return
                }
        };
    }

    $( "#exchange" ).find( ".del" ).click( del( "EXCHANGE" ) );
    $( "#imap" ).find( ".del" ).click( del( "IMAP" ) );
    $( "#exernal" ).find( ".del" ).click( del( "SMTP" ) );
})();
<|endoftext|>


<commit_before>var app = angular.module('shoppingCart', ['localStorage']);

app.controller('CartController', ['$scope', '$store', function($scope, $store) {

	$store.bind($scope, 'cart', []);
	//$store.set('cart', []);

	$scope.invoice = {
		//Dit wordt later vervangen door een functie die alle items uit de database haalt.
		items : [{
			voorraad: 0,
			naam: 'Banaan',
			prijs: 19.95,
			id: 1001
		},
		{
			voorraad: 5,
			naam: 'Kip',
			prijs: 9.95,
			id: 1002
		},
		{
			voorraad: 45,
			naam: 'Kat',
			prijs: 89.95,
			id: 1003
		}],
		cart: $scope.cart
	};

	$scope.addToCart = function(item) {
		//check if there is already an item in the cart
		if($scope.cart.length > 0) {

			var gevonden = false;

			angular.forEach($scope.cart, function(cart, key) {
				//check if item is already in the cart, if yes icrement quantity
				if(item.id == cart.id) {
					cart.hoeveelheid++;
					gevonden = true;
				}

			});

			if(!gevonden) {
				item.hoeveelheid = 1;
				$scope.cart.push(item);
			}

		} else {
			item.hoeveelheid = 1;
			$scope.cart.push(item);

		}

		$store.set('cart', $scope.cart);

	};

	$scope.clear = function() {

		angular.forEach($scope.cart, function(item, key) {
			$scope.cart.splice(key, 1);
		});

	};

	$scope.removeItem = function(index) {
		$scope.invoice.items.splice(index, 1);
	};

	$scope.total = function() {

		var total = 0;

		angular.forEach($scope.invoice.cart, function(item) {
				total += item.prijs * item.hoeveelheid;
		});

		return total;
	};

}]);

app.controller('CheckoutController', ['$scope', '$store', function($scope, $store) {

	$scope.cart = $store.get('cart');

	$scope.total = function() {

		var total = 0;

		angular.forEach($scope.cart, function(item) {
				total += item.prijs * item.hoeveelheid;
		});

		return total;
	};

}]);<commit_msg>Added clear function<commit_after>var app = angular.module('shoppingCart', ['localStorage']);

app.controller('CartController', ['$scope', '$store', function($scope, $store) {

	$store.bind($scope, 'cart', []);
	//$store.set('cart', []);

	$scope.invoice = {
		//Dit wordt later vervangen door een functie die alle items uit de database haalt.
		items : [{
			voorraad: 0,
			naam: 'Banaan',
			prijs: 19.95,
			id: 1001
		},
		{
			voorraad: 5,
			naam: 'Kip',
			prijs: 9.95,
			id: 1002
		},
		{
			voorraad: 45,
			naam: 'Kat',
			prijs: 89.95,
			id: 1003
		}],
		cart: $scope.cart
	};

	$scope.addToCart = function(item) {
		//check if there is already an item in the cart
		if($scope.cart.length > 0) {

			var gevonden = false;

			angular.forEach($scope.cart, function(cart, key) {
				//check if item is already in the cart, if yes icrement quantity
				if(item.id == cart.id) {
					cart.hoeveelheid++;
					gevonden = true;
				}

			});

			if(!gevonden) {
				item.hoeveelheid = 1;
				$scope.cart.push(item);
			}

		} else {
			item.hoeveelheid = 1;
			$scope.cart.push(item);

		}

		$store.set('cart', $scope.cart);

	};

	$scope.clear = function() {

		angular.forEach($scope.cart[0], function(item, key) {
			$scope.cart.splice(key, 1);
		});

	};

	$scope.removeItem = function(index) {
		$scope.invoice.items.splice(index, 1);
	};

	$scope.total = function() {

		var total = 0;

		angular.forEach($scope.invoice.cart, function(item) {
				total += item.prijs * item.hoeveelheid;
		});

		return total;
	};

}]);

app.controller('CheckoutController', ['$scope', '$store', function($scope, $store) {

	$scope.cart = $store.get('cart');

	$scope.total = function() {

		var total = 0;

		angular.forEach($scope.cart, function(item) {
				total += item.prijs * item.hoeveelheid;
		});

		return total;
	};

}]);<|endoftext|>


<commit_before>window.App = {};
App.refreshTime = 1000;
App.requestMaxValue = 0;
App.bandwidthMaxValue = 0;
App.oldStats = {};
App.newStats = {};

App.getStats = function(){
	$.getJSON("/stats", function(data){
		App.oldStats = App.newStats;
		App.newStats = data;
	})
}

App.calcHitRatio = function(){
	delta_client_req = App.newStats.client_req.value - App.oldStats.client_req.value;
	delta_cache_hit = App.newStats.cache_hit.value - App.oldStats.cache_hit.value;
	hitRatio = (delta_cache_hit*100)/delta_client_req;
	return Math.round(hitRatio);
}

App.calcAverageHitRatio = function(){
	hitRatio = App.newStats.cache_hit.value * 100 / App.oldStats.client_req.value;
	return Math.round(hitRatio);
}

App.updateHitRatioGauge = function(){
	App.hitRatioGauge.refresh(App.calcHitRatio());
}

App.updateRequestGauge = function() {
	requests_per_second = App.newStats.client_req.value - App.oldStats.client_req.value;
	if(requests_per_second > App.requestMaxValue){
		App.requestMaxValue = requests_per_second;
	}
	App.requestGauge.refresh(requests_per_second, App.requestMaxValue);
}

App.updateBandwidthGauge = function(){
	bandwidth = Math.round(((App.newStats.s_hdrbytes.value + App.newStats.s_bodybytes.value) - (App.oldStats.s_hdrbytes.value + App.oldStats.s_bodybytes.value)) / 1024 / 1024);
	if(bandwidth > App.bandwidthMaxValue){
		App.bandwidthMaxValue = bandwidth;
	}
	App.bandwidthGauge.refresh(bandwidth, App.bandwidthMaxValue);
}

App.updateData = function(){
	App.getStats();
	App.updateHitRatioGauge();
	App.updateRequestGauge();
	App.updateBandwidthGauge();
	App.builMetricsTable("cache", App.getCacheMetrics());
	App.builMetricsTable("traffic", App.getTrafficMetrics());
	App.builMetricsTable("backend", App.getBackendMetrics());
}

App.getCacheMetrics = function() {
	var hits_ratio = {
		label: "Hits Ratio",
		new_value: App.calcHitRatio(),
		average_value: App.calcAverageHitRatio()
	}
	var hits_qty = {
		label: "Hits Qty.",
		new_value: nFormatter(App.newStats.cache_hit.value - App.oldStats.cache_hit.value),
		average_value: nFormatter(App.newStats.cache_hit.value / App.newStats.uptime.value)
	}
	var miss_qty = {
		label: "Miss Qty.",
		new_value: nFormatter(App.newStats.cache_miss.value - App.oldStats.cache_miss.value),
		average_value: nFormatter(App.newStats.cache_miss.value / App.newStats.uptime.value)
	}
	var obj_cache = {
		label: "Objs. in Cache",
		new_value: nFormatter(App.newStats.n_object.value - App.oldStats.n_object.value),
		average_value: nFormatter(App.newStats.n_object.value)
	}
	return [hits_ratio, hits_qty, miss_qty, obj_cache]
}

App.getTrafficMetrics = function() {
	var client_conn = {
		label: "Connections",
		new_value: nFormatter(App.newStats.client_conn.value - App.oldStats.client_conn.value),
		average_value: nFormatter(App.newStats.client_conn.value / App.newStats.uptime.value)
	}
	var client_req = {
		label: "Requests",
		new_value: nFormatter(App.newStats.client_req.value - App.oldStats.client_req.value),
		average_value: nFormatter(App.newStats.client_req.value / App.newStats.uptime.value)
	}
	var req_per_conn = {
		label: "Req / Conn",
		new_value: nFormatter((App.newStats.client_req.value - App.oldStats.client_req.value) /(App.newStats.client_conn.value - App.oldStats.client_conn.value) ),
		average_value: nFormatter(App.newStats.client_req.value / App.newStats.client_conn.value)
	}

	var bandwith = {
		label: "Bandwidth",
		new_value: nFormatter((App.newStats.s_hdrbytes.value + App.newStats.s_bodybytes.value) - (App.oldStats.s_hdrbytes.value + App.oldStats.s_bodybytes.value)),
		average_value: nFormatter((App.newStats.s_hdrbytes.value + App.newStats.s_bodybytes.value) / App.newStats.uptime.value)
	}

	return [client_conn, client_req, req_per_conn, bandwith]

}

App.getBackendMetrics = function() {
	var backend_conn = {
		label: "Connections",
		new_value: nFormatter(App.newStats.backend_conn.value - App.oldStats.backend_conn.value),
		average_value: nFormatter(App.newStats.backend_conn.value / App.newStats.uptime.value)
	}
	var backend_fail = {
		label: "Fails",
		new_value: nFormatter(App.newStats.backend_fail.value - App.oldStats.backend_fail.value),
		average_value: nFormatter(App.newStats.backend_fail.value / App.newStats.uptime.value)
	}
	var backend_reuse = {
		label: "Reuse",
		new_value: nFormatter(App.newStats.backend_reuse.value - App.oldStats.backend_reuse.value),
		average_value: nFormatter(App.newStats.backend_reuse.value / App.newStats.uptime.value)
	}
	var backend_fetch = {
		label: "Fetch & Pass",
		new_value: nFormatter(App.newStats.s_pass.value + App.newStats.s_fetch.value - App.oldStats.s_fetch.value - App.oldStats.s_pass.value),
		average_value: nFormatter((App.newStats.s_pass.value + App.newStats.s_fetch.value) / App.newStats.uptime.value)
	}
	return [backend_conn, backend_fetch, backend_fail, backend_reuse]
}

App.builMetricsTable = function(table_id, values_object){
	var source   = $("#metrics-table-template").html();
	var context = { metric: values_object};
	var template = Handlebars.compile(source);
	var html = template(context);
	$("#"+table_id+"-metrics-table").html(html);
}

$(function(){
	App.hitRatioGauge = new JustGage({
	    id: "hit-ratio",
	    value: 0,
	 	levelColors: ["#f70000","#f9c800","#a8d600"],
	    min: 0,
	    max: 100,
	    title: " ",
		label: "%"
	  });

	App.requestGauge = new JustGage({
	    id: "request-gauge",
	    value: 0,
	    min: 0,
	    max: 100,
	    title: " ",
		label: "per second"
	  });

	App.bandwidthGauge = new JustGage({
	    id: "bandwidth-gauge",
	    value: 0,
	    min: 0,
	    max: 100,
	    title: " ",
		label: "Mbps"
	  });

	setInterval(App.updateData,App.refreshTime);

});

function nFormatter(num) {
     if (num >= 1000000000) {
        return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
     }
     if (num >= 1000000) {
        return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
     }
     if (num >= 1000) {
        return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
     }
     return Math.round(num);
}<commit_msg>first commit<commit_after>window.App = {};
App.refreshTime = 1000;
App.requestMaxValue = 0;
App.bandwidthMaxValue = 0;
App.oldStats = {};
App.newStats = {};

App.getStats = function(){
	$.getJSON("/stats", function(data){
		App.oldStats = App.newStats;
		App.newStats = data;
	})
}

App.calcHitRatio = function(){
	delta_client_req = App.newStats.client_req.value - App.oldStats.client_req.value;
	delta_cache_hit = App.newStats.cache_hit.value - App.oldStats.cache_hit.value;
	hitRatio = (delta_cache_hit*100)/delta_client_req;
	return Math.round(hitRatio);
}

App.calcAverageHitRatio = function(){
	hitRatio = App.newStats.cache_hit.value * 100 / App.oldStats.client_req.value;
	return Math.round(hitRatio);
}

App.updateHitRatioGauge = function(){
	App.hitRatioGauge.refresh(App.calcHitRatio());
}

App.updateRequestGauge = function() {
	requests_per_second = App.newStats.client_req.value - App.oldStats.client_req.value;
	if(requests_per_second > App.requestMaxValue){
		App.requestMaxValue = requests_per_second;
	}
	App.requestGauge.refresh(requests_per_second, App.requestMaxValue);
}

App.updateBandwidthGauge = function(){
	bandwidth = Math.round(((App.newStats.s_hdrbytes.value + App.newStats.s_bodybytes.value) - (App.oldStats.s_hdrbytes.value + App.oldStats.s_bodybytes.value)) / 1024 / 1024);
	if(bandwidth > App.bandwidthMaxValue){
		App.bandwidthMaxValue = bandwidth;
	}
	App.bandwidthGauge.refresh(bandwidth, App.bandwidthMaxValue);
}

App.updateData = function(){
	App.getStats();
	App.updateHitRatioGauge();
	App.updateRequestGauge();
	App.updateBandwidthGauge();
	App.builMetricsTable("cache", App.getCacheMetrics());
	App.builMetricsTable("traffic", App.getTrafficMetrics());
	App.builMetricsTable("backend", App.getBackendMetrics());
}

App.getCacheMetrics = function() {
	var hits_ratio = {
		label: "Hits Ratio",
		new_value: App.calcHitRatio(),
		average_value: App.calcAverageHitRatio()
	}
	var hits_qty = {
		label: "Hits Qty.",
		new_value: nFormatter(App.newStats.cache_hit.value - App.oldStats.cache_hit.value),
		average_value: nFormatter(App.newStats.cache_hit.value / App.newStats.uptime.value)
	}
	var miss_qty = {
		label: "Miss Qty.",
		new_value: nFormatter(App.newStats.cache_miss.value - App.oldStats.cache_miss.value),
		average_value: nFormatter(App.newStats.cache_miss.value / App.newStats.uptime.value)
	}
	var obj_cache = {
		label: "Objs. in Cache",
		new_value: nFormatter(App.newStats.n_object.value - App.oldStats.n_object.value),
		average_value: nFormatter(App.newStats.n_object.value)
	}
	return [hits_ratio, hits_qty, miss_qty, obj_cache]
}

App.getTrafficMetrics = function() {
	var client_conn = {
		label: "Connections",
		new_value: nFormatter(App.newStats.client_conn.value - App.oldStats.client_conn.value),
		average_value: nFormatter(App.newStats.client_conn.value / App.newStats.uptime.value)
	}
	var client_req = {
		label: "Requests",
		new_value: nFormatter(App.newStats.client_req.value - App.oldStats.client_req.value),
		average_value: nFormatter(App.newStats.client_req.value / App.newStats.uptime.value)
	}
	var req_per_conn = {
		label: "Req / Conn",
		new_value: nFormatter((App.newStats.client_req.value - App.oldStats.client_req.value) /(App.newStats.client_conn.value - App.oldStats.client_conn.value) ),
		average_value: nFormatter(App.newStats.client_req.value / App.newStats.client_conn.value)
	}

	var bandwith = {
		label: "Bandwidth",
		new_value: nFormatter((App.newStats.s_hdrbytes.value + App.newStats.s_bodybytes.value) - (App.oldStats.s_hdrbytes.value + App.oldStats.s_bodybytes.value)),
		average_value: nFormatter((App.newStats.s_hdrbytes.value + App.newStats.s_bodybytes.value) / App.newStats.uptime.value)
	}

	return [client_conn, client_req, req_per_conn, bandwith]

}

App.getBackendMetrics = function() {
	var backend_conn = {
		label: "Connections",
		new_value: nFormatter(App.newStats.backend_conn.value - App.oldStats.backend_conn.value),
		average_value: nFormatter(App.newStats.backend_conn.value / App.newStats.uptime.value)
	}
	var backend_fail = {
		label: "Fails",
		new_value: nFormatter(App.newStats.backend_fail.value - App.oldStats.backend_fail.value),
		average_value: nFormatter(App.newStats.backend_fail.value / App.newStats.uptime.value)
	}
	var backend_reuse = {
		label: "Reuse",
		new_value: nFormatter(App.newStats.backend_reuse.value - App.oldStats.backend_reuse.value),
		average_value: nFormatter(App.newStats.backend_reuse.value / App.newStats.uptime.value)
	}
	var backend_fetch = {
		label: "Fetch & Pass",
		new_value: nFormatter(App.newStats.s_pass.value + App.newStats.s_fetch.value - App.oldStats.s_fetch.value - App.oldStats.s_pass.value),
		average_value: nFormatter((App.newStats.s_pass.value + App.newStats.s_fetch.value) / App.newStats.uptime.value)
	}
	return [backend_conn, backend_fetch, backend_fail, backend_reuse]
}

App.builMetricsTable = function(table_id, values_object){
	var source   = $("#metrics-table-template").html();
	var context = { metric: values_object};
	var template = Handlebars.compile(source);
	var html = template(context);
	$("#"+table_id+"-metrics-table").html(html);
}

$(function(){
	App.hitRatioGauge = new JustGage({
	    id: "hit-ratio",
	    value: 0,
	 	levelColors: ["#f70000","#f9c800","#a8d600"],
	    min: 0,
	    max: 100,
	    title: " ",
		label: "%"
	  });

	App.requestGauge = new JustGage({
	    id: "request-gauge",
	    value: 0,
	    min: 0,
	    max: 100,
	    title: " ",
		label: "per second"
	  });

	App.bandwidthGauge = new JustGage({
	    id: "bandwidth-gauge",
	    value: 0,
	    min: 0,
	    max: 100,
	    title: " ",
		levelColors: ["#40b7f1","#40b7f1","#40b7f1"],
		label: "Mbps"
	  });

	setInterval(App.updateData,App.refreshTime);

});

function nFormatter(num) {
     if (num >= 1000000000) {
        return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
     }
     if (num >= 1000000) {
        return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
     }
     if (num >= 1000) {
        return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
     }
     return Math.round(num);
}<|endoftext|>


<commit_before>$(document).ready(function() {

	// Upload a photo
	var uploadPhoto = $("#uploadPhotoBtn");

	function readURL(input) {
		if (input.files && input.files[0]) {
			var reader = new FileReader();

			reader.onload = function(event) {
				$("#userPhoto").attr("src", event.target.result);
			}

			reader.readAsDataURL(input.files[0]);
		}
	}

	uploadPhoto.on("change", function(event) {
		readURL(this);
	});

	//Filters - Grayscale

	var imageObj = new Image();

	var grayscaleBtn = document.getElementsByTagName("button")[0];
	var canvas = document.getElementById("imgCanvas");
	var originalPhoto = document.getElementById("userPhoto");
	var grayscaleRangeSlider = $("#grayscaleRange");
	var brightenRangeSlider = $("#brightenRange");
	var blurRangeSlider = $("#blurRange");
	var resetBtn = $("#resetBtn");
	var ctx = canvas.getContext("2d");

	function drawImage(imageObj) {

		var x = 0;
		var y = 0;
		var grayscaleVal = grayscaleRangeSlider.val() * 0.01;

		ctx.drawImage(imageObj, x, y); //namaluj mi nowy obraz na jakimś x i jakimś y

		var imageData = ctx.getImageData(x, y, imageObj.width, imageObj.height);
		//pobierz pozycję i wymiary z kontekstu
		var data = imageData.data;
		//zapisz te dane do zmiennej data, imageData.data przechowuje wartości poszczególnych pikseli (0-255)

		for (var i = 0; i < data.length; i += 4) {
			var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
			// red
			data[i] = brightness / grayscaleVal;
			// green
			data[i + 1] = brightness / grayscaleVal;
			// blue
			data[i + 2] = brightness / grayscaleVal;
		}

		// overwrite original image
		ctx.putImageData(imageData, x, y); //przetworzone dane umieść z powrotem na danej pozycji x i y

	}

	grayscaleRangeSlider.on("input", function(event) {

		var imgList = $("#imgContainer").find("img");

		if (imgList.length == 1) {
			canvas.parentNode.insertBefore(originalPhoto.cloneNode(true), canvas);
		}

		$("#form1").find("img").css("display", "none");

		drawImage(document.getElementById("userPhoto"));
	});

	resetBtn.on("click", function(event) {
		ctx.drawImage(originalPhoto, 0, 0);
	});

	//przycinanie obrazu

	// window.onload(function() {

	// 	ctx.beginPath();
	// 	ctx.rect(canvas.width / 2, canvas.height / 2, 187, 251);
	// 	ctx.clip();
	// 	ctx.scale(2, 2);
	// 	ctx.drawImage(userPhoto);

	// });

	//Zoom-in, Zoom-out
	var zoomIn = document.getElementById("zoom-in");
	var zoomOut = document.getElementById("zoom-out");

	zoomIn.addEventListener("click", function(event) {
		ctx.scale(0.99, 0.99);
		ctx.drawImage(originalPhoto, 0, 0);

	}, false);

	zoomOut.addEventListener("click", function(event) {
		ctx.scale(1.01, 1.01);
		ctx.drawImage(originalPhoto, 0, 0);
	}, false);

	//Move
	var moveTop = document.getElementById("moveTop");
	var moveRight = document.getElementById("moveRight");
	var moveLeft = document.getElementById("moveLeft");
	var moveBottom = document.getElementById("moveBottom");
	var x = 0;
	var y = 0;
	var deg = 1;

	moveTop.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		y -= 2;
	}, false);

	moveRight.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		x -= 2;
	}, false);

	moveLeft.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		x += 2;
	}, false);

	moveBottom.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		y += 2;
	}, false);

	//Rotation
	var rotateControl = document.querySelector(".rotation-circle");

	rotateControl.addEventListener("click", function(event) {
		console.log(deg);
		ctx.drawImage(originalPhoto, x, y);
		ctx.rotate(deg*Math.PI/180);
		deg +=5;
	}, false);

});<commit_msg>Begin working on rotation around axis.<commit_after>$(document).ready(function() {

	// Upload a photo
	var uploadPhoto = $("#uploadPhotoBtn");

	function readURL(input) {
		if (input.files && input.files[0]) {
			var reader = new FileReader();

			reader.onload = function(event) {
				$("#userPhoto").attr("src", event.target.result);
			}

			reader.readAsDataURL(input.files[0]);
		}
	}

	uploadPhoto.on("change", function(event) {
		readURL(this);
	});

	//Filters - Grayscale

	var imageObj = new Image();

	var grayscaleBtn = document.getElementsByTagName("button")[0];
	var canvas = document.getElementById("imgCanvas");
	var originalPhoto = document.getElementById("userPhoto");
	var grayscaleRangeSlider = $("#grayscaleRange");
	var brightenRangeSlider = $("#brightenRange");
	var blurRangeSlider = $("#blurRange");
	var resetBtn = $("#resetBtn");
	var ctx = canvas.getContext("2d");

	function drawImage(imageObj) {

		var x = 0;
		var y = 0;
		var grayscaleVal = grayscaleRangeSlider.val() * 0.01;

		ctx.drawImage(imageObj, x, y); //namaluj mi nowy obraz na jakimś x i jakimś y

		var imageData = ctx.getImageData(x, y, imageObj.width, imageObj.height);
		//pobierz pozycję i wymiary z kontekstu
		var data = imageData.data;
		//zapisz te dane do zmiennej data, imageData.data przechowuje wartości poszczególnych pikseli (0-255)

		for (var i = 0; i < data.length; i += 4) {
			var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
			// red
			data[i] = brightness / grayscaleVal;
			// green
			data[i + 1] = brightness / grayscaleVal;
			// blue
			data[i + 2] = brightness / grayscaleVal;
		}

		// overwrite original image
		ctx.putImageData(imageData, x, y); //przetworzone dane umieść z powrotem na danej pozycji x i y

	}

	grayscaleRangeSlider.on("input", function(event) {

		var imgList = $("#imgContainer").find("img");

		if (imgList.length == 1) {
			canvas.parentNode.insertBefore(originalPhoto.cloneNode(true), canvas);
		}

		$("#form1").find("img").css("display", "none");

		drawImage(document.getElementById("userPhoto"));
	});

	resetBtn.on("click", function(event) {
		ctx.drawImage(originalPhoto, 0, 0);
	});

	//przycinanie obrazu

	// window.onload(function() {

	// 	ctx.beginPath();
	// 	ctx.rect(canvas.width / 2, canvas.height / 2, 187, 251);
	// 	ctx.clip();
	// 	ctx.scale(2, 2);
	// 	ctx.drawImage(userPhoto);

	// });

	//Zoom-in, Zoom-out
	var zoomIn = document.getElementById("zoom-in");
	var zoomOut = document.getElementById("zoom-out");

	zoomIn.addEventListener("click", function(event) {
		ctx.scale(0.99, 0.99);
		ctx.drawImage(originalPhoto, 0, 0);

	}, false);

	zoomOut.addEventListener("click", function(event) {
		ctx.scale(1.01, 1.01);
		ctx.drawImage(originalPhoto, 0, 0);
	}, false);

	//Move
	var moveTop = document.getElementById("moveTop");
	var moveRight = document.getElementById("moveRight");
	var moveLeft = document.getElementById("moveLeft");
	var moveBottom = document.getElementById("moveBottom");
	var x = 0;
	var y = 0;
	var deg = 1;

	moveTop.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		y -= 2;
	}, false);

	moveRight.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		x -= 2;
	}, false);

	moveLeft.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		x += 2;
	}, false);

	moveBottom.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		y += 2;
	}, false);

	//Rotation
	var rotateControl = document.querySelector(".rotation-circle");

	rotateControl.addEventListener("click", function(event) {
		ctx.clearRect(0, 0, canvas.width, canvas.height);
		ctx.translate(canvas.width / 2, canvas.width / 2);

		console.log(deg);
		ctx.drawImage(originalPhoto, x, y);
		ctx.rotate(deg * Math.PI / 180);

		ctx.translate(-canvas.width / 2, -canvas.width / 2);
		deg += 5;
	}, false);

});<|endoftext|>


<commit_before>/* jshint undef: true, unused: true */
/* globals console:false, CloudOS:false  */
/* globals console, setTimeout, CloudOS, Fuse */

(function($)
{

    var router=new $.mobile.Router( {
       "#page-manage-fuse": {handler: "pageManageFuse",
			     events: "bs,bh",
			     argsre: true
			    }
    },
    {
	pageManageFuse: function(type, ui, page) {
	    console.log("manage fuse: main page");
	}
    },
    {
        defaultHandler: function(type, ui, page) {
            console.log("Default handler called due to unknown route (" + type + ", " + ui + ", " + page + ")");
        },
        defaultHandlerEvents: "s",
	defaultArgsRe: true
    });

    // Handlebar templates compiled at load time to create functions
    // templates are in index.html where they should be
    window['snippets'] = {
    };

    function plant_authorize_button()
    {
        //Oauth through kynetx
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
    };

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
    CloudOS.retrieveSession();
    plant_authorize_button();

    if(! CloudOS.authenticatedSession()) {
	console.log("We're not authorized...");
	$.mobile.changePage('#page-authorize', {
	    transition: 'slide'
	});
    } else {
	console.log("We're authorized...");
	$( ":mobile-pagecontainer" ).pagecontainer( "change", '#page-manage-fuse', {
	    transition: 'slide'
	});
	console.log("What are we doing???");
    }

})(jQuery);
<commit_msg>something's not right...<commit_after>/* jshint undef: true, unused: true */
/* globals console:false, CloudOS:false  */
/* globals console, setTimeout, CloudOS, Fuse */

(function($)
{

    var router=new $.mobile.Router( {
       "#page-manage-fuse": {handler: "pageManageFuse",
			     events: "bs,bh",
			     argsre: true
			    }
    },
    {
	pageManageFuse: function(type, ui, page) {
	    console.log("manage fuse: main page");
	}
    },
    {
        defaultHandler: function(type, ui, page) {
            console.log("Default handler called due to unknown route (" + type + ", " + ui + ", " + page + ")");
        },
        defaultHandlerEvents: "s",
	defaultArgsRe: true
    });

    // Handlebar templates compiled at load time to create functions
    // templates are in index.html where they should be
    window['snippets'] = {
    };

    function plant_authorize_button()
    {
        //Oauth through kynetx
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
    };

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
    CloudOS.retrieveSession();
    plant_authorize_button();

    if(! CloudOS.authenticatedSession()) {
	console.log("We're not authorized...");
	$.mobile.changePage('#page-authorize', {
	    transition: 'slide'
	});
    } else {
	console.log("We're authorized...");
	var foo = $( ":mobile-pagecontainer" ).pagecontainer( "change", '#page-manage-fuse', {
	    transition: 'slide'
	});

	console.log("What are we doing???", foo);
    }

})(jQuery);
<|endoftext|>


<commit_before>function drinkRecipe(drinkName, ingredients, glass, image, category, liquor){
	this.drinkName = drinkName;
	this.ingredients = ingredients;
	this.glassType = glass;
	this.imageProperty = image;
	this.category = category;
  this.baseLiquior = liquor;
  this.match = 0;
	this.percentMatch = 0;
	this.ingMatch = [0];
	this.ingMismatch = [0];
}
function ingredient(ingName, image, substitutes){
	this.ingName = ingName;
	this.image = image;
	this.substitutes = substitutes;
}

var base = new Firebase("https://glaring-heat-8547.firebaseio.com"); // Link to the firebase!
var drinksDir = base.child("drinks");
var drinkArray = [];
var ingArray = [];

var drinkArray = [  // This array holds objects for every drink ever entered into the database!
    new drinkRecipe('Screwdriver',[['Vodka','1.5 oz'],['Orange juice','6 oz']],'high ball','highball.jpg','cold','vodka'),
    new drinkRecipe('Margarita',[['Tequila','1.5 oz'],['Triple sec','1.5 oz'],['Lime juice','1-1.25 oz'],['Salt','on the rim of the glass']],'margarita','margarita.jpg','cold','tequila'),
    new drinkRecipe('Irish Coffee',[['Whiskey','1.5 oz'],['Coffee','1 cup'],['Brown sugar','1 tablespoon']],'Irish Coffee','irish.jpg','warm','whiskey'),
    new drinkRecipe('Mimosa',[['champagne','1/3 cup'],['orange juice','1/3 cup'],['triple sec','1 tablespoon (optional)']],'flute','flute.jpg','cold','champagne')
  ];
var ingArray = [ // This array holds objects for every ingredient the user has in their
		new ingredient('vodka', 'img/vodka.jpg', ''),
		new ingredient('rum', 'img/rum.jpg', ''),
		new ingredient('whiskey', 'img/whiskey.jpg', '')
];

function loadDrinks(){ // Adds all drinks stored in the database to the current instance.
	base.on("value", function(snapshot) {
  	console.log('Setting the user\'s drinks to the database drink contents!');
		var tempObj = snapshot.val();
		drinkArray = [tempObj.drinks];
	}, function (errorObject) {
  console.log("The firebase read failed: " + errorObject.code);
	});
};
function updateDrinks(){ // For all drink obects, if drinkName is not present in the database, add it.
	console.log('Updating the drinks database!')
	drinksDir.set(drinkArray);
};
function loadIngredients(){ // Adds all ingredients stored in local-data to the current instance.
	var tempArray = JSON.parse(localStorage.getItem('ingData'));
	if (tempArray){
		console.log('Getting ingredient info from local storage..')
		var ingArray = tempArray;
	} else {
		console.log('No local ingredient data found!');
	}
};
function updateIngredients(){ // For all ingredients, if ingredient is not present in local storage, add it.
	console.log('Updating local ingredient data..')
	localStorage.setItem('ingData', JSON.stringify(ingArray));
};
function delDrink(drinkName){ // Removes drink with a drinkName string matching the drinkName argument.

};
function delIngredient(ingName){ // Removes ingredient with a string matching ingName from the user's local data.

};

// loadDrinks();
// updateDrinks();
// loadIngredients();
// updateIngredients();
<commit_msg>improved updateDrinks and delDrink functions<commit_after>function drinkRecipe(drinkName, ingredients, glass, image, category, liquor){
	this.drinkName = drinkName;
	this.ingredients = ingredients;
	this.glassType = glass;
	this.imageProperty = image;
	this.category = category;
  this.baseLiquior = liquor;
  this.match = 0;
	this.percentMatch = 0;
	this.ingMatch = [];
	this.ingMismatch = [];
}
function ingredient(ingName, image, substitutes){
	this.ingName = ingName;
	this.image = image;
	this.substitutes = substitutes;
}

var base = new Firebase("https://glaring-heat-8547.firebaseio.com"); // Link to the firebase!
var drinksDir = base.child("drinks");
var drinkArray = [];
var ingArray = [];

var drinkArray = [  // This array holds objects for every drink ever entered into the database!
    new drinkRecipe('Screwdriver',[['Vodka','1.5 oz'],['Orange juice','6 oz']],'high ball','highball.jpg','cold','vodka'),
    new drinkRecipe('Margarita',[['Tequila','1.5 oz'],['Triple sec','1.5 oz'],['Lime juice','1-1.25 oz'],['Salt','on the rim of the glass']],'margarita','margarita.jpg','cold','tequila'),
    new drinkRecipe('Irish Coffee',[['Whiskey','1.5 oz'],['Coffee','1 cup'],['Brown sugar','1 tablespoon']],'Irish Coffee','irish.jpg','warm','whiskey'),
    new drinkRecipe('Mimosa',[['champagne','1/3 cup'],['orange juice','1/3 cup'],['triple sec','1 tablespoon (optional)']],'flute','flute.jpg','cold','champagne')
  ];
var ingArray = [ // This array holds objects for every ingredient the user has in their
		new ingredient('vodka', 'img/vodka.jpg', ''),
		new ingredient('rum', 'img/rum.jpg', ''),
		new ingredient('whiskey', 'img/whiskey.jpg', '')
];

function loadDrinks(){ // Adds all drinks stored in the database to the current instance.
	base.on("value", function(snapshot) {
  	console.log('Setting the user\'s drinks to the database drink contents!');
		var tempObj = snapshot.val();
		drinkArray = [tempObj.drinks];
	}, function (errorObject) {
  console.log("The firebase read failed: " + errorObject.code);
	});
};
function updateDrinks(){ // For all drink obects, if drinkName is not present in the database, add it.
	console.log('Updating the drinks database!')
	base.once("value", function(snapshot){
		var tempObj = snapshot.val(); // Puts data from the firebase into an object
		var match = false; // Haven't found a match for the drink yet, so this is false
		drinkArray.forEach(function(drink){ // For each of the user's drinks
			for (var cloudDrink in tempObj.drinks){ // For each drink in the firebase
				if (drink.drinkName === tempObj.drinks[cloudDrink].drinkName){match = true;} // If there's a match, set match = true
			}
			if (match){ // if maych is true, it matched one of the drinks in the database
				console.log(drink.drinkName + ' is already in the database!') // and so already exists
			} else { // otherwise, this must be a new drink
				console.log('User submitted a new drink: ' + drink.drinkName + ', adding it to the database.');
				drinksDir.push(drink); // so add it to the database
			}
			match = false; // reset match before returning to the drinkArray forEach
		})
	})
};
function loadIngredients(){ // Adds all ingredients stored in local-data to the current instance.
	var tempArray = JSON.parse(localStorage.getItem('ingData'));
	if (tempArray){
		console.log('Getting ingredient info from local storage..')
		var ingArray = tempArray;
	} else {
		console.log('No local ingredient data found!');
	}
};
function updateIngredients(){ // For all ingredients, if ingredient is not present in local storage, add it.
	console.log('Updating local ingredient data..')
	localStorage.setItem('ingData', JSON.stringify(ingArray));
};
function delDrink(drinkID){ // Removes drink with a drinkName string matching the drinkName argument.
	var tempArray = drinkArray
	base.once("value", function(snapshot){
		var tempObj = snapshot.val();
		for (var cloudDrink in tempObj.drinks){
			if (drinkID === tempObj.drinks[cloudDrink].drinkName){
				console.log('Deleting ' + drinkID + ' from the firebase..')
				delete tempObj.drinks[cloudDrink];
				base.set(tempObj);
			}
		}
	})
	drinkArray.forEach(function(drink, indexNum){
		if (drinkID === drink.drinkName){
			console.log('Deleting ' + drinkID + ' from the drinks array..')
			drinkArray.splice(indexNum, 1);
			console.log(drinkArray);
		}
	})
};

function delIngredient(ingName){ // Removes ingredient with a string matching ingName from the user's local data.
};

// drinksDir.set(drinkArray);
// loadDrinks();
// updateDrinks();
// loadIngredients();
// updateIngredients();

// delDrink('Screwdriver');
<|endoftext|>


<commit_before>angular.module('henrik', ['ui.router', 'controllers'])

.config(function ($stateProvider, $urlRouterProvider) {

  $stateProvider.state('home', {
    url: '/home',
    templateUrl: 'partials/home.html',
    controller: 'HomeCtrl'
  })

  .state('adventure', {
    url: '/adventure',
    templateUrl: 'partials/adventure.html',
    controller: 'HomeCtrl'
  })

  .state('clients', {
    url: '/clients',
    templateUrl: 'partials/clients.html',
    controller: 'HomeCtrl'
  })

  .state('social', {
    url: '/social',
    templateUrl: 'partials/social.html',
    controller: 'HomeCtrl'
  });

  $urlRouterProvider.otherwise('/home');

});
<commit_msg>Sort states<commit_after>angular.module('henrik', ['ui.router', 'controllers'])

.config(function ($stateProvider, $urlRouterProvider) {

  $stateProvider.state('home', {
    url: '/home',
    templateUrl: 'partials/home.html',
    controller: 'HomeCtrl'
  })

  .state('assignments', {
    url: '/assignments',
    templateUrl: 'partials/assignments.html',
    controller: 'HomeCtrl'
  })

  .state('clients', {
    url: '/clients',
    templateUrl: 'partials/clients.html',
    controller: 'HomeCtrl'
  })

  .state('adventure', {
    url: '/adventure',
    templateUrl: 'partials/adventure.html',
    controller: 'HomeCtrl'
  })

  .state('social', {
    url: '/social',
    templateUrl: 'partials/social.html',
    controller: 'HomeCtrl'
  });

  $urlRouterProvider.otherwise('/home');

});
<|endoftext|>


<commit_before>(function (document, window) {

	// TOUCHES = [];

	// function detectDrag(e) {
	// 	TOUCHES = (e.changedTouches);
	// 	console.log(TOUCHES);
	// 	return true;
	// }

	function Graphic(properties) {
		this.image = new Image();
		this.image.src = properties.src;
		this.label = properties.label;
		this.credit = properties.credit;
	}

	Graphic.prototype.getImageDimensions = function() {
		var dimensions = {
			width: this.image.naturalWidth,
			height: this.image.naturalHeight,
			aspect: function() { return (this.width / this.height); }
		};
		console.log(dimensions);
		return dimensions;
	};

	var imageSlider = function(id, images, options) {

		function setBackgroundImage(element, url) {
			var property = "url(" + url + ")";
			element.style.backgroundImage = property;
		}

		function ImageSlider(id, images, options) {

			var i;
			this.options = {
				animate: true,
				showLabels: true,
				showCredits: true,
				startingPosition: "50%"
			};

			for (i in options) {
				this.options[i] = options[i];
			}

			if (images.length == 2) {
				this.imgBefore = new Graphic(images[0]);
				this.imgAfter = new Graphic(images[1]);
			} else {
				throw new Error("The images paramater takes two Image objects.");
			}

			//Image Loading
			var load1 = false;
			var load2 = false;

			this.imgBefore.image.onload = function() {
				load1 = true;
				this._onLoaded();
			};

			this.imgAfter.image.onload = function() {
				load2 = true;
				this._onLoaded();
			};

			ImageSlider.prototype = {

				updateSlider: function(e, dragging) {

					var sliderRect = this.slider.getBoundingClientRect()
					var offset = {
					  top: sliderRect.top + document.body.scrollTop,
					  left: sliderRect.left + document.body.scrollLeft
					};

					var width = this.slider.offsetWidth;

					var relativeX = e.pageX - offset.left;

					var leftPercent = (relativeX / width) * 100 + "%";
					var rightPercent = 100 - ((relativeX / width) * 100) + "%";

					var a = (relativeX / width);
					if (a < 1) {

						this.handle.classList.remove("transition");
						this.rightImage.classList.remove("transition");
						this.leftImage.classList.remove("transition");

						if(this.options.animate && !dragging) {
							this.handle.classList.add("transition");
							this.leftImage.classList.add("transition");
							this.rightImage.classList.add("transition");
						}

						this.handle.style.left = leftPercent;
						this.leftImage.style.width = leftPercent;
						this.rightImage.style.width = rightPercent;
					}
				},

				displayLabels: function() {
					leftDate = document.createElement("div");
					leftDate.className = 'klba-label';
					leftDate.textContent = this.imgBefore.label;
					rightDate = document.createElement("div");
					rightDate.className = 'klba-label';
					rightDate.textContent = this.imgAfter.label;

					this.leftImage.appendChild(leftDate);
					this.rightImage.appendChild(rightDate);
				},

				displayCredits: function() {
					credit = document.createElement("div");
					credit.className = "klba-credit";

					text = 	"Before " + this.imgBefore.credit +
							" After " + this.imgAfter.credit;
					credit.innerHTML = text;

					this.wrapper.appendChild(credit);
				},

				checkImages: function() {
					if (this.imgBefore.getImageDimensions().aspect() ==
						this.imgAfter.getImageDimensions().aspect()) {
						return true;
					} else {
						return false;
					}
				},

				_onLoaded: function() {
					if (load1 && load2) {

						this.wrapper = document.getElementById(id);

						if (this.wrapper.classList) {
							this.wrapper.classList.add("klba-wrapper");
						} else {
							this.wrapper.className += ' ' + "klba-wrapper";
						}

						this.slider = document.createElement("div");
						this.slider.className = 'klba-slider';
						this.wrapper.appendChild(this.slider);

						this.handle = document.createElement("div");
						this.handle.className = 'klba-handle';

						this.rightImage = document.createElement("div");
						this.rightImage.className = 'klba-image right';
						this.leftImage = document.createElement("div");
						this.leftImage.className = 'klba-image left'

						this.slider.appendChild(this.handle);
						this.slider.appendChild(this.leftImage);
						this.slider.appendChild(this.rightImage);

						leftArrow = document.createElement("div");
						rightArrow = document.createElement("div");
						control = document.createElement("div");
						controller = document.createElement("div");

						leftArrow.className = 'klba-arrow left';
						rightArrow.className = 'klba-arrow right';
						control.className = 'klba-control';
						controller.className = 'klba-controller';

						this.handle.appendChild(leftArrow);
						this.handle.appendChild(control);
						this.handle.appendChild(rightArrow);
						control.appendChild(controller);

						this.dragging = false;

						this._init(this);
					}
				},

				_init: function() {

					if (this.checkImages() === false) {
						throw new Error("The two images need to have the same dimensions.");
					}

					rightStart = 100 - parseInt(this.options.startingPosition) + "%";

					this.leftImage.style.width = this.options.startingPosition;
					this.rightImage.style.width = rightStart;
					this.handle.style.left = this.options.startingPosition;

					setBackgroundImage(this.leftImage, this.imgBefore.image.src);
					setBackgroundImage(this.rightImage, this.imgAfter.image.src);

					if (this.options.showLabels) {
						this.displayLabels();
					}

					if (this.options.showCredits) {
						this.displayCredits();
					}

					var self = this;
					this.slider.addEventListener("mousedown", function(d) {
						d.preventDefault();
						self.updateSlider(d, false);
						dragging = true;

						this.addEventListener("mousemove", function(event) {
							if (dragging) {
								self.updateSlider(event, true);
							}
						});

						document.addEventListener('mouseup', function() {
							dragging = false;
						});

						this.addEventListener('mouseleave', function() {
							dragging = false;
						});
					});

					this.slider.addEventListener("touchstart", function(d) {
						d.preventDefault();
						self.updateSlider(d, false)
						dragging = true;

						this.addEventListener("touchmove", function(event) {
							swipe = detectDrag(event);
							if (dragging) {
								self.updateSlider(event, true);
							}
						});
					});
				}
			}
			return new ImageSlider(id, images, options);
		};

	window.imageSlider = imageSlider;

}(document, window));
<commit_msg>fixed issue #2, still working on fixing other bugs<commit_after>(function (document, window) {

	// TOUCHES = [];

	// function detectDrag(e) {
	// 	TOUCHES = (e.changedTouches);
	// 	console.log(TOUCHES);
	// 	return true;
	// }

	function Graphic(properties) {
		this.image = new Image();
		this.image.src = properties.src;
		this.label = properties.label;
		this.credit = properties.credit;
	}

	Graphic.prototype.getImageDimensions = function() {
		var dimensions = {
			width: this.image.naturalWidth,
			height: this.image.naturalHeight,
			aspect: function() { return (this.width / this.height); }
		};
		console.log(dimensions);
		return dimensions;
	};

	var imageSlider = function(id, images, options) {

		function setBackgroundImage(element, url) {
			var property = "url(" + url + ")";
			element.style.backgroundImage = property;
		}

		function ImageSlider(id, images, options) {

			var i;
			this.options = {
				animate: true,
				showLabels: true,
				showCredits: true,
				startingPosition: "50%"
			};

			for (i in options) {
				this.options[i] = options[i];
			}

			if (images.length == 2) {
				this.imgBefore = new Graphic(images[0]);
				this.imgAfter = new Graphic(images[1]);
			} else {
				throw new Error("The images paramater takes two Image objects.");
			}

			//Image Loading
			var load1 = false;
			var load2 = false;

			var self = this;

			this.imgBefore.image.onload = function() {
				console.log(self);
				load1 = true;
				self._onLoaded();
			};

			this.imgAfter.image.onload = function() {
				load2 = true;
				self._onLoaded();
			};

			ImageSlider.prototype = {

				updateSlider: function(e, dragging) {

					var sliderRect = this.slider.getBoundingClientRect()
					var offset = {
					  top: sliderRect.top + document.body.scrollTop,
					  left: sliderRect.left + document.body.scrollLeft
					};

					var width = this.slider.offsetWidth;

					var relativeX = e.pageX - offset.left;

					var leftPercent = (relativeX / width) * 100 + "%";
					var rightPercent = 100 - ((relativeX / width) * 100) + "%";

					var a = (relativeX / width);
					if (a < 1) {

						this.handle.classList.remove("transition");
						this.rightImage.classList.remove("transition");
						this.leftImage.classList.remove("transition");

						if(this.options.animate && !dragging) {
							this.handle.classList.add("transition");
							this.leftImage.classList.add("transition");
							this.rightImage.classList.add("transition");
						}

						this.handle.style.left = leftPercent;
						this.leftImage.style.width = leftPercent;
						this.rightImage.style.width = rightPercent;
					}
				},

				displayLabels: function() {
					leftDate = document.createElement("div");
					leftDate.className = 'klba-label';
					leftDate.textContent = this.imgBefore.label;
					rightDate = document.createElement("div");
					rightDate.className = 'klba-label';
					rightDate.textContent = this.imgAfter.label;

					this.leftImage.appendChild(leftDate);
					this.rightImage.appendChild(rightDate);
				},

				displayCredits: function() {
					credit = document.createElement("div");
					credit.className = "klba-credit";

					text = 	"Before " + this.imgBefore.credit +
							" After " + this.imgAfter.credit;
					credit.innerHTML = text;

					this.wrapper.appendChild(credit);
				},

				checkImages: function() {
					if (this.imgBefore.getImageDimensions().aspect() ==
						this.imgAfter.getImageDimensions().aspect()) {
						return true;
					} else {
						return false;
					}
				},

				_onLoaded: function() {

					//If both images have loaded
					if (load1 & load2) {

						//Create the HTML structure for the slider
						this.wrapper = document.getElementById(id);

						if (this.wrapper.classList) {
							this.wrapper.classList.add("klba-wrapper");
						} else {
							this.wrapper.className += ' ' + "klba-wrapper";
						}

						this.slider = document.createElement("div");
						this.slider.className = 'klba-slider';
						this.wrapper.appendChild(this.slider);

						this.handle = document.createElement("div");
						this.handle.className = 'klba-handle';

						this.rightImage = document.createElement("div");
						this.rightImage.className = 'klba-image right';
						this.leftImage = document.createElement("div");
						this.leftImage.className = 'klba-image left'

						this.slider.appendChild(this.handle);
						this.slider.appendChild(this.leftImage);
						this.slider.appendChild(this.rightImage);

						leftArrow = document.createElement("div");
						rightArrow = document.createElement("div");
						control = document.createElement("div");
						controller = document.createElement("div");

						leftArrow.className = 'klba-arrow left';
						rightArrow.className = 'klba-arrow right';
						control.className = 'klba-control';
						controller.className = 'klba-controller';

						this.handle.appendChild(leftArrow);
						this.handle.appendChild(control);
						this.handle.appendChild(rightArrow);
						control.appendChild(controller);

						this.dragging = false;

						//Add Interactivity
						this._init();
					}
				},

				_init: function() {

					if (this.checkImages() == false) {
						throw new Error("The two images need to have the same dimensions.");
					}

					var rightStart = 100 - parseInt(this.options.startingPosition) + "%";

					this.leftImage.style.width = this.options.startingPosition;
					this.rightImage.style.width = rightStart;
					this.handle.style.left = this.options.startingPosition;

					setBackgroundImage(this.leftImage, this.imgBefore.image.src);
					setBackgroundImage(this.rightImage, this.imgAfter.image.src);

					if (this.options.showLabels) {
						this.displayLabels();
					}

					if (this.options.showCredits) {
						this.displayCredits();
					}

					var self = this;

					this.slider.addEventListener("mousedown", function(d) {
						d.preventDefault();
						self.updateSlider(d, false);
						dragging = true;

						this.addEventListener("mousemove", function(event) {
							if (dragging) {
								self.updateSlider(event, true);
							}
						});

						document.addEventListener('mouseup', function() {
							dragging = false;
						});

						this.addEventListener('mouseleave', function() {
							dragging = false;
						});
					});

					this.slider.addEventListener("touchstart", function(d) {
						d.preventDefault();
						self.updateSlider(d, false)
						dragging = true;

						this.addEventListener("touchmove", function(event) {
							swipe = detectDrag(event);
							if (dragging) {
								self.updateSlider(event, true);
							}
						});
					});
				}
			}

		}

		return new ImageSlider(id, images, options);
	};

	window.imageSlider = imageSlider;

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


<commit_before>$(document).ready(function() {
  grid.drawGrid();
  grid.updateDiameter(250);

  var YX = grid.YX;
  //YX[1][1].addClass('test');

  function checkNeighbours(cell) {
    var x = cell.x;
    var y = cell.y;
    var aliveNeighbours = 0;

    // Determining the right neighbour.
    if (x == grid.amount) {
      var right = grid.YX[y][1];
    }else{
      var right = grid.YX[y][x+1];
    }
    // Determining the left neighbour.
    if (x == 1) {
      var left = grid.YX[y][grid.amount];
    }else{
      var left = grid.YX[y][x-1];
    }
    // Determining the top neighbour
    if (y == 1) {
      var top = grid.YX[grid.amount][x];
    }else{
      var top = grid.YX[y-1][x];
    }
    // Determining the bottom neighbour.
    if(y == grid.amount){
      var bottom = grid.YX[1][x];
    }else {
      var bottom = grid.YX[y+1][x];
    }
    // Determining top right neighbour.
    if (top.x == grid.amount) {
      var topRight = grid.YX[top.y][1];
    }else{
      var topRight = grid.YX[top.y][top.x+1];
    }
    // Determining top left neighbour.
    if(top.x == 1){
      var topLeft = grid.YX[top.y][grid.amount];
    }else {
      var topLeft = grid.YX[top.y][top.x-1]
    }
    // Determining bottom right neighbour.
    if (bottom.x == grid.amount) {
      var bottomRight = grid.YX[bottom.y][1]
    }else {
      var bottomRight = grid.YX[bottom.y][bottom.x+1]
    }
    // Determining top left neighbour.
    if(bottom.x == 1){
      var bottomLeft = grid.YX[bottom.y][grid.amount];
    }else {
      var bottomLeft = grid.YX[bottom.y][bottom.x-1]
    }

    // If a neighbours' state is alive the amount of alive neighbours =+1
    if(right.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    if (left.state == 1) {
      aliveNeighbours = aliveNeighbours+1;
    }
    if(top.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    if(bottom.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    if(topRight.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    if(topLeft.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    if(bottomRight.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    if(bottomLeft.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    // Adding the amount of living neighbours to the cells object
    cell.aliveNeighbours = aliveNeighbours;

  } // end of function

  function nextStates(cell) {
    //
    if(cell.state == 1 && cell.aliveNeighbours < 2) {
      cell.nextState = 0;
    }
    else if(cell.state == 1 && cell.aliveNeighbours > 3) {
      cell.nextState = 0;
    }

    else if(cell.state == 1 && cell.aliveNeighbours == 2) {
      cell.nextState = 1;
    }
    else if (cell.state == 1 && cell.aliveNeighbours == 3) {
      cell.nextState = 1;
    }
    else if(cell.state == 0 && cell.aliveNeighbours == 3) {
      cell.nextState = 1;
    }
    else{
      cell.nextState = cell.state;
    }
  }

  function gameStep() {
    for (var i = 1; i < grid.amount*grid.amount+1; i++) {
      grid.cells[i].setState(grid.cells[i].nextState);
    }
  }

  $(document).click(function(){
    for (var i = 1; i < grid.amount*grid.amount+1; i++) {
      checkNeighbours(grid.cells[i]);
      nextStates(grid.cells[i]);
    }
    gameStep();
  });

});
// --- THE RULES ---
// Any live cell with fewer than two live neighbours dies (referred to as underpopulation or exposure[1]).
// Any live cell with more than three live neighbours dies (referred to as overpopulation or overcrowding).
// Any live cell with two or three live neighbours lives, unchanged, to the next generation.
// Any dead cell with exactly three live neighbours will come to life.
<commit_msg>added interval...game is automatic<commit_after>$(document).ready(function() {
  grid.drawGrid();
  grid.updateDiameter(250);

  var YX = grid.YX;
  //YX[1][1].addClass('test');

  function checkNeighbours(cell) {
    var x = cell.x;
    var y = cell.y;
    var aliveNeighbours = 0;

    // Determining the right neighbour.
    if (x == grid.amount) {
      var right = grid.YX[y][1];
    }else{
      var right = grid.YX[y][x+1];
    }
    // Determining the left neighbour.
    if (x == 1) {
      var left = grid.YX[y][grid.amount];
    }else{
      var left = grid.YX[y][x-1];
    }
    // Determining the top neighbour
    if (y == 1) {
      var top = grid.YX[grid.amount][x];
    }else{
      var top = grid.YX[y-1][x];
    }
    // Determining the bottom neighbour.
    if(y == grid.amount){
      var bottom = grid.YX[1][x];
    }else {
      var bottom = grid.YX[y+1][x];
    }
    // Determining top right neighbour.
    if (top.x == grid.amount) {
      var topRight = grid.YX[top.y][1];
    }else{
      var topRight = grid.YX[top.y][top.x+1];
    }
    // Determining top left neighbour.
    if(top.x == 1){
      var topLeft = grid.YX[top.y][grid.amount];
    }else {
      var topLeft = grid.YX[top.y][top.x-1]
    }
    // Determining bottom right neighbour.
    if (bottom.x == grid.amount) {
      var bottomRight = grid.YX[bottom.y][1]
    }else {
      var bottomRight = grid.YX[bottom.y][bottom.x+1]
    }
    // Determining top left neighbour.
    if(bottom.x == 1){
      var bottomLeft = grid.YX[bottom.y][grid.amount];
    }else {
      var bottomLeft = grid.YX[bottom.y][bottom.x-1]
    }

    // If a neighbours' state is alive the amount of alive neighbours =+1
    if(right.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    if (left.state == 1) {
      aliveNeighbours = aliveNeighbours+1;
    }
    if(top.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    if(bottom.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    if(topRight.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    if(topLeft.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    if(bottomRight.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    if(bottomLeft.state == 1){
      aliveNeighbours = aliveNeighbours+1;
    }
    // Adding the amount of living neighbours to the cells object
    cell.aliveNeighbours = aliveNeighbours;

  } // end of function

  function nextStates(cell) {
    //
    if(cell.state == 1 && cell.aliveNeighbours < 2) {
      cell.nextState = 0;
    }
    else if(cell.state == 1 && cell.aliveNeighbours > 3) {
      cell.nextState = 0;
    }

    else if(cell.state == 1 && cell.aliveNeighbours == 2) {
      cell.nextState = 1;
    }
    else if (cell.state == 1 && cell.aliveNeighbours == 3) {
      cell.nextState = 1;
    }
    else if(cell.state == 0 && cell.aliveNeighbours == 3) {
      cell.nextState = 1;
    }
    else{
      cell.nextState = cell.state;
    }
  }

  function gameStep() {
    for (var i = 1; i < grid.amount*grid.amount+1; i++) {
      grid.cells[i].setState(grid.cells[i].nextState);
    }
  }

  $(window).setInterval(function(){
    for (var i = 1; i < grid.amount*grid.amount+1; i++) {
      checkNeighbours(grid.cells[i]);
      nextStates(grid.cells[i]);
    }
    gameStep();
  },175);

});
// --- THE RULES ---
// Any live cell with fewer than two live neighbours dies (referred to as underpopulation or exposure[1]).
// Any live cell with more than three live neighbours dies (referred to as overpopulation or overcrowding).
// Any live cell with two or three live neighbours lives, unchanged, to the next generation.
// Any dead cell with exactly three live neighbours will come to life.
<|endoftext|>