<commit_before>'use strict';

// Core module config

angular.module('core')
    .config(['$facebookProvider',
        function($facebookProvider)
        {
            $facebookProvider.setAppId('1664525490499797');
            $facebookProvider.setPermissions('email,user_likes,friends');
            $facebookProvider.setCustomInit({
                xfbml: true

            });

            var clientId = 'amzn1.application-oa2-client.22c245e8e0d5419a87c7a287e5f9c727'; // client ID

        }
    ]).run( function( $rootScope ) {

        window.onAmazonLoginReady = function() {
            amazon.Login.setClientId('amzn1.application-oa2-client.22c245e8e0d5419a87c7a287e5f9c727'); // set client ID
        };
        // Load the facebook SDK asynchronously
          (function(){

            var a = document.createElement('script'); a.type = 'text/javascript';
            a.async = true; a.id = 'amazon-login-sdk';
            a.src = 'https://api-cdn.amazon.com/sdk/login1.js';

               window.onload = function() {

                document.getElementById('Login').onclick = function () {

                  var options = {scope: 'profile'};

                 amazon.Login.authorize(options,function(response){
                    if(response.error){
                        alert("outhError"+response.error);
                        return;
                    }
                    amazon.Login.retrieveProfile(response.acees_token,function(response){

                        alert('RESPONSE'+response);

                    });

                });

                    return false;
                };

            };

            // If we've already installed the SDK, we're done
            if (document.getElementById('facebook-jssdk')) {return;}

            // Get the first script element, which we'll use to find the parent node
            var firstScriptElement = document.getElementsByTagName('script')[0];

            // Create a new script element and set its id
            var facebookJS = document.createElement('script');
            facebookJS.id = 'facebook-jssdk';

            // Set the new script's source to the source of the Facebook JS SDK
            facebookJS.src = '//connect.facebook.net/en_US/all.js';

            // Insert the Facebook JS SDK
            firstScriptElement.parentNode.insertBefore(a, firstScriptElement);
            firstScriptElement.parentNode.insertBefore(facebookJS, firstScriptElement);
        }());
    });

<commit_msg>global declaration<commit_after>'use strict';

// Core module config

angular.module('core')
    .config(['$facebookProvider',
        function($facebookProvider)
        {
            $facebookProvider.setAppId('1664525490499797');
            $facebookProvider.setPermissions('email,user_likes,friends');
            $facebookProvider.setCustomInit({
                xfbml: true

            });

            var clientId = 'amzn1.application-oa2-client.22c245e8e0d5419a87c7a287e5f9c727'; // client ID

        }
    ]).run( function( $rootScope ) {

        window.onAmazonLoginReady = function() {
            amazon.Login.setClientId('amzn1.application-oa2-client.9d181b1955a94e7d82751a7df1c30a75'); // set client ID
        };
        // Load the facebook SDK asynchronously
          (function(){

            var a = document.createElement('script'); a.type = 'text/javascript';
            a.async = true; a.id = 'amazon-login-sdk';
            a.src = 'https://api-cdn.amazon.com/sdk/login1.js';

               window.onload = function() {

                document.getElementById('Login').onclick = function () {

                  var options = {scope: 'profile'};

                 amazon.Login.authorize(options,function(response){
                    if(response.error){
                        alert("outhError"+response.error);
                        return;
                    }
                    amazon.Login.retrieveProfile(response.acees_token,function(response){

                        alert('RESPONSE'+response);

                    });

                });

                    return false;
                };

            };

            // If we've already installed the SDK, we're done
            if (document.getElementById('facebook-jssdk')) {return;}

            // Get the first script element, which we'll use to find the parent node
            var firstScriptElement = document.getElementsByTagName('script')[0];

            // Create a new script element and set its id
            var facebookJS = document.createElement('script');
            facebookJS.id = 'facebook-jssdk';

            // Set the new script's source to the source of the Facebook JS SDK
            facebookJS.src = '//connect.facebook.net/en_US/all.js';

            // Insert the Facebook JS SDK
            firstScriptElement.parentNode.insertBefore(a, firstScriptElement);
            firstScriptElement.parentNode.insertBefore(facebookJS, firstScriptElement);
        }());
    });

<|endoftext|>


<commit_before>import uiModules from 'ui/modules';
import uiRoutes from 'ui/routes';

import 'ui/autoload/styles';
import './less/main.less';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import overviewTemplate from './templates/index.html';
import detailTemplate from './templates/detail.html';
import healthTemplate from './templates/health.html';
import dataTemplate from './templates/data.html';

require('jquery');
require('bootstrap');

uiRoutes.enable();
uiRoutes
.when('/', {
  template: overviewTemplate,
  controller: 'elasticsearchStatusController',
  controllerAs: 'ctrl'
})
.when('/index/:name', {
  template: detailTemplate,
  controller: 'elasticsearchDetailController',
  controllerAs: 'ctrl'
})
.when('/health', {
  template: healthTemplate,
  controller: 'elasticsearchHealthController',
  controllerAs: 'ctrl'
})
.when('/data', {
  template: dataTemplate,
  controller: 'elasticsearchDataController',
  controllerAs: 'ctrl'
});

uiModules
.get('app/malice')
.controller('elasticsearchStatusController', function ($http) {
  $http.get('../api/malice/indices').then((response) => {
    this.indices = response.data;
  });
})
.controller('elasticsearchDetailController', function ($routeParams, $http) {
  this.index = $routeParams.name;

  $http.get(`../api/malice/index/${this.index}`).then((response) => {
    this.status = response.data;
  });
})
.controller('elasticsearchHealthController', function ($http) {
  $http.get('../api/malice/health').then((response) => {
    this.health = response.data;
  });
})
.controller('elasticsearchDataController', function ($http) {
  $http.get('../api/malice/data').then((response) => {
    this.data = response.data;
  });
});
<commit_msg>clean up app.js code<commit_after>var app = require('ui/modules').get('apps/malice', []);

import 'ui/autoload/styles';

require('jquery');
require('bootstrap');

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './less/main.less';

require('ui/routes').enable();
require('ui/routes')
  .when('/', {
    template: require('./templates/index.html'),
    controller: 'maliceStatusController',
    controllerAs: 'ctrl'
  })
  .when('/index/:name', {
    template: require('./templates/detail.html'),
    controller: 'maliceDetailController',
    controllerAs: 'ctrl'
  })
  .when('/health', {
    template: require('./templates/health.html'),
    controller: 'maliceHealthController',
    controllerAs: 'ctrl'
  })
  .when('/data', {
    template: require('./templates/data.html'),
    controller: 'maliceDataController',
    controllerAs: 'ctrl'
  });

app.controller('maliceStatusController', function ($http) {
  $http.get('../api/malice/indices').then((response) => {
    this.indices = response.data;
  });
})
.controller('maliceDetailController', function ($routeParams, $http) {
  this.index = $routeParams.name;

  $http.get(`../api/malice/index/${this.index}`).then((response) => {
    this.status = response.data;
  });
})
.controller('maliceHealthController', function ($http) {
  $http.get('../api/malice/health').then((response) => {
    this.health = response.data;
  });
})
.controller('maliceDataController', function ($http) {
  $http.get('../api/malice/data').then((response) => {
    this.data = response.data;
  });
});
<|endoftext|>


<commit_before>/*
 * DiscoJuice
 *  Work is based upon mock up made by the Kantara ULX group.
 *
 * Author: Andreas Åkre Solberg, UNINETT, andreas.solberg@uninett.no
 * Licence undecided. Awaiting alignment with the licence of the origin Kantara mockup.
 */
if (typeof DiscoJuice == "undefined") var DiscoJuice = {};

DiscoJuice.UI = {
	// Reference to the top level DiscoJuice object
	"parent" : DiscoJuice,

	// The current data model
	"control": null,

	// Reference to the
	"popup": null,

	// Entities / items
	"resulthtml": 'Loading data…',

	"show": function() {
		this.control.load();

		this.popup.fadeIn("slow");
		$("div#discojuice_overlay").show(); // fadeIn("fast");
		this.focusSearch();
	},

	"focusSearch": function() {
		$("input.discojuice_search").focus();
	},
	"hide": function() {
		$("div#discojuice_overlay").fadeOut("slow"); //fadeOut("fast");
		this.popup.fadeOut("slow");
	},

	"clearItems": function() {
		this.resulthtml = '';
	},

	// addItem(item, description, {country, flag}, keywordmatch, distance)
	// addItem(current, current.descr || null, countrydef, search, current.distance);
	"addItem": function(item, countrydef, search, distance) {
		var textLink = '';
		var classes = '';
		if (item.weight < -50) classes += 'hothit';

		var iconpath = this.parent.Utils.options.get('discoPath', '') + 'logos/';
		var flagpath = this.parent.Utils.options.get('discoPath', '') + 'flags/';
		var clear = false;

		var debugweight = this.parent.Utils.options.get('debug.weight', false);

		// Add icon element first
		if (item.icon) {
			textLink += '';
			clear = true;
		}

		// Add title
		textLink += '' + item.title + '';

		// Add matched search term
		if (search && search !== true) {
			textLink += '– ' + search + '';
		} else if (item.descr) {
			textLink += '– ' +  item.descr + '';
		}

		if (countrydef || (distance != undefined)) {

			textLink += '';
			if (countrydef) {
				textLink += '';
				if (countrydef.flag) textLink += ' ';
				textLink += countrydef.country + '';
			}

			if (distance != undefined) {
				if (distance < 1) {
					textLink += 'Nearby';
				} else {
					textLink += '' +  Math.round(distance) + ' km' + '';
				}

			}
			textLink += '';
		}

		if (debugweight) {
			textLink += '
';
			var w = 0;
			if (item.weight) {
				w += item.weight;
			}
			if (item.distanceweight) {
				w += item.distanceweight;
			}
			textLink += 'Weight ' + Math.round(100*w)/100 + ' ';

			if (item.weight) {
				textLink += ' (base ' + item.weight + ')   ';
			}
			if (item.distanceweight) {
				textLink += '(dist ' + Math.round(100*item.distanceweight)/100 + ')';
			}

			textLink += '
';
		}

		// Add a clear bar.
		if (clear) {
			textLink += '
';
		}

		console.log(item);

		// Wrap in A element
		textLink = '' +
			textLink + '';

		this.resulthtml += textLink;
	},

	"refreshData": function(showmore, show, listcount) {
		var that = this;

		this.parent.Utils.log('DiscoJuice.UI refreshData()');

		this.popup.find("div.scroller").empty().append(this.resulthtml);
		this.popup.find("div.scroller a").each(function() {
			var overthere = that;	// Overthere is a reference to the UI object
			$(this).click(function(event) {
				event.preventDefault();
				overthere.hide();
				var entityID = unescape($(this).attr('rel'));
				overthere.control.selectProvider(entityID);
			});
		});

		if (showmore) {
			var moreLink = 'Results limited to ' + show + ' entries – show more…';
			this.popup.find("p.discojuice_moreLinkContainer").empty().append(moreLink);
			this.popup.find("p.discojuice_moreLinkContainer a.discojuice_showmore").click(function(e) {
				event.preventDefault();
				that.control.increase();
			});
		} else {
			this.popup.find("p.discojuice_moreLinkContainer").empty();
			if (listcount > 10) {
				var moreLink = '' + listcount + ' entries listed';
				this.popup.find("p.discojuice_moreLinkContainer").append(moreLink);
			}
		}
	},

	"enable": function(control) {
		var imgpath = this.parent.Utils.options.get('discoPath', '') + 'images/';

		var html = 	'
' +
			'
' +
				' ' +
				'
' + this.parent.Utils.options.get('title', 'Title')  +  '
' +
				'
' + this.parent.Utils.options.get('subtitle', 'Subtitle') + '
' +
			'
' +

			'
' +
				'
' +
					'
 Loading list of providers...
' +
				'
' +
				'

' +
			'
' +

			'
' +
				'
<input type="search" class="discojuice_search" results=5 autosave="discojuice" name="searchfield" placeholder="or search for a provider, in example Univerity of Oslo" value="" />
' +
				'
' +
					'Help me, I cannot find my provider' +
//					'
If your institusion is not connected to Foodle, you may either select to login one of the commercial providers such as Facebook or Google, or you may create a new account using any of the Guest providers, such as Feide OpenIdP.
' +
					'
If your institusion is not connected to Foodle, you may create a new account using any of the Guest providers, such as OpenIdP (Guest users).
' +
				'
' +
			'
' +

			'
' +
				'
' +
					'
' +
						'' +
						'Locate me more accurately using HTML5 Geo-Location' +
					'
' +
					'

' +
				'
' +
				'

' +
			'
' +

			'
' +
				'
DiscoJuice © UNINETT
' +
			'
' +

		'
';
		var that = this;

		if (this.parent.Utils.options.get('overlay', true) === true) {
			var overlay = '

';
			$(overlay).appendTo($("body"));
		}

		this.popup = $(html).appendTo($("body"));

		if (this.parent.Utils.options.get('always', false) === true) {
			this.popup.find(".discojuice_close").hide();
			this.show();
		} else {
			// Add a listener to the sign in button.
			$(control).click(function(event) {
				event.preventDefault();
				that.show();
				return false;
			});
		}

		// Add listeners to the close button.
		this.popup.find(".discojuice_close").click(function() {
			that.hide();
		});

 		// Add toogle for what is this text.
		this.popup.find(".discojuice_what").click(function() {
			that.popup.find(".discojuice_whatisthis").toggleClass("show");
		});

		if (this.parent.Utils.options.get('location', false) && navigator.geolocation) {
			var that = this;
			$("#locateme").click(function(event) {
				var imgpath = that.parent.Utils.options.get('discoPath', '') + 'images/';
				event.preventDefault();
				$("div.locatemebefore").hide();
				$("div.locatemeafter").html('
 Getting your location...
');
				that.control.locateMe();
			});
		} else {
			$("dd#locatemediv").hide();
		}

	},

	"setLocationText": function(html) {
		return $("div.locatemeafter").html(html);
	},

	"addContent": function(html) {
		return $(html).appendTo($("body"));
	},
	"addFilter": function(html) {
		return $(html).prependTo(this.popup.find('.filters'));
//		this.popup.find('.filters').append(html).css('border', '1px solid red');
	}
};

<commit_msg>disable debugging<commit_after>/*
 * DiscoJuice
 *  Work is based upon mock up made by the Kantara ULX group.
 *
 * Author: Andreas Åkre Solberg, UNINETT, andreas.solberg@uninett.no
 * Licence undecided. Awaiting alignment with the licence of the origin Kantara mockup.
 */
if (typeof DiscoJuice == "undefined") var DiscoJuice = {};

DiscoJuice.UI = {
	// Reference to the top level DiscoJuice object
	"parent" : DiscoJuice,

	// The current data model
	"control": null,

	// Reference to the
	"popup": null,

	// Entities / items
	"resulthtml": 'Loading data…',

	"show": function() {
		this.control.load();

		this.popup.fadeIn("slow");
		$("div#discojuice_overlay").show(); // fadeIn("fast");
		this.focusSearch();
	},

	"focusSearch": function() {
		$("input.discojuice_search").focus();
	},
	"hide": function() {
		$("div#discojuice_overlay").fadeOut("slow"); //fadeOut("fast");
		this.popup.fadeOut("slow");
	},

	"clearItems": function() {
		this.resulthtml = '';
	},

	// addItem(item, description, {country, flag}, keywordmatch, distance)
	// addItem(current, current.descr || null, countrydef, search, current.distance);
	"addItem": function(item, countrydef, search, distance) {
		var textLink = '';
		var classes = '';
		if (item.weight < -50) classes += 'hothit';

		var iconpath = this.parent.Utils.options.get('discoPath', '') + 'logos/';
		var flagpath = this.parent.Utils.options.get('discoPath', '') + 'flags/';
		var clear = false;

		var debugweight = this.parent.Utils.options.get('debug.weight', false);

		// Add icon element first
		if (item.icon) {
			textLink += '';
			clear = true;
		}

		// Add title
		textLink += '' + item.title + '';

		// Add matched search term
		if (search && search !== true) {
			textLink += '– ' + search + '';
		} else if (item.descr) {
			textLink += '– ' +  item.descr + '';
		}

		if (countrydef || (distance != undefined)) {

			textLink += '';
			if (countrydef) {
				textLink += '';
				if (countrydef.flag) textLink += ' ';
				textLink += countrydef.country + '';
			}

			if (distance != undefined) {
				if (distance < 1) {
					textLink += 'Nearby';
				} else {
					textLink += '' +  Math.round(distance) + ' km' + '';
				}

			}
			textLink += '';
		}

		if (debugweight) {
			textLink += '
';
			var w = 0;
			if (item.weight) {
				w += item.weight;
			}
			if (item.distanceweight) {
				w += item.distanceweight;
			}
			textLink += 'Weight ' + Math.round(100*w)/100 + ' ';

			if (item.weight) {
				textLink += ' (base ' + item.weight + ')   ';
			}
			if (item.distanceweight) {
				textLink += '(dist ' + Math.round(100*item.distanceweight)/100 + ')';
			}

			textLink += '
';
		}

		// Add a clear bar.
		if (clear) {
			textLink += '
';
		}

		// Wrap in A element
		textLink = '' +
			textLink + '';

		this.resulthtml += textLink;
	},

	"refreshData": function(showmore, show, listcount) {
		var that = this;

		this.parent.Utils.log('DiscoJuice.UI refreshData()');

		this.popup.find("div.scroller").empty().append(this.resulthtml);
		this.popup.find("div.scroller a").each(function() {
			var overthere = that;	// Overthere is a reference to the UI object
			$(this).click(function(event) {
				event.preventDefault();
				overthere.hide();
				var entityID = unescape($(this).attr('rel'));
				overthere.control.selectProvider(entityID);
			});
		});

		if (showmore) {
			var moreLink = 'Results limited to ' + show + ' entries – show more…';
			this.popup.find("p.discojuice_moreLinkContainer").empty().append(moreLink);
			this.popup.find("p.discojuice_moreLinkContainer a.discojuice_showmore").click(function(e) {
				event.preventDefault();
				that.control.increase();
			});
		} else {
			this.popup.find("p.discojuice_moreLinkContainer").empty();
			if (listcount > 10) {
				var moreLink = '' + listcount + ' entries listed';
				this.popup.find("p.discojuice_moreLinkContainer").append(moreLink);
			}
		}
	},

	"enable": function(control) {
		var imgpath = this.parent.Utils.options.get('discoPath', '') + 'images/';

		var html = 	'
' +
			'
' +
				' ' +
				'
' + this.parent.Utils.options.get('title', 'Title')  +  '
' +
				'
' + this.parent.Utils.options.get('subtitle', 'Subtitle') + '
' +
			'
' +

			'
' +
				'
' +
					'
 Loading list of providers...
' +
				'
' +
				'

' +
			'
' +

			'
' +
				'
<input type="search" class="discojuice_search" results=5 autosave="discojuice" name="searchfield" placeholder="or search for a provider, in example Univerity of Oslo" value="" />
' +
				'
' +
					'Help me, I cannot find my provider' +
//					'
If your institusion is not connected to Foodle, you may either select to login one of the commercial providers such as Facebook or Google, or you may create a new account using any of the Guest providers, such as Feide OpenIdP.
' +
					'
If your institusion is not connected to Foodle, you may create a new account using any of the Guest providers, such as OpenIdP (Guest users).
' +
				'
' +
			'
' +

			'
' +
				'
' +
					'
' +
						'' +
						'Locate me more accurately using HTML5 Geo-Location' +
					'
' +
					'

' +
				'
' +
				'

' +
			'
' +

			'
' +
				'
DiscoJuice © UNINETT
' +
			'
' +

		'
';
		var that = this;

		if (this.parent.Utils.options.get('overlay', true) === true) {
			var overlay = '

';
			$(overlay).appendTo($("body"));
		}

		this.popup = $(html).appendTo($("body"));

		if (this.parent.Utils.options.get('always', false) === true) {
			this.popup.find(".discojuice_close").hide();
			this.show();
		} else {
			// Add a listener to the sign in button.
			$(control).click(function(event) {
				event.preventDefault();
				that.show();
				return false;
			});
		}

		// Add listeners to the close button.
		this.popup.find(".discojuice_close").click(function() {
			that.hide();
		});

 		// Add toogle for what is this text.
		this.popup.find(".discojuice_what").click(function() {
			that.popup.find(".discojuice_whatisthis").toggleClass("show");
		});

		if (this.parent.Utils.options.get('location', false) && navigator.geolocation) {
			var that = this;
			$("#locateme").click(function(event) {
				var imgpath = that.parent.Utils.options.get('discoPath', '') + 'images/';
				event.preventDefault();
				$("div.locatemebefore").hide();
				$("div.locatemeafter").html('
 Getting your location...
');
				that.control.locateMe();
			});
		} else {
			$("dd#locatemediv").hide();
		}

	},

	"setLocationText": function(html) {
		return $("div.locatemeafter").html(html);
	},

	"addContent": function(html) {
		return $(html).appendTo($("body"));
	},
	"addFilter": function(html) {
		return $(html).prependTo(this.popup.find('.filters'));
//		this.popup.find('.filters').append(html).css('border', '1px solid red');
	}
};

<|endoftext|>


<commit_before>window.onload = function() {
    var dataseries = makeRandomData(50);

    var svg = d3.select("#selection-demo");
    svg.attr("width", 480).attr("height", 320);
    var xScale = new LinearScale();
    var xAxis = new XAxis(xScale, "bottom");
    var yScale = new LinearScale();
    var yAxis = new YAxis(yScale, "left");
    var renderAreaD1 = new CircleRenderer(dataseries, xScale, yScale);
    var basicTable = new Table([[yAxis, renderAreaD1],
                                [null, xAxis]]);

    var areaInteraction = new AreaInteraction(renderAreaD1); // attach a new AreaInteraction to the render area
    var lastSelection = null; // initially, nothing is selected
    var selectPoints = function(pixelArea) {
        if (lastSelection != null) {
            lastSelection.classed("seleted-point", false); // clear out the last set of selected points
        }
        var selectionArea = renderAreaD1.invertXYSelectionArea(pixelArea);
        var selected = renderAreaD1.getSelectionFromArea(selectionArea);
        selected.classed("selected-point", true); // set a selected class on the points
        lastSelection = selected;
    };
    areaInteraction.callback(selectPoints); // add selectPoints as a callback when a selection is made

    basicTable.anchor(svg).computeLayout().render();
};
<commit_msg>Fixed typo in selectionDemo<commit_after>window.onload = function() {
    var dataseries = makeRandomData(50);

    var svg = d3.select("#selection-demo");
    svg.attr("width", 480).attr("height", 320);
    var xScale = new LinearScale();
    var xAxis = new XAxis(xScale, "bottom");
    var yScale = new LinearScale();
    var yAxis = new YAxis(yScale, "left");
    var renderAreaD1 = new CircleRenderer(dataseries, xScale, yScale);
    var basicTable = new Table([[yAxis, renderAreaD1],
                                [null, xAxis]]);

    var areaInteraction = new AreaInteraction(renderAreaD1); // attach a new AreaInteraction to the render area
    var lastSelection = null; // initially, nothing is selected
    var selectPoints = function(pixelArea) {
        if (lastSelection != null) {
            lastSelection.classed("selected-point", false); // clear out the last set of selected points
        }
        var selectionArea = renderAreaD1.invertXYSelectionArea(pixelArea);
        var selected = renderAreaD1.getSelectionFromArea(selectionArea);
        selected.classed("selected-point", true); // set a selected class on the points
        lastSelection = selected;
    };
    areaInteraction.callback(selectPoints); // add selectPoints as a callback when a selection is made

    basicTable.anchor(svg).computeLayout().render();
};
<|endoftext|>


<commit_before>angular.module('codeview', ['ui.router', 'firebase', 'ui.ace'])

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

  $stateProvider.state('home', {
    url: '/',
    templateUrl: 'templates/home.html',
    controller: 'HomeCtrl'
  }).state('code', {
    url: '/code/:type',
    templateUrl: 'templates/code.html',
    controller: 'CodeCtrl'
  });

  $urlRouterProvider.otherwise('/');
})

.controller('HomeCtrl', function($scope) {
  $scope.test = 'asdf';
  // Closes the sidebar menu
  $("#menu-close").click(function(hi) {
    hi.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
  });

  // Opens the sidebar menu
  $("#menu-toggle").click(function(hi) {
    hi.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
  });

  // Scrolls to the selected menu item on the page
  $(function() {
    $('a[href*=#]:not([href=#])').click(function() {
      if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 1000);
          return false;
        }
      }
    });
  });
})

.controller('CodeCtrl', function($scope, $stateParams, Room, $http) {
  var coder = $scope.coder = mycoder = (($stateParams.type || 'code') === 'code');

  var aces = [];

  $scope.aceOpts = {
    theme: 'monokai',
    rendererOptions: {
      fontSize: 13
    },
    onLoad: function(ace) {
      ace.$blockScrolling = Infinity;
      aces.push(ace);
    }
  };

  $scope.updateLang = function() {
    try {
      var mode = $scope.data.lang.id.split('/')[0];
      for (var i = 0; i < aces.length; i++) {
        var ace = aces[i];
        ace.getSession().setMode('ace/mode/' + mode.toLowerCase());
      }
    } catch (e) {
      console.log(e);
    }
  };

  $scope.code = '// Enter code here \n';
  $scope.code2 = '// Interviewer comments\n';
  $scope.data = {};
  var room = Room('test');
  room.$loaded().then(function() {
    $scope.data = room;
    $scope.code = room.code;
    $scope.code2 = room.code2;
    $scope.updateLang();
  });
  room.$bindTo($scope, 'data');

  if (coder) {
    // Allow editing code
    $scope.$watch('code', function() {
      if ($scope.code) {
        $scope.data.code = $scope.code;
      }
    });
    $scope.$watch('data', function() {
      $scope.code2 = $scope.data.code2;
    });
  } else {
    // Only read code
    $scope.$watch('data', function() {
      $scope.code = $scope.data.code;
    });
    $scope.$watch('code2', function() {
      if ($scope.code2) {
        $scope.data.code2 = $scope.code2;
      }
    });
  }

  execute = function(code) {
    $http.post('/execute', {
      code: code,
      lang: $scope.data.lang.id
    }).
    success(function(data, status, headers, config) {
      console.log(data);
    }).
    error(function(data, status, headers, config) {
      console.log(data);
    });
  }

  $scope.execute1 = function() {
    console.log($scope.code);
    execute($scope.code);
  }

  $scope.execute2 = function() {
    execute($scope.code2);
  }

  $scope.langs = [];
  $http.get('/langs').then(function(data) {
    $scope.langs = data.data;
  });
})

.factory('Room', function($firebase) {
  return function(room) {
    var ref = new Firebase("https://codeview1.firebaseio.com/rooms/").child(room);
    return $firebase(ref).$asObject();
  }
});
<commit_msg>Enable wrapping<commit_after>angular.module('codeview', ['ui.router', 'firebase', 'ui.ace'])

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

  $stateProvider.state('home', {
    url: '/',
    templateUrl: 'templates/home.html',
    controller: 'HomeCtrl'
  }).state('code', {
    url: '/code/:type',
    templateUrl: 'templates/code.html',
    controller: 'CodeCtrl'
  });

  $urlRouterProvider.otherwise('/');
})

.controller('HomeCtrl', function($scope) {
  $scope.test = 'asdf';
  // Closes the sidebar menu
  $("#menu-close").click(function(hi) {
    hi.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
  });

  // Opens the sidebar menu
  $("#menu-toggle").click(function(hi) {
    hi.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
  });

  // Scrolls to the selected menu item on the page
  $(function() {
    $('a[href*=#]:not([href=#])').click(function() {
      if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 1000);
          return false;
        }
      }
    });
  });
})

.controller('CodeCtrl', function($scope, $stateParams, Room, $http) {
  var coder = $scope.coder = mycoder = (($stateParams.type || 'code') === 'code');

  var aces = [];

  $scope.aceOpts = {
    theme: 'monokai',
    useWrapMode: true,
    rendererOptions: {
      fontSize: 13
    },
    onLoad: function(ace) {
      ace.$blockScrolling = Infinity;
      aces.push(ace);
    }
  };

  $scope.updateLang = function() {
    try {
      var mode = $scope.data.lang.id.split('/')[0];
      for (var i = 0; i < aces.length; i++) {
        var ace = aces[i];
        ace.getSession().setMode('ace/mode/' + mode.toLowerCase());
      }
    } catch (e) {
      console.log(e);
    }
  };

  $scope.code = '// Enter code here \n';
  $scope.code2 = '// Interviewer comments\n';
  $scope.data = {};
  var room = Room('test');
  room.$loaded().then(function() {
    $scope.data = room;
    $scope.code = room.code;
    $scope.code2 = room.code2;
    $scope.updateLang();
  });
  room.$bindTo($scope, 'data');

  if (coder) {
    // Allow editing code
    $scope.$watch('code', function() {
      if ($scope.code) {
        $scope.data.code = $scope.code;
      }
    });
    $scope.$watch('data', function() {
      $scope.code2 = $scope.data.code2;
    });
  } else {
    // Only read code
    $scope.$watch('data', function() {
      $scope.code = $scope.data.code;
    });
    $scope.$watch('code2', function() {
      if ($scope.code2) {
        $scope.data.code2 = $scope.code2;
      }
    });
  }

  execute = function(code) {
    $http.post('/execute', {
      code: code,
      lang: $scope.data.lang.id
    }).
    success(function(data, status, headers, config) {
      console.log(data);
    }).
    error(function(data, status, headers, config) {
      console.log(data);
    });
  }

  $scope.execute1 = function() {
    console.log($scope.code);
    execute($scope.code);
  }

  $scope.execute2 = function() {
    execute($scope.code2);
  }

  $scope.langs = [];
  $http.get('/langs').then(function(data) {
    $scope.langs = data.data;
  });
})

.factory('Room', function($firebase) {
  return function(room) {
    var ref = new Firebase("https://codeview1.firebaseio.com/rooms/").child(room);
    return $firebase(ref).$asObject();
  }
});
<|endoftext|>


<commit_before>angular.module('biBuilder', [])
.controller('MainCtrl', ['$scope', function($scope) {

	$scope.gridSizeX = 20;
	$scope.gridSizeY = 20;

	$scope.gridX = 50;
	$scope.gridY = 50;

	$scope.totalX = $scope.gridSizeX * ($scope.gridX);
	$scope.totalY = $scope.gridSizeY * ($scope.gridY);

	$scope.getNumber = function(num) {
		return new Array(num);
	}

	//Buildings Prototype
	function Unit(){
		this.name = '';
		this.id = -1;
		this.color = "#FFF";
		this.height = 2;
		this.width = 2;
	}

	$scope.units = [];

	//fake data
	var unit = new Unit();
	unit.name = 'Zone R';
	unit.id = 1;
	unit.color = "green";
	unit.height = 2;
	unit.width = 2;

	$scope.units.push( unit  );

	var unit = new Unit();
	unit.name = 'Zone I';
	unit.id = 2;
	unit.color = "yellow";
	unit.height = 3;
	unit.width = 2;

	$scope.units.push( unit  );
	//fake data

}])
.directive('draggable', function($document) {
return function(scope, element, attr) {

	//referenciel #grid;
	var refX = jQuery('#grid').offset().left;
	var refY = jQuery('#grid').offset().top;

	element.css({
		position: 'relative',
		border: '1px solid red',
		backgroundColor: 'lightgrey',
		cursor: 'pointer',
		display: 'block',
		width: scope.gridSizeX + 'px',
		height: scope.gridSizeX + 'px'
	});

	element.on('mousedown', function(event) {
		// Prevent default dragging of selected content
		event.preventDefault();

		//console.log ('screen ' + event.clientX + ' / ' + event.clientY);

		var copie = $(element).clone();

		copie.css({
			position: 'absolute',
			border: '1px solid green',
			backgroundColor: 'lightgrey',
			cursor: 'pointer',
			display: 'block',
			width: scope.gridSizeX * 2 + 'px',
			height: scope.gridSizeX * 2 + 'px',
			left: event.pageX - scope.gridSizeX/2 + 'px',
			top: event.pageY - scope.gridSizeY/2 + 'px'
		});

		copie.appendTo('body');

		function mousemove(event) {
			y = event.pageY;
			x = event.pageX;
			//console.log(copie);
			//console.log ('befor ' + x + ' x ' + y);

			var caseX = Math.floor((x - refX) / scope.gridSizeX);
			var caseY = Math.floor((y - refY) / scope.gridSizeY);
			//console.log('caseY = ' + caseY + ' X ' + caseX);

			//Snapping elmt to the grid
			if (caseY >= 0 && caseX >= 0 && caseY < scope.gridY && caseX < scope.gridX) {
				//console.log('inside the grid');

				//console.log("y= " + y + " scope=" + scope.gridSizeY + ' mod=' + ( y % scope.gridSizeY ));
				y = (caseY * scope.gridSizeY + refY);
				x = (caseX * scope.gridSizeX + refX);
			}
			else {
				//console.log('outside the grid');
			}

			//console.log ('after ' + x + ' / ' + y);
			//console.log ('abspo ' + jQuery(element).offset().left + ' / ' + jQuery(element).offset().top);

			copie.css({
				top: y + 'px',
				left: x  + 'px'
			});
		}

		function mouseup(event) {
			//console.log('mouseup');

			$document.off('mousemove', mousemove);
			$document.off('mouseup', mouseup);
		}

		function mousedown(event) {
			event.preventDefault();

			//console.log('mousedown');

			$document.on('mousemove', mousemove);
			$document.on('mouseup', mouseup);
		}

		$document.on('mousemove', mousemove);
		copie.on('mousedown', mousedown);
		$document.on('mouseup', mouseup);

		//clonedElm = $(element).clone();
		//console.log(clonedElm);
/*
		clonedElm.css({
			position: 'absolute',
			border: '1px solid green',
			backgroundColor: 'lightgrey',
			cursor: 'pointer',
			display: 'block',
			width: scope.gridSizeX + 'px',
			height: scope.gridSizeX + 'px',
			left: absX + 'px',
			top: absY + 'px'
		});
*/
		//$(event.srcElement).parent().append(clonedElm);

//		clonedElm.on('mousemove', mousemove);
//		clonedElm.on('mouseup', mouseup);
	});
/*
	//start Values - used for relative mvmt
	var startX = 0, startY = 0, x = 0, y = 0;

	//referenciel #grid;
	var refY = jQuery('#grid').offset().top;
	var refX = jQuery('#grid').offset().left;

	var baseDiffX = refX - jQuery(element).offset().left;
	var baseDiffY = refY - jQuery(element).offset().top;

	console.log ('difff ' + baseDiffX + ' / ' + baseDiffY);

	element.css({
		position: 'relative',
		border: '1px solid red',
		backgroundColor: 'lightgrey',
		cursor: 'pointer',
		display: 'block',
		width: scope.gridSizeX + 'px',
		height: scope.gridSizeX + 'px'
	});

	element.on('mousedown', function(event) {
		// Prevent default dragging of selected content
		event.preventDefault();
		startX = event.screenX - x;
		startY = event.screenY - y;
		$document.on('mousemove', mousemove);
		$document.on('mouseup', mouseup);
	});

	function mousemove(event) {
		y = event.screenY - startY;
		x = event.screenX - startX;

		//console.log ('befor ' + x + ' x ' + y);

		var absX = jQuery(element).offset().left;
		var absY = jQuery(element).offset().top;

		//Snapping elmt to the grid
		if ((refX < absX && (refX + scope.totalX) > absX) && (refY < absY && (refY + scope.totalY) > absY) ) {
			//console.log("y= " + y + " scope=" + scope.gridSizeY + ' mod=' + ( y % scope.gridSizeY ));
			//y = y - ( y % scope.gridSizeY );
			//x = x - ( x % scope.gridSizeX );
		}
		else {
			//console.log('outside the grid');
		}

		//console.log ('after ' + x + ' / ' + y);
		//console.log ('abspo ' + jQuery(element).offset().left + ' / ' + jQuery(element).offset().top);

		element.css({
			top: y + 'px',
			left:  x + 'px'
		});
	}

	function mouseup() {
		console.log('mouseup');

		x = event.screenX - startX;
		y = event.screenY - startY;

		var absX = jQuery(element).offset().left;
		var absY = jQuery(element).offset().top;

		console.log ('befor ' + x + ' x ' + y);
		console.log ('relat ' + absX + ' x ' + absY);
		console.log ('refer ' + refX + ' / ' + refY);
		console.log ('difff ' + baseDiffX + ' / ' + baseDiffY);

		if ((refX < absX && (refX + scope.totalX) > absX) && (refY < absY && (refY + scope.totalY) > absY) )
		{
			//in  : OK;
			console.log("y= " + y + " scope=" + scope.gridSizeY + ' mod=' + ( y % scope.gridSizeY ));
			//y = y - ( y % scope.gridSizeY );

			element.css({
				//top: ( y % scope.gridSizeY ) + 'px'
				//left:  0 + 'px'
			});
		}
		else {
			//outside the grid : reseting elmt position.

			element.css({
				top: 0 + 'px',
				left:  0 + 'px'
			});

			//reset elmt position if outside the grid;
			startX = 0;
			startY = 0;

			x = 0;
			y = 0;

		}

		$document.off('mousemove', mousemove);
		$document.off('mouseup', mouseup);
	}

	*/
};
});
<commit_msg>~debug<commit_after>angular.module('biBuilder', [])
.controller('MainCtrl', ['$scope', function($scope) {

	$scope.gridSizeX = 20;
	$scope.gridSizeY = 20;

	$scope.gridX = 50;
	$scope.gridY = 50;

	$scope.totalX = $scope.gridSizeX * ($scope.gridX);
	$scope.totalY = $scope.gridSizeY * ($scope.gridY);

	$scope.getNumber = function(num) {
		return new Array(num);
	}

	//Buildings Prototype
	function Unit(){
		this.name = '';
		this.id = -1;
		this.color = "#FFF";
		this.height = 2;
		this.width = 2;
	}

	$scope.units = [];

	//fake data
	var unit = new Unit();
	unit.name = 'Zone R';
	unit.id = 1;
	unit.color = "green";
	unit.height = 2;
	unit.width = 2;

	$scope.units.push( unit  );

	var unit = new Unit();
	unit.name = 'Zone I';
	unit.id = 2;
	unit.color = "yellow";
	unit.height = 3;
	unit.width = 2;

	$scope.units.push( unit  );
	//fake data

}])
.directive('draggable', function($document) {
return function(scope, element, attr) {

	//referenciel #grid;
	var refX = jQuery('#grid').offset().left;
	var refY = jQuery('#grid').offset().top;

	element.css({
		position: 'relative',
		border: '1px solid red',
		backgroundColor: 'lightgrey',
		cursor: 'pointer',
		display: 'block',
		width: scope.gridSizeX + 'px',
		height: scope.gridSizeX + 'px'
	});

	element.on('mousedown', function(event) {
		// Prevent default dragging of selected content
		event.preventDefault();

		//console.log ('screen ' + event.clientX + ' / ' + event.clientY);

		var copie = $(element).clone();

		copie.css({
			position: 'absolute',
			border: '1px solid green',
			backgroundColor: 'lightgrey',
			cursor: 'pointer',
			display: 'block',
			width: scope.gridSizeX * 2 + 'px',
			height: scope.gridSizeX * 2 + 'px',
			left: event.pageX - scope.gridSizeX/2 + 'px',
			top: event.pageY - scope.gridSizeY/2 + 'px'
		});

		copie.appendTo('body');

		function mousemove(event) {
			y = event.pageY;
			x = event.pageX;
			//console.log(copie);
			console.log ('befor ' + x + ' x ' + y);

			var caseX = Math.floor((x - refX) / scope.gridSizeX);
			var caseY = Math.floor((y - refY) / scope.gridSizeY);
			console.log('caseY = ' + caseY + ' X ' + caseX);

			//Snapping elmt to the grid
			if (caseY >= 0 && caseX >= 0 && caseY < scope.gridY && caseX < scope.gridX) {
				//console.log('inside the grid');

				//console.log("y= " + y + " scope=" + scope.gridSizeY + ' mod=' + ( y % scope.gridSizeY ));
				y = (caseY * scope.gridSizeY + refY);
				x = (caseX * scope.gridSizeX + refX);
			}
			else {
				//console.log('outside the grid');
			}

			console.log ('after ' + x + ' / ' + y);
			//console.log ('abspo ' + jQuery(element).offset().left + ' / ' + jQuery(element).offset().top);

			copie.css({
				top: y + 'px',
				left: x  + 'px'
			});
		}

		function mouseup(event) {
			//console.log('mouseup');

			$document.off('mousemove', mousemove);
			$document.off('mouseup', mouseup);
		}

		function mousedown(event) {
			event.preventDefault();

			//console.log('mousedown');

			$document.on('mousemove', mousemove);
			$document.on('mouseup', mouseup);
		}

		$document.on('mousemove', mousemove);
		copie.on('mousedown', mousedown);
		$document.on('mouseup', mouseup);

		//clonedElm = $(element).clone();
		//console.log(clonedElm);
/*
		clonedElm.css({
			position: 'absolute',
			border: '1px solid green',
			backgroundColor: 'lightgrey',
			cursor: 'pointer',
			display: 'block',
			width: scope.gridSizeX + 'px',
			height: scope.gridSizeX + 'px',
			left: absX + 'px',
			top: absY + 'px'
		});
*/
		//$(event.srcElement).parent().append(clonedElm);

//		clonedElm.on('mousemove', mousemove);
//		clonedElm.on('mouseup', mouseup);
	});
/*
	//start Values - used for relative mvmt
	var startX = 0, startY = 0, x = 0, y = 0;

	//referenciel #grid;
	var refY = jQuery('#grid').offset().top;
	var refX = jQuery('#grid').offset().left;

	var baseDiffX = refX - jQuery(element).offset().left;
	var baseDiffY = refY - jQuery(element).offset().top;

	console.log ('difff ' + baseDiffX + ' / ' + baseDiffY);

	element.css({
		position: 'relative',
		border: '1px solid red',
		backgroundColor: 'lightgrey',
		cursor: 'pointer',
		display: 'block',
		width: scope.gridSizeX + 'px',
		height: scope.gridSizeX + 'px'
	});

	element.on('mousedown', function(event) {
		// Prevent default dragging of selected content
		event.preventDefault();
		startX = event.screenX - x;
		startY = event.screenY - y;
		$document.on('mousemove', mousemove);
		$document.on('mouseup', mouseup);
	});

	function mousemove(event) {
		y = event.screenY - startY;
		x = event.screenX - startX;

		//console.log ('befor ' + x + ' x ' + y);

		var absX = jQuery(element).offset().left;
		var absY = jQuery(element).offset().top;

		//Snapping elmt to the grid
		if ((refX < absX && (refX + scope.totalX) > absX) && (refY < absY && (refY + scope.totalY) > absY) ) {
			//console.log("y= " + y + " scope=" + scope.gridSizeY + ' mod=' + ( y % scope.gridSizeY ));
			//y = y - ( y % scope.gridSizeY );
			//x = x - ( x % scope.gridSizeX );
		}
		else {
			//console.log('outside the grid');
		}

		//console.log ('after ' + x + ' / ' + y);
		//console.log ('abspo ' + jQuery(element).offset().left + ' / ' + jQuery(element).offset().top);

		element.css({
			top: y + 'px',
			left:  x + 'px'
		});
	}

	function mouseup() {
		console.log('mouseup');

		x = event.screenX - startX;
		y = event.screenY - startY;

		var absX = jQuery(element).offset().left;
		var absY = jQuery(element).offset().top;

		console.log ('befor ' + x + ' x ' + y);
		console.log ('relat ' + absX + ' x ' + absY);
		console.log ('refer ' + refX + ' / ' + refY);
		console.log ('difff ' + baseDiffX + ' / ' + baseDiffY);

		if ((refX < absX && (refX + scope.totalX) > absX) && (refY < absY && (refY + scope.totalY) > absY) )
		{
			//in  : OK;
			console.log("y= " + y + " scope=" + scope.gridSizeY + ' mod=' + ( y % scope.gridSizeY ));
			//y = y - ( y % scope.gridSizeY );

			element.css({
				//top: ( y % scope.gridSizeY ) + 'px'
				//left:  0 + 'px'
			});
		}
		else {
			//outside the grid : reseting elmt position.

			element.css({
				top: 0 + 'px',
				left:  0 + 'px'
			});

			//reset elmt position if outside the grid;
			startX = 0;
			startY = 0;

			x = 0;
			y = 0;

		}

		$document.off('mousemove', mousemove);
		$document.off('mouseup', mouseup);
	}

	*/
};
});
<|endoftext|>


<commit_before>// API call
$(document).ready(function() {
  getId()
})
var id = []
var farm  = []
var server = []
var secret = []
var title = []
var orientation = ""
var random = Math.floor(Math.random() * 18)
function getId(){
  var url = "https://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=850fe695ff16c8b0d94eb86407512d53&user_id=149907004@N05&format=json&nojsoncallback=1"
   $.get(url)
  .then(function(data){
    for (var i=0; i<(data.photos.photo).length; i++){
      id.push(+data.photos.photo[i].id)
      farm.push(+data.photos.photo[i].farm)
      server.push(+data.photos.photo[i].server)
      secret.push(data.photos.photo[i].secret)
      title.push(data.photos.photo[i].title)
    }
    if (id[random] === 34119127771 || id[random] === 33865752870 || id[random] === 34119127641 || id[random] === 34119127511 || id[random] === 33865752520 || id[random] === 34249268725 || id[random] === 34118930141 || id[random] === 34118929981 || id[random] === 33439283403 || id[random] === 33439283263){
      orientation = "portrait"
    } else {
      orientation = "landscape"
    }

    console.log(id[random])
    console.log(farm[random])
    console.log(server[random])
    console.log(secret[random])
    console.log ('https://c1.staticflickr.com/' + farm[random] + '/' + server[random] + '/' + id[random] + '_' + secret[random] + '_z.jpg')
    updatePage(farm, server, id, secret)

  })
}
function updatePage(farm, server, id, secret){
    $(".origArt").append("")
}

//pixel grid
var colorPicker = document.querySelector('.paint-container')
var currentColor = "#fff"
colorPicker.addEventListener('click', function () {
  var property = window.getComputedStyle(event.target)
  var color = property.getPropertyValue("background-color")
  console.log(color)
  currentColor=color
})
function createCell (){
  var gridContainer = document.querySelector(".pixel")
  for (var i=0; i<6825; i++){
    var newCell = document.createElement('div')
    // set

    newCell.classList.add('cell')
    gridContainer.appendChild(newCell)
  }
  if (orientation === "landscape"){
    gridContainer.classList.add('landscape')
  }
  else {
    gridContainer.classList.add('portrait')
  }
  gridContainer.addEventListener('click', function () {
    if (event.target.classList.contains("cell")){
    event.target.style.backgroundColor = currentColor
  }})
}

  createCell()

// function updatePage(farm, server, id, secret){
//   $(".origArt").append("")
// }
// var grid = $(".grid")
// function createGrid (x, y) {
// 	while (grid.firstChild) {
//   	grid.removeChild(grid.firstChild);
//   }
// 	// set grid width so that divs will properly wrap
//   grid.style.width = (6) * x + 'px'
//   // get total number of new individual cells needed
//   var cellCount = x * y
//   // iterate through and create each new cell
//   for (var i = 1; i <= cellCount; i++) {
//     var newCell = document.createElement('div')
//     // set

//     newCell.classList.add('cell')
//     newCell.setAttribute('id', i)
//     // newCell.textContent = i
//     grid.appendChild(newCell)
//     // set cell size to requested px size
//     newCell.style.width = '4px'
//     newCell.style.height = '4px'
//   }
// }

// function checkOrientation (orientation) {
//   if (orientation === "landscape") {
//     createGrid(200, 150)
//   } else {
//     createGrid(150, 200)
//   }
// }
// checkOrientation("landscape")
// var colorPicker = document.querySelector('.paint-container')
// var currentColor = "#fff"
// colorPicker.addEventListener('click', function () {
//   var property = window.getComputedStyle(event.target)
//   var color = property.getPropertyValue("background-color")
//   console.log(color)
//   currentColor=color
// })
<commit_msg>Added id = i to cell generator<commit_after>// API call
$(document).ready(function() {
  getId()
})
var id = []
var farm  = []
var server = []
var secret = []
var title = []
var orientation = ""
var random = Math.floor(Math.random() * 18)
function getId(){
  var url = "https://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=850fe695ff16c8b0d94eb86407512d53&user_id=149907004@N05&format=json&nojsoncallback=1"
   $.get(url)
  .then(function(data){
    for (var i=0; i<(data.photos.photo).length; i++){
      id.push(+data.photos.photo[i].id)
      farm.push(+data.photos.photo[i].farm)
      server.push(+data.photos.photo[i].server)
      secret.push(data.photos.photo[i].secret)
      title.push(data.photos.photo[i].title)
    }
    if (id[random] === 34119127771 || id[random] === 33865752870 || id[random] === 34119127641 || id[random] === 34119127511 || id[random] === 33865752520 || id[random] === 34249268725 || id[random] === 34118930141 || id[random] === 34118929981 || id[random] === 33439283403 || id[random] === 33439283263){
      orientation = "portrait"
    } else {
      orientation = "landscape"
    }

    console.log(id[random])
    console.log(farm[random])
    console.log(server[random])
    console.log(secret[random])
    console.log ('https://c1.staticflickr.com/' + farm[random] + '/' + server[random] + '/' + id[random] + '_' + secret[random] + '_z.jpg')
    updatePage(farm, server, id, secret)

  })
}
function updatePage(farm, server, id, secret){
    $(".origArt").append("")
}

//pixel grid
var colorPicker = document.querySelector('.paint-container')
var currentColor = "#fff"
colorPicker.addEventListener('click', function () {
  var property = window.getComputedStyle(event.target)
  var color = property.getPropertyValue("background-color")
  console.log(color)
  currentColor=color
})
function createCell (){
  var gridContainer = document.querySelector(".pixel")
  for (var i=0; i<6825; i++){
    var newCell = document.createElement('div')
    // set

    newCell.classList.add('cell')
    newCell.setAttribute('id', i)
    gridContainer.appendChild(newCell)
  }
  if (orientation === "landscape"){
    gridContainer.classList.add('landscape')
  }
  else {
    gridContainer.classList.add('portrait')
  }
  gridContainer.addEventListener('click', function () {
    if (event.target.classList.contains("cell")){
    event.target.style.backgroundColor = currentColor
  }})
}

  createCell()

// function updatePage(farm, server, id, secret){
//   $(".origArt").append("")
// }
// var grid = $(".grid")
// function createGrid (x, y) {
// 	while (grid.firstChild) {
//   	grid.removeChild(grid.firstChild);
//   }
// 	// set grid width so that divs will properly wrap
//   grid.style.width = (6) * x + 'px'
//   // get total number of new individual cells needed
//   var cellCount = x * y
//   // iterate through and create each new cell
//   for (var i = 1; i <= cellCount; i++) {
//     var newCell = document.createElement('div')
//     // set

//     newCell.classList.add('cell')
//     newCell.setAttribute('id', i)
//     // newCell.textContent = i
//     grid.appendChild(newCell)
//     // set cell size to requested px size
//     newCell.style.width = '4px'
//     newCell.style.height = '4px'
//   }
// }

// function checkOrientation (orientation) {
//   if (orientation === "landscape") {
//     createGrid(200, 150)
//   } else {
//     createGrid(150, 200)
//   }
// }
// checkOrientation("landscape")
// var colorPicker = document.querySelector('.paint-container')
// var currentColor = "#fff"
// colorPicker.addEventListener('click', function () {
//   var property = window.getComputedStyle(event.target)
//   var color = property.getPropertyValue("background-color")
//   console.log(color)
//   currentColor=color
// })
<|endoftext|>


<commit_before>(function(){

   // Spalten ind er Reihenfolge der Darstellung
   var columns = ['Name', 'Titel', 'Views'];

   document.addEventListener('DOMContentLoaded', function() {
      //Filter einblenden
      var body = document.getElementsByTagName("BODY")[0];
      body.style.maxWidth = '600px';
      body.style.padding = '10px';

      // Load Positions
      var request = new XMLHttpRequest();
      request.open('GET', '/positions', true);
      request.onload = function() {
         if(request.status >= 200 && request.status < 400) {
            var data = JSON.parse(request.responseText);
            var positions = {};
            for(let i in data) {
            }
            console.log(data);
         } else {
            // Error
         }
      };
      request.onerror = function() {
         // There was a connection error of some sort
         console.log('There was an error in xmlHttpRequest!');
      };
      request.send();
   });
})();<commit_msg>display data<commit_after>(function(){

   document.addEventListener('DOMContentLoaded', function() {
      //Filter einblenden
      var body = document.getElementsByTagName("BODY")[0];
      body.style.maxWidth = '600px';
      body.style.padding = '10px';

      // Load Positions
      var request = new XMLHttpRequest();
      request.open('GET', '/positions', true);
      request.onload = function() {
         if(request.status >= 200 && request.status < 400) {
            var data = JSON.parse(request.responseText);
            body.appendChild(btable(data));
            console.log(data);
         } else {
            // Error
         }
      };
      request.onerror = function() {
         // There was a connection error of some sort
         console.log('There was an error in xmlHttpRequest!');
      };
      request.send();
   });

   // Spalten ind er Reihenfolge der Darstellung
   var columns = ['Market', 'Asset', 'Pair', 'Amount', 'open', 'last', 'Tot BTC', 'Tot USD'];

   var btable = function(positions) {
      var t = document.createElement('table');
      t.className = 'table-striped';
      t.width = '100%';
      t.maxWidth = '400px';
      var thead = document.createElement('thead');
      var tr = document.createElement('tr');
      var th;
      for (var c in columns) {
         th = document.createElement('th');
         th.innerHTML = columns[c];
         tr.appendChild(th);
      }
      thead.appendChild(tr);
      t.appendChild(thead);
      var tbody = document.createElement('tbody');
      for (let i in positions) {
         tbody.appendChild(positionsRow(positions[i]));
      }
      t.appendChild(tbody);
      return t;
   };

   var positionsRow = function(position) {
      var cols = {};
      for (var i in columns) {
         cols[columns[i]] = {};
      }
      var tr = document.createElement('tr');
      var ftd = function(html, align) {
         if(typeof align==='undefined' ){
            align = 'left';
         }
         var td = document.createElement('td');
         if(typeof html === 'object') {
            td.appendChild(html);
         } else if(typeof html === 'undefined') {
            td.innerHTML = '';
         } else {
            td.innerHTML = html;
         }
         td.style.textAlign = align;
         return td;
      };
      cols.Market = ftd(position.name);
      cols.Asset = ftd(position.counter);
      cols.Pair = ftd(position.base + '_' + position.counter);
      cols.Amount = ftd(position.amount, 'right');
      cols.open = ftd(position.open, 'right');
      cols.last = ftd(position.rates[0].last, 'right');
      let btc = position.rates[0].last * position.amount;
      cols['Tot BTC'] = ftd(btc, 'right');
      cols['Tot USD'] = ftd(btc * 1330);
      for (var i in cols) {
         tr.appendChild(cols[i]);
      }
      return tr;
   };
})();<|endoftext|>


<commit_before>var app = angular.module('infinityRPG', ['ngRoute', 'ngCookies']);

app.controller('GameController', function ($scope, $http, $cookies, $location) {
	var cookieToken = $cookies.get('token');
	$scope.me = $cookies.get('user');

	$scope.getHpBar = function (user) {
		var percentage = (user.hp/user.maxHp)*100 + '%';
		return percentage;
	};

	$scope.getLvl = function (user) {
		if (user) {
				return parseInt(Math.sqrt(user.exp));
		}
	};

	$scope.getBarClass = function (user) {
		if (user.hp/user.maxHp > 0.6) {
			return 'progress-bar-info';
		} else if (user.hp/user.maxHp > 0.3) {
			return 'progress-bar-warning';
		} else {
			return 'progress-bar-danger';
		}
	};

	$scope.useItem = function ( itemName ) {
		$http.get('/api/items/use/' + itemName,
			{ headers: { 'x-access-token' : cookieToken } })
			.then( function (res) {
				$scope.getPlayers();
			}, function (res) {
				console.log('Error on using item');
			});
	};

	$scope.attack = function (user) {
		var defender = {};
		defender.username = user.username;

		if (defender.username != $scope.me.username) {
			$http.post('/api/1x1', defender,
				{ headers: {'x-access-token' : cookieToken } })
				.then ( function (res) {
					if (res.data.attacker) {
						var attackerName = res.data.attacker.username;
						var defenderName = res.data.defender.username;

						$scope.me = res.data.attacker;
						$scope.players[attackerName] = res.data.attacker;
						(res.data.defender.hp < 0)
							?	delete $scope.players[defenderName]
							: $scope.players[defenderName] = res.data.defender;
					} else { //ATTACKER DIED
						console.log(res.data);

						$location.path('/');

					}

				}, function (res) {
					console.log('Error');
				});

		} else { //ATTACKING SELF
			console.log("Can't attack yourself!");
		}

	};

	$scope.upgradeStat = function (stat) {
		$http.post('/api/me/stats', { stat: stat},
			{ headers: {'x-access-token': cookieToken } })
			.then ( function (res) {
				$scope.getMe(cookieToken);
			}, function (res) {
				console.log('Error upgrading stat.');
			})
	};

	$scope.getMe = function(cookieToken) {
		$http.get('/api/me',
			{ headers: {'x-access-token' : cookieToken } })
			.then ( function (res) {
				$scope.me = res.data;
				if (!$scope.me) $location.path('/');
			}, function (res) {
				console.log('Error fetching data.');
			});
	};

	$scope.getPlayers = function() {
		$http.get('/api/users',
			{ headers: {'x-access-token' : cookieToken } })
			.then( function (res) {
				$scope.players = res.data;
			}, function (res) {
				console.log('Error fetching players.');
		});
	};

	$scope.getMe(cookieToken);
	$scope.getPlayers();
	var refreshPlayers = setInterval( function(){ $scope.getPlayers(); }, 30000);

});

app.controller('LoginController', function ($scope, $http, $location, $cookies) {

	$scope.signup = function (user) {
		$http.post('/api/signup', user)
			.then( function (res) {
				if (res.data.token) {
					$cookies.put('token', res.data.token);
					window.localStorage.setItem('user', JSON.stringify(res.data.user));
					$location.path('/play');
				} else {
					delete $scope.user.username;
					delete $scope.user.password;
					$scope.error = 'Error on login';
				}

			}, function (res) {
				console.log('Error on signup');
			});
	};

	$scope.auth = function (user) {
		$http.post('/api/auth', user)
			.then ( function (res) {
				if (res.data.token){
					$cookies.put('token', res.data.token);
					$location.path('/play');
				}

			}, function (res) {
				$scope.error = 'Error on login.';
			});
	};

});

app.config( function ($routeProvider, $locationProvider) {
	$routeProvider
		.when('/',
		{
			controller: 'LoginController',
			templateUrl: 'partials/login.html'
		})

		.when('/play',
		{
			controller: 'GameController',
			templateUrl: 'partials/game.html'
		})

		.when ('/signup',
		{
			controller: 'SignupController',
			templateUrl: 'partials/signup.html'
		})
		.otherwise(
		{
			redirectTo: '/'
		});

});
<commit_msg>Waiting before sending another attack.<commit_after>var app = angular.module('infinityRPG', ['ngRoute', 'ngCookies']);

app.controller('GameController', function ($scope, $http, $cookies, $location) {
	var cookieToken = $cookies.get('token');
	$scope.me = $cookies.get('user');

	$scope.getHpBar = function (user) {
		var percentage = (user.hp/user.maxHp)*100 + '%';
		return percentage;
	};

	$scope.getLvl = function (user) {
		if (user) {
				return parseInt(Math.sqrt(user.exp));
		}
	};

	$scope.getBarClass = function (user) {
		if (user.hp/user.maxHp > 0.6) {
			return 'progress-bar-info';
		} else if (user.hp/user.maxHp > 0.3) {
			return 'progress-bar-warning';
		} else {
			return 'progress-bar-danger';
		}
	};

	$scope.useItem = function ( itemName ) {
		$http.get('/api/items/use/' + itemName,
			{ headers: { 'x-access-token' : cookieToken } })
			.then( function (res) {
				$scope.getPlayers();
			}, function (res) {
				console.log('Error on using item');
			});
	};

	$scope.attack = function (user) {
		if ($scope.attacking) {
			$scope.error = 'Wait!';
		} else {
			$scope.attacking = true;
			var defender = {};
			defender.username = user.username;

			if (defender.username != $scope.me.username) {
				$http.post('/api/1x1', defender,
					{ headers: {'x-access-token' : cookieToken } })
					.then ( function (res) {
						$scope.attacking = false;
						if (res.data.attacker) {
							var attackerName = res.data.attacker.username;
							var defenderName = res.data.defender.username;

							$scope.me = res.data.attacker;
							$scope.players[attackerName] = res.data.attacker;
							(res.data.defender.hp < 0)
								?	delete $scope.players[defenderName]
								: $scope.players[defenderName] = res.data.defender;
						} else { //ATTACKER DIED
							console.log(res.data);

							$location.path('/');

						}

					}, function (res) { //ERROR RESPONSE
						$scope.attacking = false;
						console.log('Error on attack.');
					});

			} else { //ATTACKING SELF
				console.log("Can't attack yourself!");
			}
		}
	};

	$scope.upgradeStat = function (stat) {
		$http.post('/api/me/stats', { stat: stat},
			{ headers: {'x-access-token': cookieToken } })
			.then ( function (res) {
				$scope.getMe(cookieToken);
			}, function (res) {
				console.log('Error upgrading stat.');
			})
	};

	$scope.getMe = function(cookieToken) {
		$http.get('/api/me',
			{ headers: {'x-access-token' : cookieToken } })
			.then ( function (res) {
				$scope.me = res.data;
				if (!$scope.me) $location.path('/');
			}, function (res) {
				console.log('Error fetching data.');
			});
	};

	$scope.getPlayers = function() {
		$http.get('/api/users',
			{ headers: {'x-access-token' : cookieToken } })
			.then( function (res) {
				$scope.players = res.data;
			}, function (res) {
				console.log('Error fetching players.');
		});
	};

	$scope.getMe(cookieToken);
	$scope.getPlayers();
	var refreshPlayers = setInterval( function(){ $scope.getPlayers(); }, 30000);

});

app.controller('LoginController', function ($scope, $http, $location, $cookies) {

	$scope.signup = function (user) {
		$http.post('/api/signup', user)
			.then( function (res) {
				if (res.data.token) {
					$cookies.put('token', res.data.token);
					window.localStorage.setItem('user', JSON.stringify(res.data.user));
					$location.path('/play');
				} else {
					delete $scope.user.username;
					delete $scope.user.password;
					$scope.error = 'Error on login';
				}

			}, function (res) {
				console.log('Error on signup');
			});
	};

	$scope.auth = function (user) {
		$http.post('/api/auth', user)
			.then ( function (res) {
				if (res.data.token){
					$cookies.put('token', res.data.token);
					$location.path('/play');
				}

			}, function (res) {
				$scope.error = 'Error on login.';
			});
	};

});

app.config( function ($routeProvider, $locationProvider) {
	$routeProvider
		.when('/',
		{
			controller: 'LoginController',
			templateUrl: 'partials/login.html'
		})

		.when('/play',
		{
			controller: 'GameController',
			templateUrl: 'partials/game.html'
		})

		.when ('/signup',
		{
			controller: 'SignupController',
			templateUrl: 'partials/signup.html'
		})
		.otherwise(
		{
			redirectTo: '/'
		});

});
<|endoftext|>


<commit_before>
/*

  Metadata.js

  Metadata is stored as comments near the beginning of an HTML file.
  e.g. DATA=recipes:/api/recipes{slug,url}?recipe.key=<slug>,/users

*/

var Utils    = require("./utils"),
    Metadata = {};

module.exports = Metadata;

/*

  function extract

  Extracts pertinent metadata for querying.

*/

Metadata.extract = function(str) {

  var names = ["QUERY", "DATA", "COOKIES", "SESSION"],
      re    = new RegExp("(\\b(?:" + names.join("|") + ")\\=[^\\n\\r]+)", "g"),
      meta  = {};

  Utils.getRegExpMatches(str, re).map(Metadata.parse).forEach(function(metadata) {
    meta[metadata["name"]] = metadata.value;
  });

  return meta;

}

/*

  function parse

  Converts command into multiple querys
  e.g. DATA=<query1>,<query2>

*/

Metadata.parse = function(str) {

  var re = /([^\{,]*\{[^\}]*\}[^,]*|[^\{\},]+),*/g,
      matches = str.split(/\=(.*)/),
      name = matches[0].toLowerCase(),
      value;

  // Handle different types of metadata differently
  switch (name) {
    case "query":
      value = Utils.getRegExpMatches(matches[1], re).map(Metadata.parseQuery)[0];
      if (Array.isArray(value.fields)) value.fields = value.fields[0];
      break;
    case "cookies":
      value = JSON.parse("{" + matches[1] + "}");
      break;
    case "session":
      value = JSON.parse("{" + matches[1] + "}");
      break;
    default:
      value = Utils.getRegExpMatches(matches[1], re).map(Metadata.parseQuery)
      break;
  }

  return { name : name, value : value }

}

/*

  function parseQuery

  Parses a specific metadata query.

*/

Metadata.parseQuery = function(str) {

  var query = {},
      parts = /^(?:([^:]+):)?([^\{?]+)(?:\{([^\}]+)\})?(?:\?([^\[]*))?(?:\[(\d+)\])?$/g.exec(str);

  if (parts) {
    if (parts[1]) query.key     = parts[1];
    if (parts[2]) query.route   = parts[2].replace(/^\//, "");
    if (parts[3]) query.fields  = parts[3].split(",");
    if (parts[4]) query.filters = Metadata.parseFilters(parts[4]);
    if (parts[5]) query.idx     = parseInt(parts[5]);
  }

  return query;

}

/*

  function parseFilters

*/

Metadata.parseFilters = function(str) {

  var results = {},
      parts,
      part;

  str.split("&").forEach(function(filter) {

    parts = filter.split("=");
    part  = parts[1];

    // Cast to types
    if ("false" === part)
      part = false;
    else if ("true" === part)
      part = true;
    else if (isNumeric(part))
      part = parseFloat(part);

    results[parts[0]] = part;

  });

  return results;

}

<commit_msg>Metadata#parseFilters: removes function (no longer used)<commit_after>
/*

  Metadata.js

  Metadata is stored as comments near the beginning of an HTML file.
  e.g. DATA=recipes:/api/recipes{slug,url}?recipe.key=<slug>,/users

*/

var Utils    = require("./utils"),
    Metadata = {};

module.exports = Metadata;

/*

  function extract

  Extracts pertinent metadata for querying.

*/

Metadata.extract = function(str) {

  var names = ["QUERY", "DATA", "COOKIES", "SESSION"],
      re    = new RegExp("(\\b(?:" + names.join("|") + ")\\=[^\\n\\r]+)", "g"),
      meta  = {};

  Utils.getRegExpMatches(str, re).map(Metadata.parse).forEach(function(metadata) {
    meta[metadata["name"]] = metadata.value;
  });

  return meta;

}

/*

  function parse

  Converts command into multiple querys
  e.g. DATA=<query1>,<query2>

*/

Metadata.parse = function(str) {

  var re = /([^\{,]*\{[^\}]*\}[^,]*|[^\{\},]+),*/g,
      matches = str.split(/\=(.*)/),
      name = matches[0].toLowerCase(),
      value;

  // Handle different types of metadata differently
  switch (name) {
    case "query":
      value = Utils.getRegExpMatches(matches[1], re).map(Metadata.parseQuery)[0];
      if (Array.isArray(value.fields)) value.fields = value.fields[0];
      break;
    case "cookies":
      value = JSON.parse("{" + matches[1] + "}");
      break;
    case "session":
      value = JSON.parse("{" + matches[1] + "}");
      break;
    default:
      value = Utils.getRegExpMatches(matches[1], re).map(Metadata.parseQuery)
      break;
  }

  return { name : name, value : value }

}

/*

  function parseQuery

  Parses a specific metadata query.

*/

Metadata.parseQuery = function(str) {

  var query = {},
      parts = /^(?:([^:]+):)?([^\{?]+)(?:\{([^\}]+)\})?(?:\?([^\[]*))?(?:\[(\d+)\])?$/g.exec(str);

  if (parts) {
    if (parts[1]) query.key     = parts[1];
    if (parts[2]) query.route   = parts[2].replace(/^\//, "");
    if (parts[3]) query.fields  = parts[3].split(",");
    if (parts[4]) query.filters = Metadata.parseFilters(parts[4]);
    if (parts[5]) query.idx     = parseInt(parts[5]);
  }

  return query;

}

}
<|endoftext|>


<commit_before>/* global window */
import 'can-define-stream';
import canStream from 'can-stream';
import DefineMap from 'can-define/map/';
import route from 'can-route';
// import 'can-route-pushstate';
import Session from 'bitcentive/models/session';
// import 'bitcentive/models/fixtures/';

// viewmodel debugging
import viewModel from 'can-view-model';
window.viewModel = viewModel;

var pages = {
  home: 'public',
  dashboard: 'private',
  contributors: 'private'
};

const AppViewModel = DefineMap.extend({

  /**
   * By default, viewModel attributes will not be serialized into the URL as
   * route attributes.
   */
  '*': {
    serialize: false
  },

  /**
   * Use Session.get() to see if there's a valid JWT. If one exists,
   * a new Session will be created.
   */
  session: {
    stream (setStream) {
      Session.get().catch(err => console.log(err));
      return canStream.toStream(Session, 'created')
        .merge(canStream.toStream(Session, 'destroyed'))
        .map(event => event.type === 'created' ? event.args[0] : undefined);
    }
  },

  /**
   * Determines which page-level component is displayed.
   */
  page: {
    serialize: true,
    get (page, setPage) {
      if (page === 'logout') {
        return this.logout();
      }

      if (pages[page]) {
        // Logic for authenticated users.
        if (this.session) {
          if (page === 'home') {
            page = 'dashboard';
          }
        // Logic for non-authenticated users.
        } else {
          if (pages[page] !== 'public') {
            page = 'home';
          }
        }
      // 404 if the page isn't in the list of pages.
      } else {
        page = 'four-oh-four';
      }
      return page;
    }
  },

  /**
   * The `title` attribute is used in index.stache as the HTML title.
   */
  title: {
    value: 'Bitcentive'
  },

  logout () {
    this.session && this.session.destroy()
      .then(() => {
        if (!window.doneSsr) {
          this.page = 'home';
        }
      });
  }
});

route('{page}', {page: 'home'});

export default AppViewModel;
<commit_msg>Set initial session in its own property.<commit_after>/* global window */
import 'can-define-stream';
import canStream from 'can-stream';
import DefineMap from 'can-define/map/';
import route from 'can-route';
// import 'can-route-pushstate';
import Session from 'bitcentive/models/session';
// import 'bitcentive/models/fixtures/';

// viewmodel debugging
import viewModel from 'can-view-model';
window.viewModel = viewModel;

var pages = {
  home: 'public',
  dashboard: 'private',
  contributors: 'private'
};

const AppViewModel = DefineMap.extend({

  /**
   * By default, viewModel attributes will not be serialized into the URL as
   * route attributes.
   */
  '*': {
    serialize: false
  },

  // Once https://github.com/canjs/can-define-stream/issues/15 is fixed,
  // we can move the initialSession into the session `value` function.
  initialSession: {
    value () {
      Session.get().then(session => {
        this.initialSession = session;
      })
      .catch(err => console.log(err));
    }
  },

  /**
   * Use Session.get() to see if there's a valid JWT. If one exists,
   * a new Session will be created.
   */
  session: {
    // value () {},
    stream (setStream) {
      return canStream.toStream(Session, 'created')
        .merge(canStream.toStream(Session, 'destroyed'))
        .map(event => event.type !== 'destroyed' ? event.args[0] : undefined)
        .merge(this.stream('.initialSession'));
    }
  },

  /**
   * Determines which page-level component is displayed.
   */
  page: {
    serialize: true,
    get (page, setPage) {
      if (page === 'logout') {
        return this.logout();
      }

      if (pages[page]) {
        // Logic for authenticated users.
        if (this.session) {
          if (page === 'home') {
            page = 'dashboard';
          }
        // Logic for non-authenticated users.
        } else {
          if (pages[page] !== 'public') {
            page = 'home';
          }
        }
      // 404 if the page isn't in the list of pages.
      } else {
        page = 'four-oh-four';
      }
      return page;
    }
  },

  /**
   * The `title` attribute is used in index.stache as the HTML title.
   */
  title: {
    value: 'Bitcentive'
  },

  logout () {
    this.session && this.session.destroy()
      .then(() => {
        if (!window.doneSsr) {
          this.page = 'home';
        }
      });
  }
});

route('{page}', {page: 'home'});

export default AppViewModel;
<|endoftext|>


<commit_before>var _badestellen,_freibaeder,_fkk,_hallenbaeder;

function init() {
    $.get('data/badestellen.kml', function(kml) {
        _badestellen = kml;
        $.get("data/freibaeder.kml", function(kml) {
            _freibaeder = kml;
            $.get("data/fkk.kml", function(kml) {
                _fkk = kml;
                $.get("data/hallenbaeder.kml", function(kml) {
                    _hallenbaeder = kml;
                    $.ajax({
			url: "data/all.json",
			type: 'GET',
			dataType: 'json',
			cache: false,
			success: function (json) {
                            _quality = json;
                            initMap();
			}
                    });
                });
            });
        });
    });
}

function initMap() {
    var map = new L.Map('map');

    var min = 11;
    var max = 16;
    var reuse = true;

    //var baseUrl = 'http://mamanoke.de/tiles/badeseen/';
    var baseUrl = 'http://services.codefor.de/static/badeseen/';
    var errorTile = baseUrl + 'error.png';

    var osmCopyright = "Map data © 2012 OpenStreetMap contributors";

    var center = new L.LatLng(52.51, 13.37628);
    map.setView(center, min);

    var icons = {
        'blau': L.icon({
            iconUrl: 'img/blau.png',
            iconSize:     [32, 39], // size of the icon width,height
            iconAnchor:   [14, 45], // point of the icon which will correspond to marker's location
            popupAnchor:  [4,-46]   // point from which the popup should open relative to the iconAnchor
        }),
        'gelb': L.icon({
            iconUrl: 'img/gelb.png',
            iconSize:     [32, 37],
            iconAnchor:   [14, 39],
            popupAnchor:  [4,-46]
        }),
        'rot': L.icon({
            iconUrl: 'img/rot.png',
            iconSize:     [26, 45],
            iconAnchor:   [13, 44],
            popupAnchor:  [4,-46]
        }),
        'freibad': L.icon({
            iconUrl: 'img/freibad.png',
            iconSize:     [23, 32],
            iconAnchor:   [11, 26],
            popupAnchor:  [4,-46]
        }),
        'fkk': L.icon({
            iconUrl: 'img/fkk.png',
            iconSize:     [22, 26],
            iconAnchor:   [11, 26],
            popupAnchor:  [4,-46]
        }),
        'hallenbad': L.icon({
            iconUrl: 'img/hallenbad.png',
            iconSize:  [35, 21],
            iconAnchor: [11, 26],
            popupAnchor: [4,-46]
        }),
        'fernsehturm': L.icon({
            iconUrl: 'img/fernsehturm.png',
            iconSize: [27, 125],
            iconAnchor: [8,111]
        }),
        'funkturm': L.icon({
            iconUrl: 'img/funkturm.png',
            iconSize: [36, 110],
            iconAnchor: [16,108]
        })
    };

    var marker = {
        'fernsehturm': L.marker([52.520841,13.409405],{icon: icons.fernsehturm}).addTo(map),
        'funkturm': L.marker([52.5050681,13.278211400000032],{icon: icons.funkturm}).addTo(map)
    };

    var base = {
        'Hintergrund': new L.TileLayer(baseUrl + 'hintergrund/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 0,
            reuseTiles: reuse
        }).addTo(map),
        'Grau': new L.TileLayer(baseUrl + 'grau/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 1,
            reuseTiles: reuse
        }).addTo(map),
    };

    var overlay = {
        'Natur': new L.TileLayer(baseUrl + 'natur/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 1,
            reuseTiles: reuse
        }),
        'BVG Haltestellen': new L.TileLayer(baseUrl + 'bvg/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 4,
            reuseTiles: reuse
        }),
        'Badestellen': new L.layerGroup().addTo(map),
        'Freibäder': new L.layerGroup(),
        'FKK-Baden': new L.layerGroup(),
        'Hallenbäder': new L.layerGroup(),
        'Hundebadestellen': new L.TileLayer(baseUrl + 'hunde/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 6,
            reuseTiles: reuse
        }),
    };

    L.control.layers({}, overlay, {collapsed: false}).addTo(map);

    // Badestellen
    $(_badestellen).find("Placemark").each(function(){
        var description = $(this).find("description").text();
        var name = $(this).find("name").text();
        var sicht = "";
        var overall;
        var date;
        var url;

        for (var i = 0; i<_quality.index.length; i++) {
            if (_quality.index[i].rss_name == name) {
                sicht = (_quality.index[i].sicht);
                var s = _quality.index[i].dat.split('-');
                date = s[2] + '.' + s[1] + '.' + s[0];
                url = unescape(_quality.index[i].badestellelink.replace("[","").replace("]",""));
		url = url.split("|")[0];
                url = url.substr(1, url.length);
                url = 'http://www.berlin.de/' + url;
            }
        }

        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var icon;

        if(description.indexOf('gruen')!= -1){
            icon = icons['blau'];
            overall = 'gut';
        } else if(description.indexOf('gelb')!= -1){
            icon = icons['gelb'];
            overall = 'mittel';
        } else {
            icon = icons['rot'];
            overall = 'schlecht';
        }

        var marker = L.marker([lat,lon],{icon: icon});
        marker.bindPopup(''+ name + '
Sichttiefe: ' + sicht + ' cm
 Messdatum: ' + date + '
 Wasserqualität: ' + overall + '
'+ 'Link');
        marker.on('click', function(e){
            marker.openPopup();
        });
        overlay['Badestellen'].addLayer(marker);
    });

    // Freibad
    $(_freibaeder).find("Placemark").each(function(){
        var description = $(this).find("description").text();
        var name = $(this).find("name").text();
        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var marker = L.marker([lat,lon],{icon: icons['freibad']});
        marker.bindPopup(''+ name + '
' + 'Link');
        marker.on('click', function(e){
            marker.openPopup();
        });
        overlay['Freibäder'].addLayer(marker);
    });

    // FKK
    $(_fkk).find("Placemark").each(function(){
        //var description = $b.find("description").text();
        var name = $(this).find("name").text();
        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var marker = L.marker([lat,lon],{icon: icons['fkk']});
        marker.bindPopup(name);
        marker.on('click', function(e){
           marker.openPopup();
        });
        overlay['FKK-Baden'].addLayer(marker);
    });

    // Hallenbaeder
    $(_hallenbaeder).find("Placemark").each(function(){
        var description = $(this).find("description").text();
        var name = $(this).find("name").text();
        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var marker = L.marker([lat,lon],{icon: icons['hallenbad']});
        marker.bindPopup(''+ name + '
' + 'Link');
        marker.on('click', function(e){
            marker.openPopup();
        });
        overlay['Hallenbäder'].addLayer(marker);
    });
}<commit_msg>small fix<commit_after>var _badestellen,_freibaeder,_fkk,_hallenbaeder;

function init() {
    $.get('data/badestellen.kml', function(kml) {
        _badestellen = kml;
        $.get("data/freibaeder.kml", function(kml) {
            _freibaeder = kml;
            $.get("data/fkk.kml", function(kml) {
                _fkk = kml;
                $.get("data/hallenbaeder.kml", function(kml) {
                    _hallenbaeder = kml;
                    $.ajax({
			url: "data/all.json",
			type: 'GET',
			dataType: 'json',
			cache: false,
			success: function (json) {
                            _quality = json;
                            initMap();
			}
                    });
                });
            });
        });
    });
}

function initMap() {
    var map = new L.Map('map');

    var min = 11;
    var max = 16;
    var reuse = true;

    //var baseUrl = 'http://mamanoke.de/tiles/badeseen/';
    var baseUrl = 'http://services.codefor.de/static/badeseen/';
    var errorTile = baseUrl + 'error.png';

    var osmCopyright = "Map data © 2012 OpenStreetMap contributors";

    var center = new L.LatLng(52.51, 13.37628);
    map.setView(center, min);

    var icons = {
        'blau': L.icon({
            iconUrl: 'img/blau.png',
            iconSize:     [32, 39], // size of the icon width,height
            iconAnchor:   [14, 45], // point of the icon which will correspond to marker's location
            popupAnchor:  [4,-46]   // point from which the popup should open relative to the iconAnchor
        }),
        'gelb': L.icon({
            iconUrl: 'img/gelb.png',
            iconSize:     [32, 37],
            iconAnchor:   [14, 39],
            popupAnchor:  [4,-46]
        }),
        'rot': L.icon({
            iconUrl: 'img/rot.png',
            iconSize:     [26, 45],
            iconAnchor:   [13, 44],
            popupAnchor:  [4,-46]
        }),
        'freibad': L.icon({
            iconUrl: 'img/freibad.png',
            iconSize:     [23, 32],
            iconAnchor:   [11, 26],
            popupAnchor:  [4,-46]
        }),
        'fkk': L.icon({
            iconUrl: 'img/fkk.png',
            iconSize:     [22, 26],
            iconAnchor:   [11, 26],
            popupAnchor:  [4,-46]
        }),
        'hallenbad': L.icon({
            iconUrl: 'img/hallenbad.png',
            iconSize:  [35, 21],
            iconAnchor: [11, 26],
            popupAnchor: [4,-46]
        }),
        'fernsehturm': L.icon({
            iconUrl: 'img/fernsehturm.png',
            iconSize: [27, 125],
            iconAnchor: [8,111]
        }),
        'funkturm': L.icon({
            iconUrl: 'img/funkturm.png',
            iconSize: [36, 110],
            iconAnchor: [16,108]
        })
    };

    var marker = {
        'fernsehturm': L.marker([52.520841,13.409405],{icon: icons.fernsehturm}).addTo(map),
        'funkturm': L.marker([52.5050681,13.278211400000032],{icon: icons.funkturm}).addTo(map)
    };

    var base = {
        'Hintergrund': new L.TileLayer(baseUrl + 'hintergrund/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 0,
            reuseTiles: reuse
        }).addTo(map),
        'Grau': new L.TileLayer(baseUrl + 'grau/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 1,
            reuseTiles: reuse
        }).addTo(map),
    };

    var overlay = {
        'Natur': new L.TileLayer(baseUrl + 'natur/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 1,
            reuseTiles: reuse
        }),
        'BVG Haltestellen': new L.TileLayer(baseUrl + 'bvg/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 4,
            reuseTiles: reuse
        }),
        'Badestellen': new L.layerGroup().addTo(map),
        'Freibäder': new L.layerGroup(),
        'FKK-Baden': new L.layerGroup(),
        'Hallenbäder': new L.layerGroup(),
        'Hundebadestellen': new L.TileLayer(baseUrl + 'hunde/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 6,
            reuseTiles: reuse
        }),
    };

    L.control.layers({}, overlay, {collapsed: false}).addTo(map);

    // Badestellen
    $(_badestellen).find("Placemark").each(function(){
        var description = $(this).find("description").text();
        var name = $(this).find("name").text();
        var farbe;
        var sicht = "";
        var overall;
        var date;
        var url;

        for (var i = 0; i<_quality.index.length; i++) {
            if (_quality.index[i].rss_name == name) {
                farbe = _quality.index[i].farbe;
                sicht = (_quality.index[i].sicht);
                var s = _quality.index[i].dat.split('-');
                date = s[2] + '.' + s[1] + '.' + s[0];
                url = unescape(_quality.index[i].badestellelink.replace("[","").replace("]",""));
		url = url.split("|")[0];
                url = url.substr(1, url.length);
                url = 'http://www.berlin.de/' + url;
            }
        }

        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var icon;

        if (farbe === 'gruen.jpg') {
            icon = icons['blau'];
            overall = 'gut';
        } else if(farbe === 'gelb.jpg') {
            icon = icons['gelb'];
            overall = 'mittel';
        } else {
            icon = icons['rot'];
            overall = 'schlecht';
        }

        var marker = L.marker([lat,lon],{icon: icon});
        marker.bindPopup(''+ name + '
Sichttiefe: ' + sicht + ' cm
 Messdatum: ' + date + '
 Wasserqualität: ' + overall + '
'+ 'Link');
        marker.on('click', function(e){
            marker.openPopup();
        });
        overlay['Badestellen'].addLayer(marker);
    });

    // Freibad
    $(_freibaeder).find("Placemark").each(function(){
        var description = $(this).find("description").text();
        var name = $(this).find("name").text();
        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var marker = L.marker([lat,lon],{icon: icons['freibad']});
        marker.bindPopup(''+ name + '
' + 'Link');
        marker.on('click', function(e){
            marker.openPopup();
        });
        overlay['Freibäder'].addLayer(marker);
    });

    // FKK
    $(_fkk).find("Placemark").each(function(){
        //var description = $b.find("description").text();
        var name = $(this).find("name").text();
        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var marker = L.marker([lat,lon],{icon: icons['fkk']});
        marker.bindPopup(name);
        marker.on('click', function(e){
           marker.openPopup();
        });
        overlay['FKK-Baden'].addLayer(marker);
    });

    // Hallenbaeder
    $(_hallenbaeder).find("Placemark").each(function(){
        var description = $(this).find("description").text();
        var name = $(this).find("name").text();
        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var marker = L.marker([lat,lon],{icon: icons['hallenbad']});
        marker.bindPopup(''+ name + '
' + 'Link');
        marker.on('click', function(e){
            marker.openPopup();
        });
        overlay['Hallenbäder'].addLayer(marker);
    });
}<|endoftext|>