<commit_before>var Scene1 = new function () {
    var that = this;
    this.config;
    this.Queue;
    this.win = 0;
    this.svg = [];

    this.initialize = function (lan, level) {
        that.lan = lan;
        that.level = level - 1;
        var rect = new createjs.Shape();
        rect.graphics.beginFill("#E8D24A").drawRect(0, 0, canvas.width, canvas.height);
        stage.addChild(rect);
        that.progress = new createjs.Shape();
        that.progress.x = canvas.width / 2;
        that.progress.y = canvas.height * 0.5;
        stage.addChild(that.progress);

        that.loader = new createjs.LoadQueue();
        that.loader.addEventListener("complete", loaderComplete);
        that.loader.loadManifest([
            {id: "names", src: "assets/scene1/" + level + "/img/lan/names-" + lan + ".png", type: createjs.LoadQueue.IMAGE},
            {id: "lan", src: "lan/"+lan+".json", type: createjs.LoadQueue.JSON},
            {id: "config", src: "config/scene1-config.json", type: createjs.LoadQueue.JSON}
        ]);
    };
};

var loaderComplete = function () {
    var loader = Scene1.loader;
    Scene1.lan = loader.getResult("lan");
    Scene1.config = loader.getResult("config");
    var level = Scene1.config[Scene1.level];
    Scene1.Queue = new createjs.LoadQueue();
    Scene1.Queue.addEventListener("progress", queueProgress);
    Scene1.Queue.addEventListener("complete", loadManifest);
    var Manifest = [];
    for (var i = 0; i < level.backg.length; i++) {
        Manifest.push({id: "backg" + i, src: level.backg[i].backgUrl, type: createjs.LoadQueue.IMAGE});
    }
    for (var i = 0; i < level.img.length; i++) {
        Manifest.push({id: "img" + i, src: level.img[i].imgUrl, type: createjs.LoadQueue.IMAGE});
    }
    Scene1.Queue.loadManifest(Manifest);
};
var queueProgress = function (event) {
    var value = event.loaded / event.total;
    Scene1.progress.graphics.clear()
        .beginFill("#fff").drawRoundRect(-103, -13, 306, 26, 13)
        .beginFill("#0D83BA").drawRoundRect(-100, -10, value * 300 | 0, 20, 10);
    stage.update();
};
var loadManifest = function () {
    var level = Scene1.config[Scene1.level];
    var loader = Scene1.Queue;
    for (var i = 0; i < level.backg.length; i++) {
        var backg = new createjs.Bitmap(loader.getResult("backg" + i));
        backg.scaleX = canvas.width / backg.image.width;
        backg.scaleY = canvas.height / backg.image.height;
        stage.addChild(backg);
    }
//  imgs = array with images
    var img = level.img;
    for (var i = 0; i < img.length; i++) {
        new image(i,loader,img);
    }
    var lan=Scene1.lan.scene1[Scene1.level];
    for (var i = 0; i < Scene1.lan.scene1[Scene1.level].length; i++) {
        new circle(i);
    }
    stage.update();
};
var image=function(i,loader,img){
    var svg = new createjs.Bitmap(loader.getResult("img" + i));
    svg.scaleX = svg.scaleY = canvas.width * 0.00009;

    var j=i*3;
    var names=new createjs.SpriteSheet({
        "animations":{
            "gray":[j],
            "drag":[j+1],
            "done":[j+2]
        },
        "images":[Scene1.loader.getResult("names")],
        "frames":{
            "regX":33,
            "regY":25,
            "height":63,
            "width":180,
            "count":24
        }
    });
    var name = new createjs.Sprite(names,"gray");

    Scene1.svg[i] = new createjs.Container();
    Scene1.svg[i].x = canvas.width * img[i].x;
    Scene1.svg[i].y = canvas.height * img[i].y;
    Scene1.svg[i].addChild(svg,name);
    stage.addChild(Scene1.svg[i]);
};
var circle = function (i) {
    var that = this;
    that.i = i;
    var c = new createjs.Shape();
    c.graphics.beginFill("#" + Math.floor(Math.random() * 999)).drawRoundRect(0, 0, 180,63,5); //canvas.width * 0.045 set color by default > lan.scene1[level][i].color

//    var lan = Scene1.lan.scene1[Scene1.level];
//    var label = new createjs.Text(lan[i].drag, "bold 25px Arial", "#FFFFFF");
//    label.textAlign = "center";
//    label.y = -12;
    var j=i*3;
    var names=new createjs.SpriteSheet({
        "animations":{
            "gray":[j],
            "drag":[j+1],
            "done":[j+2]
        },
        "images":[Scene1.loader.getResult("names")],
        "frames":{
            "regX":0,
            "regY":0,
            "height":63,
            "width":180,
            "count":24
        }
    });
    var name = new createjs.Sprite(names,"drag");

    var dragger = new createjs.Container();
    dragger.x = dragger.y = 100;
    dragger.addChild(c, name);
    stage.addChild(dragger);
    dragger.on("pressmove", function (evt) {
        // currentTarget will be the container that the event listener was added to:
//        name.scaleX = name.scaleY = 1.35;
//        c.graphics._fillInstructions[0].params[1]="transparent";
//        label.font = "bold 40px Arial";
//        label.y = -20;
        evt.currentTarget.x = evt.stageX-90;
        evt.currentTarget.y = evt.stageY-63;
        stage.update();
    });
    dragger.on("pressup", function (evt) {
//        name.scaleX = name.scaleY = 1;
//        label.font = "bold 25px Arial";
//        label.y = -12;
        var bitmap = Scene1.svg[i];
        if ((evt.currentTarget.x+90 > (bitmap.x) && (evt.currentTarget.x < (bitmap.x + 110)))) {
            if ((evt.currentTarget.y+63 > (bitmap.y) && (evt.currentTarget.y < (bitmap.y + 130)))) {
                dragger.removeAllEventListeners();
                dragger.removeAllChildren();
                Scene1.svg[i].children[1].gotoAndStop("done");
//                label.font = "bold 32px Arial";
//                label.color = "#" + Math.floor(Math.random() * 999);
//                label.y = -100;
                Scene1.win += 1;
            }
        }
        if (Scene1.win === Scene1.lan.scene1[Scene1.level].length) {
            stage.removeAllChildren();
            Scene1.win = 0;
            init();
        }
        stage.update();
    });
    stage.update();
};<commit_msg>nuevo<commit_after>var Scene1 = new function () {
    var that = this;
    this.config;
    this.Queue;
    this.win = 0;
    this.svg = [];

    this.initialize = function (lan, level) {
        that.lan = lan;
        that.level = level - 1;
        var rect = new createjs.Shape();
        rect.graphics.beginFill("#E8D24A").drawRect(0, 0, canvas.width, canvas.height);
        stage.addChild(rect);
        that.progress = new createjs.Shape();
        that.progress.x = canvas.width / 2;
        that.progress.y = canvas.height * 0.5;
        stage.addChild(that.progress);

        that.loader = new createjs.LoadQueue();
        that.loader.addEventListener("complete", loaderComplete);
        that.loader.loadManifest([
            {id: "names", src: "assets/scene1/" + level + "/img/lan/names-" + lan + ".png", type: createjs.LoadQueue.IMAGE},
            {id: "lan", src: "lan/"+lan+".json", type: createjs.LoadQueue.JSON},
            {id: "config", src: "config/scene1-config.json", type: createjs.LoadQueue.JSON}
        ]);
    };
};

var loaderComplete = function () {
    var loader = Scene1.loader;
    Scene1.lan = loader.getResult("lan");
    Scene1.config = loader.getResult("config");
    var level = Scene1.config[Scene1.level];
    Scene1.Queue = new createjs.LoadQueue();
    Scene1.Queue.addEventListener("progress", queueProgress);
    Scene1.Queue.addEventListener("complete", loadManifest);
    var Manifest = [];
    for (var i = 0; i < level.backg.length; i++) {
        Manifest.push({id: "backg" + i, src: level.backg[i].backgUrl, type: createjs.LoadQueue.IMAGE});
    }
    for (var i = 0; i < level.img.length; i++) {
        Manifest.push({id: "img" + i, src: level.img[i].imgUrl, type: createjs.LoadQueue.IMAGE});
    }
    Scene1.Queue.loadManifest(Manifest);
};
var queueProgress = function (event) {
    var value = event.loaded / event.total;
    Scene1.progress.graphics.clear()
        .beginFill("#fff").drawRoundRect(-103, -13, 306, 26, 13)
        .beginFill("#0D83BA").drawRoundRect(-100, -10, value * 300 | 0, 20, 10);
    stage.update();
};
var loadManifest = function () {
    var level = Scene1.config[Scene1.level];
    var loader = Scene1.Queue;
    for (var i = 0; i < level.backg.length; i++) {
        var backg = new createjs.Bitmap(loader.getResult("backg" + i));
        backg.scaleX = canvas.width / backg.image.width;
        backg.scaleY = canvas.height / backg.image.height;
        stage.addChild(backg);
    }
//  imgs = array with images
    var img = level.img;
    for (var i = 0; i < img.length; i++) {
        new image(i,loader,img);
    }
    var lan=Scene1.lan.scene1[Scene1.level];
    for (var i = 0; i < Scene1.lan.scene1[Scene1.level].length; i++) {
        new circle(i);
    }
    stage.update();
};
var image=function(i,loader,img){
    var svg = new createjs.Bitmap(loader.getResult("img" + i));
    svg.scaleX = svg.scaleY = canvas.width * 0.00009;

    var j=i*3;
    var names=new createjs.SpriteSheet({
        "animations":{
            "gray":[j],
            "drag":[j+1],
            "done":[j+2]
        },
        "images":[Scene1.loader.getResult("names")],
        "frames":{
            "regX":33,
            "regY":25,
            "height":63,
            "width":180,
            "count":24
        }
    });
    var name = new createjs.Sprite(names,"gray");

    Scene1.svg[i] = new createjs.Container();
    Scene1.svg[i].x = canvas.width * img[i].x;
    Scene1.svg[i].y = canvas.height * img[i].y;
    Scene1.svg[i].addChild(svg,name);
    stage.addChild(Scene1.svg[i]);
};
var circle = function (i) {
    var that = this;
    that.i = i;
    var c = new createjs.Shape();
    c.graphics.beginFill("#" + Math.floor(Math.random() * 999)).drawRoundRect(0, 0, 180,63,5); //canvas.width * 0.045 set color by default > lan.scene1[level][i].color

//    var lan = Scene1.lan.scene1[Scene1.level];
//    var label = new createjs.Text(lan[i].drag, "bold 25px Arial", "#FFFFFF");
//    label.textAlign = "center";
//    label.y = -12;
    var j=i*3;
    var names=new createjs.SpriteSheet({
        "animations":{
            "gray":[j],
            "drag":[j+1],
            "done":[j+2]
        },
        "images":[Scene1.loader.getResult("names")],
        "frames":{
            "regX":0,
            "regY":0,
            "height":63,
            "width":180,
            "count":24
        }
    });
    var name = new createjs.Sprite(names,"drag");

    var dragger = new createjs.Container();
    dragger.x = dragger.y = 100;
    dragger.addChild(c, name);
    stage.addChild(dragger);
    dragger.on("pressmove", function (evt) {
        // currentTarget will be the container that the event listener was added to:
//        name.scaleX = name.scaleY = 1.35;
        c.graphics._fillInstructions[0].params[1]="transparent";
//        label.font = "bold 40px Arial";
//        label.y = -20;
        evt.currentTarget.x = evt.stageX-90;
        evt.currentTarget.y = evt.stageY-63;
        stage.update();
    });
    dragger.on("pressup", function (evt) {
//        name.scaleX = name.scaleY = 1;
//        label.font = "bold 25px Arial";
//        label.y = -12;
        var bitmap = Scene1.svg[i];
        if ((evt.currentTarget.x+90 > (bitmap.x) && (evt.currentTarget.x < (bitmap.x + 110)))) {
            if ((evt.currentTarget.y+63 > (bitmap.y) && (evt.currentTarget.y < (bitmap.y + 130)))) {
                dragger.removeAllEventListeners();
                dragger.removeAllChildren();
                Scene1.svg[i].children[1].gotoAndStop("done");
//                label.font = "bold 32px Arial";
//                label.color = "#" + Math.floor(Math.random() * 999);
//                label.y = -100;
                Scene1.win += 1;
            }
        }
        if (Scene1.win === Scene1.lan.scene1[Scene1.level].length) {
            stage.removeAllChildren();
            Scene1.win = 0;
            init();
        }
        stage.update();
    });
    stage.update();
};<|endoftext|>


<commit_before>/* @flow */
import type { Props } from '../message/MessageListContainer';

import { appendAuthToImages, getFullUrl } from '../utils/url';
import messageAsHtml from './messageAsHtml';
import messageHeaderAsHtml from './messageHeaderAsHtml';
import timeRowAsHtml from './timeRowAsHtml';

const renderMessages = ({
  auth,
  subscriptions,
  realmEmoji,
  renderedMessages,
  narrow,
}: Props): string[] =>
  renderedMessages.reduce((list, section, index) => {
    list.push(
      messageHeaderAsHtml({
        auth,
        item: section.message,
        subscriptions,
        narrow,
      }),
    );

    section.data.forEach((item, idx) => {
      if (item.type === 'time') {
        list.push(timeRowAsHtml(item.timestamp, item.firstMessage));
      } else {
        const { message } = item;
        list.push(
          messageAsHtml({
            id: message.id,
            isBrief: item.isBrief,
            fromName: message.sender_full_name,
            fromEmail: message.sender_email,
            content: message.match_content || message.content,
            flags: message.flags || [],
            timestamp: message.timestamp,
            avatarUrl: getFullUrl(message.avatar_url, auth ? auth.realm : ''),
            timeEdited: message.last_edit_timestamp,
            isOutbox: message.isOutbox,
            reactions: message.reactions,
            ownEmail: auth.email,
            realmEmoji,
            twentyFourHourTime: false,
          }),
        );
      }
    });

    return list; // eslint-disable-next-line
  }, []);

export default (props: Props): string => {
  const { auth } = props;

  return appendAuthToImages(renderMessages(props).join(''), auth);
};
<commit_msg>messageList: Calculate gavatar url if avatar_url is null in message.<commit_after>/* @flow */
import type { Props } from '../message/MessageListContainer';

import { appendAuthToImages, getFullUrl } from '../utils/url';
import messageAsHtml from './messageAsHtml';
import messageHeaderAsHtml from './messageHeaderAsHtml';
import timeRowAsHtml from './timeRowAsHtml';
import { getGravatarFromEmail } from '../utils/avatar';

const renderMessages = ({
  auth,
  subscriptions,
  realmEmoji,
  renderedMessages,
  narrow,
}: Props): string[] =>
  renderedMessages.reduce((list, section, index) => {
    list.push(
      messageHeaderAsHtml({
        auth,
        item: section.message,
        subscriptions,
        narrow,
      }),
    );

    section.data.forEach((item, idx) => {
      if (item.type === 'time') {
        list.push(timeRowAsHtml(item.timestamp, item.firstMessage));
      } else {
        const { message } = item;
        list.push(
          messageAsHtml({
            id: message.id,
            isBrief: item.isBrief,
            fromName: message.sender_full_name,
            fromEmail: message.sender_email,
            content: message.match_content || message.content,
            flags: message.flags || [],
            timestamp: message.timestamp,
            avatarUrl: message.avatar_url
              ? getFullUrl(message.avatar_url, auth ? auth.realm : '')
              : getGravatarFromEmail(message.sender_email),
            timeEdited: message.last_edit_timestamp,
            isOutbox: message.isOutbox,
            reactions: message.reactions,
            ownEmail: auth.email,
            realmEmoji,
            twentyFourHourTime: false,
          }),
        );
      }
    });

    return list; // eslint-disable-next-line
  }, []);

export default (props: Props): string => {
  const { auth } = props;

  return appendAuthToImages(renderMessages(props).join(''), auth);
};
<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var width = 512;
        var height = 288;
        var blockSize = 16;

        document.getElementById("startbtn").onclick = paintscreen;

        //paint a block
        function paintblock(x, y) {
            for(var i = 0; i < blockSize; i++) {
                for(var j = 0; j< blockSize; j++) {
                    if(i == 0 || i == blockSize -1){
                        c.fillStyle = "#000000";
                        c.fillRect(i*x, j*y, 1, 1);
                    }
                    if(j == 0 || j == blockSize -1){
                        c.fillStyle = "#000000";
                        c.fillRect(i*x, j*y, 1, 1);

                    }

                }
            }
        }

        //paint the screen
        function paintscreen() {
            for(var i = 0; i< 32; i++) {
                for(var j = 0; j < 18; j++) {
                    paintblock(i, j);
                }
            }
        }

    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var width = 512;
        var height = 288;
        var blockSize = 16;

        document.getElementById("startbtn").onclick = paintscreen;

        //paint a block
        function paintblock(x, y) {
            for(var i = 0; i < blockSize; i++) {
                for(var j = 0; j< blockSize; j++) {
                    if(i == 0 || i == blockSize -1){
                        c.fillStyle = "#000000";
                        c.fillRect(i*x, j*y, 1, 1);
                    }
                    if(j == 0 || j == blockSize -1){
                        c.fillStyle = "#000000";
                        c.fillRect(i*x, j*y, 1, 1);

                    }

                }
            }
        }

        //paint the screen
        function paintscreen() {
            for(var i = 0; i< 32; i++) {
                for(var j = 0; j < 18; j++) {
                    paintblock(i*blockSize, j*blockSize);
                }
            }
        }

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


<commit_before>import { map } from 'lodash';

/**
 * Execute fetchData methods for each component
 * @param renderProps
 * @param context - contains our state and actions
 * @returns {Promise} - returns a promise
 */
export default function(component, params, stores) {

    console.log(component)

    const accumulate = map(component.props.children, 'fetchData').filter(x => x)
    const fetchDataMethods = accumulate.map(method => method(stores, params))

    return Promise.all(fetchDataMethods);
}
<commit_msg>Use arrow functions<commit_after>import { map } from 'lodash';

/**
 * Execute fetchData methods for each component
 * @param renderProps
 * @param context - contains our state and actions
 * @returns {Promise} - returns a promise
 */
export default async(components, params, stores) => {

    console.log(components)

    const accumulate = map(components.props.children, 'fetchData').filter(x => x)
    const fetchDataMethods = accumulate.map(method => method(stores, params))

    return Promise.all(fetchDataMethods);
}
<|endoftext|>


<commit_before>var _ = require('underscore');
var bus = require('../bus');
var rewire = require('rewire');

var Modulecache = function(){
	this.cache = {};
};

Modulecache.prototype.get = function(id, module) {
	if (true) {};
};

Modulecache.prototype.set = function(module){

	var modResolved = require.resolve(module);
	var toCache = require(modResolved);

	var deps = _.reduce(require.cache[modResolved].children,function(memo, item){
		memo.push(item.id);
		return memo;
	},[]);

	this.cache[modResolved] = {
		exports: toCache,
		deps: deps
	};

};

Modulecache.prototype.clear = function(id, module) {
	if (id && !module) {
		this.cache[id] = null;
		delete this.cache[id];
	} else if (id && module){
		this.cache[id][module] = null;
		delete this.cache[id][module];
	} else {
		this.cache = null;
		this.cache = {};
	}
};

var Sandboxer = function(){
	var _this = this;
	this.cache = new Modulecache();
	this.definitionCache = new Modulecache();
	this.bus = bus;
	this.bus.subscribe('module.dependencies',function(data,topic){
		console.log(data.name);

		process.nextTick(function(){
			_this.definitionCache.set(data.name);
		});

	});
};

Sandboxer.prototype.create = function(locals){

	var cache = this.cache;

	for(var local in locals){
		console.log(local, locals[local]);
	}

	return function(moduleId){

		var resolvedId = require.resolve(moduleId);

		var rewiredModule = rewire(resolvedId);
		for(var local in locals){
			rewiredModule.__set__(local,locals[local]);
		}

		return rewiredModule;
	}
};

module.exports = new Sandboxer();
<commit_msg>start caching<commit_after>var _ = require('underscore');
var bus = require('../bus');
var rewire = require('rewire');

var Modulecache = function(){
	this.cache = {};
};

Modulecache.prototype.get = function(moduleId) {
	if (this.cache[moduleId]) {
		return this.cache[moduleId];
	} else {
		// throw 'Module not found';
		return false;
	}
};

Modulecache.prototype.set = function(moduleId, module){

	this.cache[moduleId] = module;

};

Modulecache.prototype.clear = function(moduleId) {
	if (this.cache[moduleId]) {
		this.cache[moduleId] = null;
		delete this.cache[moduleId];
		return true;
	} else {
		return false;
	}

};

var Sandboxer = function(){
	var _this = this;
	this.bus = bus;
};

Sandboxer.prototype.create = function(locals){

	var cache = new Modulecache();

	return function(moduleId){

		var resolvedId = require.resolve(moduleId);

		var deps = _.map(require.cache[resolvedId].children,function(dep){
			return dep.id ? dep.id : false;
		});

		if (cache[moduleId]) {
			return cache[moduleId];
		};

		var rewiredModule = rewire(resolvedId);

		for(var local in locals){
			rewiredModule.__set__(local,locals[local]);
		}

		cache.set(resolvedId, rewiredModule);

		return rewiredModule;
	}
};

module.exports = new Sandboxer();
<|endoftext|>


<commit_before>(function() {

	// load the available notes and tags.
	loadNotes(0);
	loadTags();
	var showingComplete = false;
	var $noteList = $('#note-list');

	function loadNotes(complete) {

		$.ajax({
			url: 'includes/load-note.php',
			method: 'POST',
			data: {
				userId: userId,
				complete: complete
			}
		})
		.done(function(data, result) {
			if(result === 'success') {
				$('#note-list').append(data);

				if(complete === 1) {
					// change the button text. Remove the show all notes.
					$('show-all-notes-button').hide();
					$('#complete-notes-button').html('	Show Active Notes');
				} else {
					$('show-all-notes-button').show();
					$('#complete-notes-button').html('	Show Completed Notes');
				}
			}
		})
		.fail(function(error) {
			console.log('It failed: ', error);
		});
	}

	function loadTags() {

		$.ajax({
			url: 'includes/load-tags.php',
			method: 'POST'
		})
		.done(function(data, result) {
			if(result == 'success') {
				$('#add-note-tags').append(data);
				toastr.info('Loading success');
			}
		})
		.fail(function(error) {
			console.log(error);
		});
	}

	function addTag() {
		var newTag = $('#add-new-tag-text').val();

		if(newTag.trim() !== '') {
			$('#add-note-tags').append('
<input type="checkbox" checked name="new-tag" data-tag="' + newTag + '" value="' + newTag + '">' + newTag + '
');
			$('#add-new-tag-text').val('');
		}
	}

	toastr.options = {
		"timeOut": "2000",
		"preventDuplicates": false,
		"closeButton": true
	};

	// Hide the form to create new note until clicked
	$('#new-note-section').hide();
	$('.note-text-validation').hide();

	$('#new-note-button').on('click', function(){
		$('#new-note-section').toggle();
	});

	$('#show-new-tag-button').on('click', function() {
		$('#new-tag-section').toggle();
	});

	$('#show-all-notes-button').on('click', function() {
		$('.note').show();
	});

	$('#add-note-button').on('click', function() {

		var noteText = $('#add-note-text').val();
		var noteTitle = $('#add-note-title').val();
		var tagArray = [];

		if(noteText.trim() === '') {
			$('.note-text-validation').show();
			return;
		}

		$('input:checkbox[name=new-tag]:checked').each(function() {
			tagArray.push($(this).val());
		});

		$.ajax({
			url: 'includes/add-new-note.php',
			method: 'POST',
			data: {
				noteText: noteText,
				noteTags: tagArray,
				noteTitle: noteTitle
			}
		})
		.done(function(data, result) {
			var tags = '';

			$.each(tagArray, function(index, value) {
				tags += '' + value + '';
			});

			$('#note-list').append('
Note ID: ' + data + '
' + noteTitle + '

' + noteText + '
' + tags + '

');

			// Reset and confirmation.
			$('#add-note-title').val('');
			$('#add-note-text').val('');
			$('input:checkbox[name=new-tag]').removeAttr('checked');
			tagsToAdd = [];
			toastr.success('Note has been added successfully!');
			$('#new-note-section').hide();
		})
		.fail(function(error) {
			console.log('There was a failure: ', error);
		});

	});

	$('#show-new-tag-button').on('click', addTag);

	$('#note-list').on('click', '.note-tags', function() {

		var tag = $(this).data('tag');
		var notes = $('.note');
		var hide = [];
		$('.note').show();

		$.each(notes, function(index, value) {
			$value = $(value);

			var tags = $value.children('.note-tags');
			var tagData = [];

			$.each(tags, function(i, childTag) {
				$this = $(childTag);
				var data = $this.data('tag');
				tagData.push(data);
			});

			if(tagData.indexOf(tag) === -1) {
				hide.push(value);
			}
		});

		$.each(hide, function(index, value) {
			$(value).hide();
		});

		toastr.info('Now only showing notes with the tag "' + tag + '"');
	});

	$('#note-list').on('click', '.remove-note', function() {

		if(!confirm('Are you sure you wish to remove this note?')) {
			return;
		}

		$this = $(this);
		var deleteId = $this.closest('.note').data('id');

 		$.ajax({
			method: 'POST',
			url: 'includes/delete-note.php',
			data: {
				deleteNote: deleteId
			}
		})
		.done(function(data, result) {
			$this.closest('.note').remove();
			toastr.success('Note has been deleted!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$('#note-list').on('click', '.edit-note', function() {
		// edit the note in the database.
		// also edit the note which is in the DOM
		// would probably be best to have this done in a modal.
		// TODO : above - skeleton code is below.
		$this = $(this);
		var newText = '';
		var noteId = $this.closest('.note').data('id');

		$.ajax({
			method: 'POST',
			url: 'includes/',
			data: {
				noteText: newText,
				noteId: noteId
			}
		})
		.done(function(data, result) {
			console.log(data, result)
			// update the DOM here.

			toastr.success('Note successfully updated!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$('#note-list').on('click', '.note-done', function() {
		// Mark the note as done and remove from the list. Or change color? Place in another area? Choose...
		// TODO : above
		$this = $(this);
		var newText = '';
		var noteId = $this.closest('.note').data('id');

		$.ajax({
			method: 'POST',
			url: 'includes/note-done.php',
			data: {
				noteId: noteId
			}
		})
		.done(function(data, result) {
			console.log(data, result)
			// update the DOM here.
			$this.closest('.note').remove();
			toastr.success('Note marked as complete!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$('#complete-notes-button').on('click', function() {
		if(showingComplete) {
			$noteList.empty();
			$('#complete-notes-button').html('	Show Completed Notes');
			showingComplete = false;
			loadNotes(0);
		} else {
			$noteList.empty();
			$('#complete-notes-button').html('	Show Active Notes');
			showingComplete = true;
			loadNotes(1);
		}
	});

	$('#add-note-text').on('keyup', function() {
		$('.note-text-validation').hide();
	});

	$('#add-new-tag-text').on('keyup', function(event) {
		if(event.keyCode == 13) {
			addTag();
		}
	});

	$('#refresh-button').on('click', function() {
		window.location.reload();
	});

})();<commit_msg>Changes to script.js to cache the DOM for commonly used items. Changes to when checks are made. Remove old code/comments. Changes to the new note POST which now sends the user ID, and appends a mark complete icon to DOM item.<commit_after>(function() {

	// load the available notes and tags.
	loadNotes(0);
	loadTags();
	var showingComplete = false;
	var $noteList = $('#note-list');
	var $completedNoteButton = $('#complete-notes-button');
	var $showAllNotesButton = $('#show-all-notes-button');

	function loadNotes(complete) {

		$.ajax({
			url: 'includes/load-note.php',
			method: 'POST',
			data: {
				userId: userId,
				complete: complete
			}
		})
		.done(function(data, result) {
			if(result === 'success') {

				if(data !== 'none') {
					$noteList.append(data);
				} else {
					$noteList.append('It appears that you have not yet created any notes. Create your first one.');
				}

				if(complete !== 1) {
					$showAllNotesButton.show();
					$completedNoteButton.html('	Show Completed Notes');
				} else {
					// change the button text. Remove the show all notes.
					$showAllNotesButton.hide();
					$completedNoteButton.html('	Show Active Notes');
				}
			}
		})
		.fail(function(error) {
			console.log('It failed: ', error);
		});
	}

	function loadTags() {

		$.ajax({
			url: 'includes/load-tags.php',
			method: 'POST'
		})
		.done(function(data, result) {
			if(result == 'success') {
				$('#add-note-tags').append(data);
				toastr.info('Loading success');
			}
		})
		.fail(function(error) {
			console.log(error);
		});
	}

	function addTag() {
		var newTag = $('#add-new-tag-text').val();

		if(newTag.trim() !== '') {
			$('#add-note-tags').append('
<input type="checkbox" checked name="new-tag" data-tag="' + newTag + '" value="' + newTag + '">' + newTag + '
');
			$('#add-new-tag-text').val('');
		}
	}

	toastr.options = {
		"timeOut": "2000",
		"preventDuplicates": false,
		"closeButton": true
	};

	// Hide the form to create new note until clicked
	$('#new-note-section').hide();
	$('.note-text-validation').hide();

	$('#new-note-button').on('click', function(){
		$('#new-note-section').toggle();
	});

	$('#show-new-tag-button').on('click', function() {
		$('#new-tag-section').toggle();
	});

	$showAllNotesButton.on('click', function() {
		$('.note').show();
	});

	$('#add-note-button').on('click', function() {

		var noteText = $('#add-note-text').val();
		var noteTitle = $('#add-note-title').val();
		var tagArray = [];

		if(noteText.trim() === '') {
			$('.note-text-validation').show();
			return;
		}

		$('input:checkbox[name=new-tag]:checked').each(function() {
			tagArray.push($(this).val());
		});

		$.ajax({
			url: 'includes/add-new-note.php',
			method: 'POST',
			data: {
				noteText: noteText,
				noteTags: tagArray,
				noteTitle: noteTitle,
				userId: userId
			}
		})
		.done(function(data, result) {
			var tags = '';
			$.each(tagArray, function(index, value) {
				tags += '' + value + '';
			});

			$noteList.append('
Note ID: ' + data + '
' + noteTitle + '

' + noteText + '
' + tags + '

');

			// Reset and confirmation.
			$('#add-note-title').val('');
			$('#add-note-text').val('');
			$('input:checkbox[name=new-tag]').removeAttr('checked');
			tagsToAdd = [];
			toastr.success('Note has been added successfully!');
			$('#new-note-section').hide();
		})
		.fail(function(error) {
			console.log('There was a failure: ', error);
		});

	});

	$('#show-new-tag-button').on('click', addTag);

	$noteList.on('click', '.note-tags', function() {

		var tag = $(this).data('tag');
		var notes = $('.note');
		var hide = [];
		$('.note').show();

		$.each(notes, function(index, value) {
			$value = $(value);

			var tags = $value.children('.note-tags');
			var tagData = [];

			$.each(tags, function(i, childTag) {
				$this = $(childTag);
				var data = $this.data('tag');
				tagData.push(data);
			});

			if(tagData.indexOf(tag) === -1) {
				hide.push(value);
			}
		});

		$.each(hide, function(index, value) {
			$(value).hide();
		});

		toastr.info('Now only showing notes with the tag "' + tag + '"');
	});

	$noteList.on('click', '.remove-note', function() {

		if(!confirm('Are you sure you wish to remove this note?')) {
			return;
		}

		$this = $(this);
		var deleteId = $this.closest('.note').data('id');

 		$.ajax({
			method: 'POST',
			url: 'includes/delete-note.php',
			data: {
				deleteNote: deleteId
			}
		})
		.done(function(data, result) {
			$this.closest('.note').remove();
			toastr.success('Note has been deleted!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$noteList.on('click', '.edit-note', function() {
		// edit the note in the database.
		// also edit the note which is in the DOM
		// would probably be best to have this done in a modal.
		// TODO : above - skeleton code is below.
		$this = $(this);
		var newText = '';
		var noteId = $this.closest('.note').data('id');

		$.ajax({
			method: 'POST',
			url: 'includes/',
			data: {
				noteText: newText,
				noteId: noteId
			}
		})
		.done(function(data, result) {
			console.log(data, result);
			// update the DOM here.

			toastr.success('Note successfully updated!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$noteList.on('click', '.note-done', function() {

		$this = $(this);
		var newText = '';
		var noteId = $this.closest('.note').data('id');

		$.ajax({
			method: 'POST',
			url: 'includes/note-done.php',
			data: {
				noteId: noteId
			}
		})
		.done(function(data, result) {
			console.log(data, result)
			$this.closest('.note').remove();
			toastr.success('Note marked as complete!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$completedNoteButton.on('click', function() {
		if(showingComplete) {
			$noteList.empty();
			$completedNoteButton.html('	Show Completed Notes');
			showingComplete = false;
			loadNotes(0);
		} else {
			$noteList.empty();
			$completedNoteButton.html('	Show Active Notes');
			showingComplete = true;
			loadNotes(1);
		}
	});

	$('#add-note-text').on('keyup', function() {
		$('.note-text-validation').hide();
	});

	$('#add-new-tag-text').on('keyup', function(event) {
		if(event.keyCode == 13) {
			addTag();
		}
	});

	$('#refresh-button').on('click', function() {
		window.location.reload();
	});

})();<|endoftext|>


<commit_before>function scrollIntoView (element, alignTop) {
  var document = element.ownerDocument;
  var origin = element, originRect = origin.getBoundingClientRect();
  var hasScroll = false;
  var documentScroll = document.scrollingElement;

  while (element) {
    if (element == document.body) {
      element = documentScroll;
    } else {
      element = element.parentNode;
    }

    if (element) {
      var hasScrollbar = (!element.clientHeight)?
          false : element.scrollHeight > element.clientHeight;
      if (!hasScrollbar) {
        if (element == documentScroll) {
          element = null;
        }
        continue;
      }
      var rects;
      if (element == documentScroll) {
        rects = {
          left: 0,
          top: 0
        };
      } else {
        rects = element.getBoundingClientRect();
      }

      // check that elementRect is in rects
      var deltaLeft =
          originRect.left -
          (rects.left + (parseInt(element.style.borderLeftWidth, 10) | 0));
      var deltaRight =
          originRect.right -
          (rects.left + element.clientWidth +
           (parseInt(element.style.borderLeftWidth, 10) | 0));
      var deltaTop =
          originRect.top -
          (rects.top + (parseInt(element.style.borderTopWidth, 10) | 0));
      var deltaBottom =
        originRect.bottom -
        (rects.top + element.clientHeight +
         (parseInt(element.style.borderTopWidth, 10) | 0));

      // adjust display depending on deltas
      if (deltaLeft < 0) {
        element.scrollLeft += deltaLeft;
      } else if (deltaRight > 0) {
        element.scrollLeft += deltaRight;
      }

      if (alignTop === true && !hasScroll) {
        element.scrollTop += deltaTop;
      } else if (alignTop === false && !hasScroll) {
        element.scrollTop += deltaBottom;
      } else {
        if (deltaTop < 0) {
          element.scrollTop += deltaTop;
        } else if (deltaBottom > 0) {
          element.scrollTop += deltaBottom;
        }
      }

      if (element == documentScroll) {
        element = null;
      } else {
        // readjust element position after scrolls, and check if vertical scroll
        // has changed. This is required to perform only one alignment
        var nextRect = origin.getBoundingClientRect();
        if (nextRect.top != originRect.top) {
          hasScroll = true;
        }
        originRect = nextRect;
      }
    }
  }

  // put the element into middle of the view
  document.body.scrollTop -= screen.height/2;
}

var parser = {};
// Return the node containing the DOM path leading to the html object containing
// offending pattern e.g. Taiwan, Province of China.
parser.getOffendingNode = function() {
  return parser.traverse_(document);
};
parser.getOffendingText = function(node) {
  return parser.matchOffending_(parser.getText_(node));
};
// Private methods.
parser.traverse_ = function(node) {
  for (var x = 0; x < node.children.length; ++x) {
    var child = parser.traverse_(node.children[x]);
    if (child) {
      return child;
    }
  }

  if (node.tagName == 'SCRIPT' ||
      node.tagName == 'TITLE') {
    return null;
  }
  var text = parser.getText_(node);
  if (text) {
    var offendingText = parser.matchOffending_(text);
    if (offendingText) {
      console.log('Offending text: ' + offendingText);
      return node;
    }
  }
  return null;
};
parser.getText_ = function(node) {
  var text = node.text;
  if (node.tagName == 'H2') {
    text = node.textContent;
  } else if (node.tagName == 'A') {
    text = node.innerText;
  }
  return text;
};
parser.patterns_ = [
  new RegExp('taiwan\\s*,?\\s*province\\s*of\\s*china', 'i'),
  new RegExp('taiwan\\s*,?\\s*prc', 'i'),
  new RegExp('chinese\\s*,?\\s*taipei', 'i'),
  new RegExp('taiwan\\s*,?\\s*china', 'i'),
  new RegExp('china\\s*,?\\s*taiwan', 'i')
];
parser.matchOffending_ = function(text) {
  for (var x = 0; x < parser.patterns_.length; ++x) {
    var re = parser.patterns_[x];
    if (text.match(re)) {
      return text;
    }
  }
  return false;
};

var highlightText = function() {

  // add style to element
  this.style.textDecoration = "line-through";

  // add style to parent element
  var parent = this.parentElement;
  parent.style.cssText = 'border: 3;border-style: solid; border-color: #d11212; text-decoration: line-through;';

  // check if element in view, scroll in to view if not.
  var _ele = this;
  $(document).ready(function(){
    scrollIntoView(_ele, true);
  });

  // fade in fade out calling each other for ever
  var fadeOut = function(el) {
    el.style.opacity = 1;

    (function fade() {
      if ((el.style.opacity -= .04) < 0) {
        fadeIn(el);
      } else {
        requestAnimationFrame(fade);
      }
    })();
  };

  var fadeIn = function(el) {
    el.style.opacity = 0;

    (function fade() {
      var val = parseFloat(el.style.opacity);
      if (!((val += .04) > 1)) {
        el.style.opacity = val;
        requestAnimationFrame(fade);
      } else {
        fadeOut(el);
      }
    })();
  };

  // start animation of fade in and fade out
  fadeOut(parent);
};

$(function() {
  var baseUrl = getBaseUrl(location.href);
  var offendingNode = parser.getOffendingNode();
  var offendingText = parser.getOffendingText(offendingNode);
  if (offendingNode) {
    highlightText.call(offendingNode);
  }
  if (offendingNode !== null) {
    const cp = new ContactParser(baseUrl, $(document));
    cp.findMailAddresses(function(mailAddresses) {
      for (var i = 0; i < mailAddresses.length; ++i) {
        console.log(mailAddresses[i]);
      }
    });
  }
});

function getBaseUrl(origUrl) {
  var pathArray = origUrl.split('/');
  var protocol = pathArray[0];
  var host = pathArray[2];
  return protocol + '//' + host;
}
<commit_msg>[parsing] more special case handling<commit_after>function scrollIntoView (element, alignTop) {
  var document = element.ownerDocument;
  var origin = element, originRect = origin.getBoundingClientRect();
  var hasScroll = false;
  var documentScroll = document.scrollingElement;

  while (element) {
    if (element == document.body) {
      element = documentScroll;
    } else {
      element = element.parentNode;
    }

    if (element) {
      var hasScrollbar = (!element.clientHeight)?
          false : element.scrollHeight > element.clientHeight;
      if (!hasScrollbar) {
        if (element == documentScroll) {
          element = null;
        }
        continue;
      }
      var rects;
      if (element == documentScroll) {
        rects = {
          left: 0,
          top: 0
        };
      } else {
        rects = element.getBoundingClientRect();
      }

      // check that elementRect is in rects
      var deltaLeft =
          originRect.left -
          (rects.left + (parseInt(element.style.borderLeftWidth, 10) | 0));
      var deltaRight =
          originRect.right -
          (rects.left + element.clientWidth +
           (parseInt(element.style.borderLeftWidth, 10) | 0));
      var deltaTop =
          originRect.top -
          (rects.top + (parseInt(element.style.borderTopWidth, 10) | 0));
      var deltaBottom =
        originRect.bottom -
        (rects.top + element.clientHeight +
         (parseInt(element.style.borderTopWidth, 10) | 0));

      // adjust display depending on deltas
      if (deltaLeft < 0) {
        element.scrollLeft += deltaLeft;
      } else if (deltaRight > 0) {
        element.scrollLeft += deltaRight;
      }

      if (alignTop === true && !hasScroll) {
        element.scrollTop += deltaTop;
      } else if (alignTop === false && !hasScroll) {
        element.scrollTop += deltaBottom;
      } else {
        if (deltaTop < 0) {
          element.scrollTop += deltaTop;
        } else if (deltaBottom > 0) {
          element.scrollTop += deltaBottom;
        }
      }

      if (element == documentScroll) {
        element = null;
      } else {
        // readjust element position after scrolls, and check if vertical scroll
        // has changed. This is required to perform only one alignment
        var nextRect = origin.getBoundingClientRect();
        if (nextRect.top != originRect.top) {
          hasScroll = true;
        }
        originRect = nextRect;
      }
    }
  }

  // put the element into middle of the view
  document.body.scrollTop -= screen.height/2;
}

var parser = {};
// Return the node containing the DOM path leading to the html object containing
// offending pattern e.g. Taiwan, Province of China.
parser.getOffendingNode = function() {
  return parser.traverse_(document);
};
parser.getOffendingText = function(node) {
  return parser.matchOffending_(parser.getText_(node));
};
// Private methods.
parser.traverse_ = function(node) {
  for (var x = 0; x < node.children.length; ++x) {
    var child = parser.traverse_(node.children[x]);
    if (child) {
      return child;
    }
  }

  if (node.nodeName == 'SCRIPT' ||
      node.nodeName == 'TITLE') {
    return null;
  }
  var text = parser.getText_(node);
  if (text) {
    var offendingText = parser.matchOffending_(text);
    if (offendingText) {
      console.log('Tag name: ' + node.nodeName);
      console.log('Offending text: ' + offendingText);
      return node;
    }
  }
  return null;
};
parser.getText_ = function(node) {
  if (node.nodeName[0] == 'H' && node.nodeName.length == 2) {
    text = node.textContent;
  } else if (node.nodeName == 'A') {
    text = node.innerText;
  } else if (node.nodeName == 'STRONG' || node.nodeName == 'P') {
    text = node.textContent;
  } else {
    text = node.text;
  }
  return text;
};
parser.patterns_ = [
  new RegExp('taiwan\\s*,?\\s*province\\s*of\\s*china', 'i'),
  new RegExp('taiwan\\s*,?\\s*prc', 'i'),
  new RegExp('chinese\\s*,?\\s*taipei', 'i'),
  new RegExp('taiwan\\s*,?\\s*china', 'i'),
  new RegExp('china\\s*,?\\s*taiwan', 'i')
];
parser.matchOffending_ = function(text) {
  for (var x = 0; x < parser.patterns_.length; ++x) {
    var re = parser.patterns_[x];
    if (text.match(re)) {
      return text;
    }
  }
  return false;
};

var highlightText = function() {

  // add style to element
  this.style.textDecoration = "line-through";

  // add style to parent element
  var parent = this.parentElement;
  parent.style.cssText = 'border: 3;border-style: solid; border-color: #d11212; text-decoration: line-through;';

  // check if element in view, scroll in to view if not.
  var _ele = this;
  $(document).ready(function(){
    scrollIntoView(_ele, true);
  });

  // fade in fade out calling each other for ever
  var fadeOut = function(el) {
    el.style.opacity = 1;

    (function fade() {
      if ((el.style.opacity -= .04) < 0) {
        fadeIn(el);
      } else {
        requestAnimationFrame(fade);
      }
    })();
  };

  var fadeIn = function(el) {
    el.style.opacity = 0;

    (function fade() {
      var val = parseFloat(el.style.opacity);
      if (!((val += .04) > 1)) {
        el.style.opacity = val;
        requestAnimationFrame(fade);
      } else {
        fadeOut(el);
      }
    })();
  };

  // start animation of fade in and fade out
  fadeOut(parent);
};

$(function() {
  var baseUrl = getBaseUrl(location.href);
  var offendingNode = parser.getOffendingNode();
  if (offendingNode) {
    highlightText.call(offendingNode);
    var offendingText = parser.getOffendingText(offendingNode);
  }
  if (offendingNode !== null) {
    const cp = new ContactParser(baseUrl, $(document));
    cp.findMailAddresses(function(mailAddresses) {
      for (var i = 0; i < mailAddresses.length; ++i) {
        console.log(mailAddresses[i]);
      }
    });
  }
});

function getBaseUrl(origUrl) {
  var pathArray = origUrl.split('/');
  var protocol = pathArray[0];
  var host = pathArray[2];
  return protocol + '//' + host;
}
<|endoftext|>


<commit_before>/**
 * Get Icon Lists from ajax function, and append into element html
 * @return {[type]} [description]
 */
window.onload = function() {
  // //get params
  // var paramBy = Belancon.getUrlParameter('by') ? Belancon.getUrlParameter('by') : null;
  // var by = paramBy ? paramBy : "newest";
  // var paramSearch = Belancon.getUrlParameter('search') ? Belancon.getUrlParameter('search') : null;
  // var search = paramSearch ? paramSearch : "";

  // //call method to get icon lists
  // Icon.getAll(1, by, search);

  // Icon.getCart();
  // Cart.getAll();

  // //if param ready, redirect url with params
  // if(paramBy !== null) {
  //   if(paramSearch !== null) {
  //     window.history.pushState("", "", BASE_URL + "?by=" + paramBy + "&search=" + search);
  //   } else {
  //     window.history.pushState("", "", BASE_URL + "?by=" + paramBy);
  //   }
  // }
}

$(document).ready(function () {
    //get params
    var paramBy = Belancon.getUrlParameter('by') ? Belancon.getUrlParameter('by') : null;
    var by = paramBy ? paramBy : "newest";
    var paramSearch = Belancon.getUrlParameter('search') ? Belancon.getUrlParameter('search') : null;
    var search = paramSearch ? paramSearch : "";

    //call method to get icon lists
    Icon.getAll(1, by, search);

    Icon.getCart();
    Cart.getAll();

    //if param ready, redirect url with params
    if(paramBy !== null) {
      if(paramSearch !== null) {
        window.history.pushState("", "", BASE_URL + "?by=" + paramBy + "&search=" + search);
      } else {
        window.history.pushState("", "", BASE_URL + "?by=" + paramBy);
      }
    }

    /**
     * Action When Search Form Submitted
     */
    $('#form-search-icon').submit(function(e) {
      e.preventDefault();
      var search = $('#search-icon').val().trim();

      if(search.length < 3) {

        /** Message Error */

        var opts = {
          "debug": false,
          "positionClass": "toast-top-right",
          "onclick": null,
          "showDuration": "300",
          "hideDuration": "1000",
          "timeOut": "5000",
          "extendedTimeOut": "1000",
          "showEasing": "swing",
          "hideEasing": "linear",
          "showMethod": "fadeIn",
          "hideMethod": "fadeOut"
        };
        toastr.error("Gunakan minimal 3 karakter dalam pencarian Icon.", "Warning !", opts);

      } else {
        var url = BASE_URL + "result?search=" + search;
        window.location = url;
      }
    });

    /**
     * Action when tab panel clicked
     */
    $('.btn-filter').click(function() {
      var filter = $(this).attr('data-filter');

      Icon.changefilter(filter);
    });

    /**
     * Action When Button Loadmore clicked
     */
    $(document).on('click', '#btn-load-more', function(){
      var currentUrlString = window.location.href;
      var currentUrlArr = currentUrlString.split("?");
      var currentUrl = currentUrlArr[0];

      var paramBy = Belancon.getUrlParameter('by') ? Belancon.getUrlParameter('by'): null;
      var paramSearch = Belancon.getUrlParameter('search') ? Belancon.getUrlParameter('search') : null;
      var by = paramBy ? paramBy : "newest";
      var search = paramSearch ? paramSearch : "";
      var page = $(this).attr('data-page');

      Icon.getAll(page, by, search);

      if(paramBy) {
        if(paramSearch) {
          window.history.pushState("", "", BASE_URL + "?by=" +by + "&search=" + search);
        } else {
          window.history.pushState("", "", BASE_URL + "?by=" +by);
        }
      }

    });

    /**
     * Action when button add cart clicked
     */
    $(document).on('click', '.btn-add-cart', function(){
      var id = $(this).attr('data-id');
      var name = $(this).attr('data-name');

      Icon.addToCart(id, name);
    });

    /**
     * Action when button remove cart clicked
     */
    $(document).on('click', '.btn-remove-cart', function(){
      var id = $(this).attr('data-id');
      var name = $(this).attr('data-name');

      Icon.removeFromCart(id, name);
    });

    /**
     * Action when button download icon clicked
     */
    $(document).on('click', '.btn-download-icon', function(){
      $('.btn-download-icon').button('loading');
      var type = $('input[name=format-file-options]:checked').val();

      if(type) {
        //Ajax method
        $.ajax({
         type: "post",
         url: BASE_URL + "icon/download_all",
         cache: false,
         data: {type: type},
         success: function(response){
            response = JSON.parse(response);
            //console.log(response.path);
            if(response.status === true) {
             window.location = response.path;
            }

            $('.btn-download-icon').button('reset');
            setTimeout(function(){ window.location = BASE_URL; }, 2000);
         },
         error: function(){
          alert('Error while request..');
         }
        });
      } else {

        /** Message Error */
        var opts = {
          "debug": false,
          "positionClass": "toast-top-right",
          "onclick": null,
          "showDuration": "300",
          "hideDuration": "1000",
          "timeOut": "5000",
          "extendedTimeOut": "1000",
          "showEasing": "swing",
          "hideEasing": "linear",
          "showMethod": "fadeIn",
          "hideMethod": "fadeOut"
        };
        toastr.error("Silahkan pilih tipe file yang akan didownload.", "Warning !", opts);
        $('.btn-download-icon').button('reset');
      }
    });

    /**
     * Action when button view icon clicked
     */
    $(document).on('click', '.btn-view-icon', function() {
      var id = $(this).attr('data-id');
      Icon.view(id, function(result) {
        if(result) {
          $('.modal-view-icon').modal('show');
        }
      })
    });

});

window.unload = function(e) {

};

"console" in window && console.log("%cHi Developer\nIf you find an error please report  on this page %chttps://dev.belancon.com/bug/\n%cGive your feedback on this page %chttps://dev.belancon.com/feedback/",
  "color: #000000; font-size: 17px; line-height: 2",
  "color: #2bbbad; font-size: 17px; line-height: 2; font-style: normal",
  "color: #000000; font-size: 17px; line-height: 2",
  "color: #2bbbad; font-size: 17px; line-height: 2; font-style: normal"); <commit_msg>remove window.unload<commit_after>/**
 * Get Icon Lists from ajax function, and append into element html
 * @return {[type]} [description]
 */
$(document).ready(function () {
    //get params
    var paramBy = Belancon.getUrlParameter('by') ? Belancon.getUrlParameter('by') : null;
    var by = paramBy ? paramBy : "newest";
    var paramSearch = Belancon.getUrlParameter('search') ? Belancon.getUrlParameter('search') : null;
    var search = paramSearch ? paramSearch : "";

    //call method to get icon lists
    Icon.getAll(1, by, search);

    Icon.getCart();
    Cart.getAll();

    //if param ready, redirect url with params
    if(paramBy !== null) {
      if(paramSearch !== null) {
        window.history.pushState("", "", BASE_URL + "?by=" + paramBy + "&search=" + search);
      } else {
        window.history.pushState("", "", BASE_URL + "?by=" + paramBy);
      }
    }

    /**
     * Action When Search Form Submitted
     */
    $('#form-search-icon').submit(function(e) {
      e.preventDefault();
      var search = $('#search-icon').val().trim();

      if(search.length < 3) {

        /** Message Error */

        var opts = {
          "debug": false,
          "positionClass": "toast-top-right",
          "onclick": null,
          "showDuration": "300",
          "hideDuration": "1000",
          "timeOut": "5000",
          "extendedTimeOut": "1000",
          "showEasing": "swing",
          "hideEasing": "linear",
          "showMethod": "fadeIn",
          "hideMethod": "fadeOut"
        };
        toastr.error("Gunakan minimal 3 karakter dalam pencarian Icon.", "Warning !", opts);

      } else {
        var url = BASE_URL + "result?search=" + search;
        window.location = url;
      }
    });

    /**
     * Action when tab panel clicked
     */
    $('.btn-filter').click(function() {
      var filter = $(this).attr('data-filter');

      Icon.changefilter(filter);
    });

    /**
     * Action When Button Loadmore clicked
     */
    $(document).on('click', '#btn-load-more', function(){
      var currentUrlString = window.location.href;
      var currentUrlArr = currentUrlString.split("?");
      var currentUrl = currentUrlArr[0];

      var paramBy = Belancon.getUrlParameter('by') ? Belancon.getUrlParameter('by'): null;
      var paramSearch = Belancon.getUrlParameter('search') ? Belancon.getUrlParameter('search') : null;
      var by = paramBy ? paramBy : "newest";
      var search = paramSearch ? paramSearch : "";
      var page = $(this).attr('data-page');

      Icon.getAll(page, by, search);

      if(paramBy) {
        if(paramSearch) {
          window.history.pushState("", "", BASE_URL + "?by=" +by + "&search=" + search);
        } else {
          window.history.pushState("", "", BASE_URL + "?by=" +by);
        }
      }

    });

    /**
     * Action when button add cart clicked
     */
    $(document).on('click', '.btn-add-cart', function(){
      var id = $(this).attr('data-id');
      var name = $(this).attr('data-name');

      Icon.addToCart(id, name);
    });

    /**
     * Action when button remove cart clicked
     */
    $(document).on('click', '.btn-remove-cart', function(){
      var id = $(this).attr('data-id');
      var name = $(this).attr('data-name');

      Icon.removeFromCart(id, name);
    });

    /**
     * Action when button download icon clicked
     */
    $(document).on('click', '.btn-download-icon', function(){
      $('.btn-download-icon').button('loading');
      var type = $('input[name=format-file-options]:checked').val();

      if(type) {
        //Ajax method
        $.ajax({
         type: "post",
         url: BASE_URL + "icon/download_all",
         cache: false,
         data: {type: type},
         success: function(response){
            response = JSON.parse(response);
            //console.log(response.path);
            if(response.status === true) {
             window.location = response.path;
            }

            $('.btn-download-icon').button('reset');
            setTimeout(function(){ window.location = BASE_URL; }, 2000);
         },
         error: function(){
          alert('Error while request..');
         }
        });
      } else {

        /** Message Error */
        var opts = {
          "debug": false,
          "positionClass": "toast-top-right",
          "onclick": null,
          "showDuration": "300",
          "hideDuration": "1000",
          "timeOut": "5000",
          "extendedTimeOut": "1000",
          "showEasing": "swing",
          "hideEasing": "linear",
          "showMethod": "fadeIn",
          "hideMethod": "fadeOut"
        };
        toastr.error("Silahkan pilih tipe file yang akan didownload.", "Warning !", opts);
        $('.btn-download-icon').button('reset');
      }
    });

    /**
     * Action when button view icon clicked
     */
    $(document).on('click', '.btn-view-icon', function() {
      var id = $(this).attr('data-id');
      Icon.view(id, function(result) {
        if(result) {
          $('.modal-view-icon').modal('show');
        }
      })
    });

});

window.unload = function(e) {

};

"console" in window && console.log("%cHi Developer\nIf you find an error please report  on this page %chttps://dev.belancon.com/bug/\n%cGive your feedback on this page %chttps://dev.belancon.com/feedback/",
  "color: #000000; font-size: 17px; line-height: 2",
  "color: #2bbbad; font-size: 17px; line-height: 2; font-style: normal",
  "color: #000000; font-size: 17px; line-height: 2",
  "color: #2bbbad; font-size: 17px; line-height: 2; font-style: normal"); <|endoftext|>


<commit_before>var send = require(CONFIG.root + "/core/send.js").send;
var read = require(CONFIG.root + "/core/util.js").read;
var stat = require("node-static").Server;
var model = require(CONFIG.root + "/core/model");
var client = new stat(CONFIG.root + "/core/client");
var modules = new stat(CONFIG.root + "/apps/" + CONFIG.app + "/mono_modules");

exports.getConfig = function(link) {

    // get the module instance id
    var miid = link.path[0] ? link.path[0].replace(/[^0-9a-z_\-\.]/gi, "") : null;

    if (!miid) {
        send.badrequest(link, "No miid defined");
        return;
    }

    // send no cache headers IE bug
    link.res.headers["cache-control"] = "no-cache";

    model.getAppId(link.host, function(err, appid, errMiid) {

        if (err || !appid) {
            send.internalservererror(link, err || "Missing appid");
            return;
        }

        var getModuleConfig = function(miid) {

            model.getModuleConfig(appid, miid, link.session.uid, function(err, module) {

                // error checks
                if (err || !module) {
                    if (errMiid) {
                        send.ok(link.res, { type: "miid", data: errMiid });
                    } else {
                        send.ok(link.res, { type: "text", data: "No such module found: " + miid });
                    }
                    return;
                }

                var response = module.config || {};

                response.path = module.source + "/" + module.owner + "/" + module.name + "/" + module.version;
                // TODO is maybe another solution to let modules also define their language?
                //response.lang = link.session.loc || module.lang || "en";
                response.role = link.session.role;

                if (module.config && module.config.html) {

                    // get module from app folder
                    var path = "/apps/" + appid + "/";

                    // get module from module folder
                    if (module.config.html.type == "m") {
                        path += "mono_modules/" + module.source + "/" + module.owner + "/" + module.name + "/" + module.version + "/";
                    }

                    var pathAll = path + module.config.html.path + ".html";
                    var pathLang = path + module.config.html.path + (link.lang === "*" ? "" : "." + link.lang) + ".html";

                    var setModuleHtml = function(err, html) {

                        if (err) {
                            // TODO let the module define it's missing module placeholder
                            html = "
An error occurred while retrieving this module HTML.
";
                            if (CONFIG.logLevel == "debug") {
                                html += "
Error: " + err + "
"
                            }
                        }
                        response.html = html;
                        send.ok(link.res, { type: "config", data: response });
                    };

                    read(pathLang, "utf8", function(err, html) {

                        if (err) {
                            if (link.lang !== "*") {
                                read(pathAll, "utf8", setModuleHtml);
                                return;
                            }

                            setModuleHtml(err);
                        }

                        response.html = html;
                        send.ok(link.res, { type: "config", data: response });
                    });
                }
                else {
                    send.ok(link.res, { type: "config", data: response });
                }
            });
        };

        getModuleConfig(miid);
    });
};

// browser modules
exports.getModule = function(link) {

    // error checks
    if (!link.path || !link.path[0] || !link.path[1] || !link.path[2] || !link.path[3]) {
        send.badrequest(link, "Incorrect module request URL format");
        return;
    }

    // get the module instance id
    var source = link.path[0].replace(/[^0-9a-z_\-\.]/gi, ""),
        owner = link.path[1].replace(/[^0-9a-z_\-\.]/gi, ""),
        name = link.path[2].replace(/[^0-9a-z_\-\.]/gi, ""),
        version = link.path[3].replace(/[^0-9a-z_\-\.]/gi, ""),
        path = link.path.slice(4).join("/").replace(/[^a-z0-9\/\.\-_]|\.\.\//gi, "");

    // the module name must be almost alphanumeric
    if (source.length != link.path[0].length || owner.length != link.path[1].length || name.length != link.path[2].length || version.length != link.path[3].length) {
        send.badrequest(link, "Incorrect data in module request URL");
        return;
    }

    // find the module in the database
    model.getModuleFile(source, owner, name, link.session.uid, function(err, module) {

        // error checks
        if (err || !module) {
            send.notfound(link, err || ("Could not find module: " + miid));
            return;
        }

        // now serve the module file
        link.req.url = source + "/" + owner + "/" + name + "/" + version + "/" + (module.dir ? module.dir + "/" : "") + path;

        modules.serve(link.req, link.res);
    });
};

exports.getClient = function(link){

    link.req.url = link.path[0];

    client.serve(link.req, link.res);
};
<commit_msg>cache module configurations, fixes #15<commit_after>var send = require(CONFIG.root + "/core/send.js").send;
var read = require(CONFIG.root + "/core/util.js").read;
var stat = require("node-static").Server;
var model = require(CONFIG.root + "/core/model");
var client = new stat(CONFIG.root + "/core/client");
var modules = new stat(CONFIG.root + "/apps/" + CONFIG.app + "/mono_modules");

var configCache = {};

exports.getConfig = function(link) {

    // get the module instance id
    var miid = link.path[0] ? link.path[0].replace(/[^0-9a-z_\-\.]/gi, "") : null;

    if (!miid) {
        send.badrequest(link, "No miid defined");
        return;
    }

    // send no cache headers IE bug
    link.res.headers["cache-control"] = "no-cache";

    model.getAppId(link.host, function(err, appid, errMiid) {

        if (err || !appid) {
            send.internalservererror(link, err || "Missing appid");
            return;
        }

        var getModuleConfig = function(miid) {

            model.getModuleConfig(appid, miid, link.session.uid, function(err, module) {

                // error checks
                if (err || !module) {
                    if (errMiid) {
                        send.ok(link.res, { type: "miid", data: errMiid });
                    } else {
                        send.ok(link.res, { type: "text", data: "No such module found: " + miid });
                    }
                    return;
                }

                // prepare config cache
                if (!configCache[link.host]) {
                    configCache[link.host] = {};
                }

                var response = module.config || {};

                response.path = module.source + "/" + module.owner + "/" + module.name + "/" + module.version;
                // TODO is maybe another solution to let modules also define their language?
                //response.lang = link.session.loc || module.lang || "en";
                response.role = link.session.role;

                if (module.config && module.config.html) {

                    // get module from app folder
                    var path = "/apps/" + appid + "/";

                    // get module from module folder
                    if (module.config.html.type == "m") {
                        path += "mono_modules/" + module.source + "/" + module.owner + "/" + module.name + "/" + module.version + "/";
                    }

                    var pathAll = path + module.config.html.path + ".html";
                    var pathLang = path + module.config.html.path + (link.lang === "*" ? "" : "." + link.lang) + ".html";

                    var setModuleHtml = function(err, html) {

                        if (err) {
                            // TODO let the module define it's missing module placeholder
                            html = "
An error occurred while retrieving this module HTML.
";
                            if (CONFIG.logLevel == "debug") {
                                html += "
Error: " + err + "
"
                            }
                        }

                        response.html = html;

                        configCache[link.host][miid] = response;
                        send.ok(link.res, { type: "config", data: response });
                    };

                    read(pathLang, "utf8", function(err, html) {

                        if (err) {
                            if (link.lang !== "*") {
                                read(pathAll, "utf8", setModuleHtml);
                                return;
                            }
                        }

                        setModuleHtml(err, html);
                    });
                }
                else {
                    configCache[link.host][miid] = response;
                    send.ok(link.res, { type: "config", data: response });
                }
            });
        };

        // send cached config
        if (configCache[link.host] && configCache[link.host][miid]) {
            return send.ok(link.res, {type: "config", data: configCache[link.host][miid]});
        }

        getModuleConfig(miid);
    });
};

// browser modules
exports.getModule = function(link) {

    // error checks
    if (!link.path || !link.path[0] || !link.path[1] || !link.path[2] || !link.path[3]) {
        send.badrequest(link, "Incorrect module request URL format");
        return;
    }

    // get the module instance id
    var source = link.path[0].replace(/[^0-9a-z_\-\.]/gi, ""),
        owner = link.path[1].replace(/[^0-9a-z_\-\.]/gi, ""),
        name = link.path[2].replace(/[^0-9a-z_\-\.]/gi, ""),
        version = link.path[3].replace(/[^0-9a-z_\-\.]/gi, ""),
        path = link.path.slice(4).join("/").replace(/[^a-z0-9\/\.\-_]|\.\.\//gi, "");

    // the module name must be almost alphanumeric
    if (source.length != link.path[0].length || owner.length != link.path[1].length || name.length != link.path[2].length || version.length != link.path[3].length) {
        send.badrequest(link, "Incorrect data in module request URL");
        return;
    }

    // find the module in the database
    model.getModuleFile(source, owner, name, link.session.uid, function(err, module) {

        // error checks
        if (err || !module) {
            send.notfound(link, err || ("Could not find module: " + miid));
            return;
        }

        // now serve the module file
        link.req.url = source + "/" + owner + "/" + name + "/" + version + "/" + (module.dir ? module.dir + "/" : "") + path;

        modules.serve(link.req, link.res);
    });
};

exports.getClient = function(link){

    link.req.url = link.path[0];

    client.serve(link.req, link.res);
};
<|endoftext|>


<commit_before>/*! MIT License | github.com/kingalfred/canvas */

/*
 * Replace title
 */
if (document.title === 'Log in to canvas') {
  document.title = 'King Alfred School Canvas';
}

/*
 * Add "Check Homework button"
 */
if (window.location.href.indexOf('courses')) {
  var text = 'Calendar';
  var course = window.location.pathname.split('/')[2];

  $('#section-tabs').append(
    `

        ${text}

`
  );
}

/*
 * Parent's multiple children
 */
function addChooseChild() {

  $.ajax({
    method: 'get',
    url: '/api/v1/users/self/observees?per_page=50',
    dataType: 'json'
  }).then(children => {
    var p = [];
    for (let child of children) {
      p.push(new Promise(function(resolve, reject) {
        $.ajax({
          method: 'get',
          url: '/api/v1/users/' + child.id + '/courses?per_page=20',
          dataType: 'json'
        }).then(courses => {
          var listCourses = [];
          for (var course of courses) {
            listCourses.push(course.id)
          }
          resolve({
            name: child.name,
            courses: listCourses
          });
        }).fail(err => {
          reject(err);
        });
      }));
    }
    Promise.all(p).then(res => {
      $('#calendar_header').append(`
        <select id="calendar_children" onchange="location = this.value;">
          <option class="calendar_child">Select Child</option>
          ${
            res.map(
              x => `<option class="calendar_child" value=${x.id}>${x.name}</option>`
            )
          }
        </select>
      `)
    })
  }).fail(err => {
    throw err;
  })

};

if (window.location.href.indexOf('calendar')) {
  addChooseChild();
}

/*
 * Change favicon of beta environment and test environment
 */
function changeFavicon(img) {
  var favicon = $('link[rel="shortcut icon"]');
  if (!favicon) $('head').append('<link rel="shortcut icon">');
  favicon.attr('type', 'image/png');
  favicon.attr('href', img);
}

if (window.location.hostname.indexOf('beta') > -1) {
  changeFavicon('https://lh3.googleusercontent.com/rMNbuDeVMWPAF-q1cl12qI_F_h22LZ05xxlaR6JFkRFgpwhYkq3olTEtUJ1j_D5sWbxqruSyu1RujuoKehlayQ1sDaD-mOikNn5heMw7td840kWR78aPLIvtM3gZsgLo6dVkqbZlpA=s64-no');
}

if (window.location.hostname.indexOf('test') > -1) {
  changeFavicon('https://lh3.googleusercontent.com/aWCUYVekhFjnQXVbZ0Iace8zR2UN5_VDaf8bGrsSjfte_LAK8tTBSN2ZyaKVYuBM_jXAvPR1pWey4jNw1AwvtZxXx7qRYi6_RMC3DJZ1tbzqova5BCrY1SVrF9gBgz6gc1Xrmw5z1tdbIgsUEqK1WbJfYaGRJUDSV8VLPJymY5Pkbj41zWrxC7fj5AevrFOMj8UgX70aWJEEfFsgPwPAxOFiL4bYjwjSJIOrqVSeM2HFZ1qzb3NO8Pf2ogLBcERXCA1TgEBpRsBVXuyIOa6SeuwuGramdsrubqM5bqdYBpONPWa-QRwEqmJZPaR8gzK6ijwehvIvRjJxOXmhbmxgf8fBz75Uqi__kZWdJakI9c5Pjz0kFoWt6g6Dl_oYZvYrJnJQ5GCXDkVdXn7jVdsRee3fNZB-ANePDRAEtXz0Q_qSfFTQrMZtRZ-Iou8kqd1jqNDDlA8L4hx1QDI35WAkx-uKsPa7wT-FE70kj_MXay2pcCCgi7hlU_6t8Q_aagoF68vQTt51jr_yvg6YRfHMyzaGhnudhpk5BNNhAFSoyIOWW1QyyYuY4OZZf1YK27q6Kjncw4kG_fC0Qr507CGr8rxoA_7UkpXPijM8alJ-9aUqZFnV9pnBaMiHSuKR8hnq4avKF_lQFC7DnEBnTd8VUf7OPCY3lU5D=w200-h202-no');
}

<commit_msg>fixed checking if in calendar<commit_after>/*! MIT License | github.com/kingalfred/canvas */

/*
 * Replace title
 */
if (document.title === 'Log in to canvas') {
  document.title = 'King Alfred School Canvas';
}

/*
 * Add "Check Homework button"
 */
if (window.location.href.indexOf('courses')) {
  var text = 'Calendar';
  var course = window.location.pathname.split('/')[2];

  $('#section-tabs').append(
    `

        ${text}

`
  );
}

/*
 * Parent's multiple children
 */
function addChooseChild() {

  $.ajax({
    method: 'get',
    url: '/api/v1/users/self/observees?per_page=50',
    dataType: 'json'
  }).then(children => {
    var p = [];
    for (let child of children) {
      p.push(new Promise(function(resolve, reject) {
        $.ajax({
          method: 'get',
          url: '/api/v1/users/' + child.id + '/courses?per_page=20',
          dataType: 'json'
        }).then(courses => {
          var listCourses = [];
          for (var course of courses) {
            listCourses.push(course.id)
          }
          resolve({
            name: child.name,
            courses: listCourses
          });
        }).fail(err => {
          reject(err);
        });
      }));
    }
    Promise.all(p).then(res => {
      $('#calendar_header').append(`
        <select id="calendar_children" onchange="location = this.value;">
          <option class="calendar_child">Select Child</option>
          ${
            res.map(
              x => `<option class="calendar_child" value=${x.id}>${x.name}</option>`
            )
          }
        </select>
      `)
    })
  }).fail(err => {
    throw err;
  })

};

if (window.location.href.indexOf('calendar') > -1) {
  addChooseChild();
}

/*
 * Change favicon of beta environment and test environment
 */
function changeFavicon(img) {
  var favicon = $('link[rel="shortcut icon"]');
  if (!favicon) $('head').append('<link rel="shortcut icon">');
  favicon.attr('type', 'image/png');
  favicon.attr('href', img);
}

if (window.location.hostname.indexOf('beta') > -1) {
  changeFavicon('https://lh3.googleusercontent.com/rMNbuDeVMWPAF-q1cl12qI_F_h22LZ05xxlaR6JFkRFgpwhYkq3olTEtUJ1j_D5sWbxqruSyu1RujuoKehlayQ1sDaD-mOikNn5heMw7td840kWR78aPLIvtM3gZsgLo6dVkqbZlpA=s64-no');
}

if (window.location.hostname.indexOf('test') > -1) {
  changeFavicon('https://lh3.googleusercontent.com/aWCUYVekhFjnQXVbZ0Iace8zR2UN5_VDaf8bGrsSjfte_LAK8tTBSN2ZyaKVYuBM_jXAvPR1pWey4jNw1AwvtZxXx7qRYi6_RMC3DJZ1tbzqova5BCrY1SVrF9gBgz6gc1Xrmw5z1tdbIgsUEqK1WbJfYaGRJUDSV8VLPJymY5Pkbj41zWrxC7fj5AevrFOMj8UgX70aWJEEfFsgPwPAxOFiL4bYjwjSJIOrqVSeM2HFZ1qzb3NO8Pf2ogLBcERXCA1TgEBpRsBVXuyIOa6SeuwuGramdsrubqM5bqdYBpONPWa-QRwEqmJZPaR8gzK6ijwehvIvRjJxOXmhbmxgf8fBz75Uqi__kZWdJakI9c5Pjz0kFoWt6g6Dl_oYZvYrJnJQ5GCXDkVdXn7jVdsRee3fNZB-ANePDRAEtXz0Q_qSfFTQrMZtRZ-Iou8kqd1jqNDDlA8L4hx1QDI35WAkx-uKsPa7wT-FE70kj_MXay2pcCCgi7hlU_6t8Q_aagoF68vQTt51jr_yvg6YRfHMyzaGhnudhpk5BNNhAFSoyIOWW1QyyYuY4OZZf1YK27q6Kjncw4kG_fC0Qr507CGr8rxoA_7UkpXPijM8alJ-9aUqZFnV9pnBaMiHSuKR8hnq4avKF_lQFC7DnEBnTd8VUf7OPCY3lU5D=w200-h202-no');
}

<|endoftext|>


<commit_before>/*
 * Created by marekfort on 13/04/16.
 */

$(document).ready(function(){
    // Setting summary to be centered to the iphone mockup
    $('.section-swipe .summary').css('margin-top', ($('.section-swipe img').height() / 2 - $('.section-swipe .summary').height() / 2 ));
    $('.section-supl .summary').css('margin-top', ($('.section-supl img').height() / 2 - $('.section-supl .summary').height() / 2 ));
});

lastScroll = 0;
shouldAnimate = true;
lastColor = "#3C9BFF";
shouldSlide = true;
$(window).on('scroll', function(){
    scrollTop = $('body').scrollTop();
    scrollingUp = scrollTop < lastScroll;
    lastScroll = scrollTop;
    heightOfTransition = $('.section-supl').height();

    /*
     suplTop = (scrollTop - $('.section-supl').offset().top) / 14;
     $('.section-supl img').css('top', (suplTop));
     swipeTop = (scrollTop - $('.section-swipe').offset().top) / 14;
     $('.section-swipe img').css('top', (swipeTop));
     */

    if  ($('.section-supl').offset().top + heightOfTransition - heightOfTransition / 3 - scrollTop < 0 && lastColor != "#FF3D97" && scrollingUp == false && shouldAnimate ) {
        lastColor = "#FF3D97";
        shouldAnimate = false;
        jQuery(".content").animate({
            backgroundColor: "#FF3D97"
        }, 1500 );
        setTimeout(function(){
            shouldAnimate = true
        },1500);
    }
    else if ($('.section-supl').offset().top + heightOfTransition + heightOfTransition / 3 - scrollTop > 0 && lastColor != "#3C9BFF" && scrollingUp && shouldAnimate) {
        lastColor = "#3C9BFF";
        shouldAnimate = false;
        jQuery(".content").animate({
            backgroundColor: "#3C9BFF"
        }, 1500 );
        setTimeout(function(){
            shouldAnimate = true
        },1500);
    }

    if (scrollTop >= $('.section-me').offset().top - $('.section-me').height() && shouldSlide) {
        $('.slide').addClass('animated fadeInUp');
        shouldSlide = false;
    }
});

$('.portfolio-link').click(function() {
    body = $('body');
    scrollTop = body.scrollTop();
    body.animate({scrollTop : $('.section-supl').offset().top}, 600);
});

$('#about-link').click(function() {
    body = $('body');
    scrollTop = body.scrollTop();
    body.animate({scrollTop : $('.section-me').offset().top}, 600);
});

<commit_msg>Deleted conflicts<commit_after>/*
 * Created by marekfort on 13/04/16.
 */

$(document).ready(function(){
    // Setting summary to be centered to the iphone mockup
    $('.section-swipe .summary').css('margin-top', ($('.section-swipe img').height() / 2 - $('.section-swipe .summary').height() / 2 ));
    $('.section-supl .summary').css('margin-top', ($('.section-supl img').height() / 2 - $('.section-supl .summary').height() / 2 ));
<<<<<<< 45677310c8d6d47bb45c4134c1fc6733e2d7c56f
=======

>>>>>>> Deleted conflicts
});

lastScroll = 0;
shouldAnimate = true;
lastColor = "#3C9BFF";
shouldSlide = true;
$(window).on('scroll', function(){
    scrollTop = $('body').scrollTop();
    scrollingUp = scrollTop < lastScroll;
    lastScroll = scrollTop;
    heightOfTransition = $('.section-supl').height();

    /*
     suplTop = (scrollTop - $('.section-supl').offset().top) / 14;
     $('.section-supl img').css('top', (suplTop));
     swipeTop = (scrollTop - $('.section-swipe').offset().top) / 14;
     $('.section-swipe img').css('top', (swipeTop));
     */

    if  ($('.section-supl').offset().top + heightOfTransition - heightOfTransition / 3 - scrollTop < 0 && lastColor != "#FF3D97" && scrollingUp == false && shouldAnimate ) {
        lastColor = "#FF3D97";
        shouldAnimate = false;
        jQuery(".content").animate({
            backgroundColor: "#FF3D97"
        }, 1500 );
        setTimeout(function(){
            shouldAnimate = true
        },1500);
    }
    else if ($('.section-supl').offset().top + heightOfTransition + heightOfTransition / 3 - scrollTop > 0 && lastColor != "#3C9BFF" && scrollingUp && shouldAnimate) {
        lastColor = "#3C9BFF";
        shouldAnimate = false;
        jQuery(".content").animate({
            backgroundColor: "#3C9BFF"
        }, 1500 );
        setTimeout(function(){
            shouldAnimate = true
        },1500);
    }

    if (scrollTop >= $('.section-me').offset().top - $('.section-me').height() && shouldSlide) {
        $('.slide').addClass('animated fadeInUp');
        shouldSlide = false;
    }
});

$('.portfolio-link').click(function() {
    body = $('body');
    scrollTop = body.scrollTop();
    body.animate({scrollTop : $('.section-supl').offset().top}, 600);
});

$('#about-link').click(function() {
    body = $('body');
    scrollTop = body.scrollTop();
    body.animate({scrollTop : $('.section-me').offset().top}, 600);
});

<|endoftext|>


<commit_before>function threadsToInbox(){
  // reapply the inbox label to threads in the inbox
  // Quota for App script trigger = 6 hours runtime / day ( reference: https://developers.google.com/apps-script/guides/services/quotas )
  //   - If this function is called every 1 minute, the maximum runtime is calculated as follows (must be less than quota as we have other triggers):
  //     - max_runtime < (6 hours total quota / 60 minutes) / (1 trigger/minute * 60 minutes/hr * 24 hr/day )
  //     - max_runtime < (360 minutes quota) / (1440 minutes)
  //     - max_runtime < 15 seconds or 15000 milliseconds
  // Average runtime should be between 2 to 4 seconds (unless the inbox is full of threads of length 10000+)

  var config = Configuration.getCurrent();
  if (config.debug){
    // override GAS console logger and use our spreadsheet
    // defined as environment variable for debug configuration
    Logger = BetterLog.useSpreadsheet(config.sheets.logSheetId);
    Logger.level = BetterLogLevels.DEBUG;
  }

  // startTime is only used for profiling in debug mode
  // the call to config/logger is not included in timing
  var startTime = new Date().getTime();

  var threads = GmailApp.getInboxThreads(0,15); //we don't need to look at everything in the inbox just most recent 15 threads
  var messages = GmailApp.getMessagesForThreads(threads);
  // get all email addresses and aliases for the current user as a list
  var my_email_addresses = JSON.parse(PropertiesService.getScriptProperties().getProperty("email_addresses"));
  var threadsToUpdate = [];

  if (messages === null){
    Logger.warning("Mail Script `messages` = " + typeof messages);
    return;
  } else {

    for (var i = 0; i < messages.length; i++) {

      var len = 0;
      try{
        len = messages[i].length-1;
      }catch(e) {
        Logger.error("Mail Script Error : messages[i].length-1. Error message: " + e.message);
        // return early
        return;
      }

      var last_sender_email = getLastSenderEmail(messages[i][len].getFrom());
      // if we are not the last sender in the thread, then add thread to update list
      // we need to move new messages to the appropriate place within the priority inbox
      if (indexOf.call(my_email_addresses, last_sender_email) < 0) {
        threadsToUpdate.push(threads[i]);
      }
    }
  }

  if (threadsToUpdate.length > 0) {
    GmailApp.moveThreadsToInbox(threadsToUpdate);
    GmailApp.refreshThreads(threadsToUpdate);
  }

  Logger.debug("Function runtime in (ms): %s", new Date().getTime() - startTime);
}

// snooze conversation -- return the conversation to the inbox after XX days of last message count
function snooze(){
  // label variables
  // you must make the "snooze" label and at least one time label
  // time labels in your gmail interface must match those below
  // you can use a combination of labels
  var snoozeLabel = "snooze";
  var awakeLabel = "awake";
  var timeLabels = ["4w","1w","3d","1d"];

  var allLabels = GmailApp.getUserLabels();
  var threads = GmailApp.getUserLabelByName(snoozeLabel).getThreads();

  for (var j = 0; j < threads.length; j++) {

    var threadLabels = threads[j].getLabels();
    // filter for timelabels
    var snoozeTimes = filterTimeLabels(threadLabels,timeLabels);
    // add up times from labels - return in milliseconds
    // if no time-label applied, then it will be moved to the inbox the next time the script runs -- runs at midnight-1am GMT
    var timeLimit = sumTimeFromDateLabels(snoozeTimes);

    var lastMessageDate = threads[j].getLastMessageDate();
    var now = new Date();
    var timeBetweenDates = getTimeBetweenDates(lastMessageDate,now);

    if (timeBetweenDates >= timeLimit) {
      for (var i = 0; i < snoozeTimes.length; i++) {
        threads[j].removeLabel(GmailApp.getUserLabelByName(snoozeTimes[i]));
      }
      threads[j].removeLabel(GmailApp.getUserLabelByName(snoozeLabel));
      threads[j].addLabel(GmailApp.getUserLabelByName(awakeLabel));
      threads[j].moveToInbox();
      threads[j].refresh();
    }
  }
}

// nag - require reply from customer within XX days
// move thread to inbox only if there was no reply from the customer to the thread within specified time period
function nag() {
  // label variables -- update to match those in gmail interface if required
  var nagLabel = "nag";
  var replyFailLabel = "failure to reply";
  var timeLabels = ["4w","1w","3d","1d"];
  var my_email_addresses = JSON.parse(PropertiesService.getScriptProperties().getProperty("email_addresses"));

  var allLabels = GmailApp.getUserLabels();
  var threads = GmailApp.getUserLabelByName(nagLabel).getThreads();

  for (var j = 0; j < threads.length; j++) {
    // Last Date = Mon Oct 12 14:48:13 GMT+07:00 2015
    var threadLabels = threads[j].getLabels();
    var messages = threads[j].getMessages();
    var last_sender = getLastSenderEmail(messages[messages.length-1].getFrom());

    var nagTimes = filterTimeLabels(threadLabels,timeLabels);
    var timeLimit = sumTimeFromDateLabels(nagTimes);

    var lastMessageDate = threads[j].getLastMessageDate();
    var now = new Date();
    var timeBetweenDates = getTimeBetweenDates(lastMessageDate,now);

    if (timeBetweenDates >= timeLimit) {

      // if last message in the thread is **not** from our email_addresses
      // this means we got a reply within our nag timelimit
      // and we can remove the nagLabel
      if (indexOf.call(my_email_addresses, last_sender_email) < 0) {
        for (var i = 0; i < nagTimes.length; i++) {
          threads[j].removeLabel(GmailApp.getUserLabelByName(nagTimes[i]));
        }
        threads[j].removeLabel(GmailApp.getUserLabelByName(nagLabel));
        threads[j].refresh();
      } else {
        // the last message in the thread **is** from our email_addresses
        // therefore we assume we didn't get a reply
        // and can add the replyFailLabel

        for (var k = 0; k < nagTimes.length; k++) {
          // remove all nage time labels
          threads[j].removeLabel(GmailApp.getUserLabelByName(nagTimes[k]));
        }
        // remove nag label and apply the replyFailLabel
        threads[j].removeLabel(GmailApp.getUserLabelByName(nagLabel));
        threads[j].addLabel(GmailApp.getUserLabelByName(replyFailLabel));

        threads[j].moveToInbox();
        threads[j].refresh();
      }
    }
  }
}<commit_msg>updating logger levels<commit_after>function threadsToInbox(){
  // reapply the inbox label to threads in the inbox
  // Quota for App script trigger = 6 hours runtime / day ( reference: https://developers.google.com/apps-script/guides/services/quotas )
  //   - If this function is called every 1 minute, the maximum runtime is calculated as follows (must be less than quota as we have other triggers):
  //     - max_runtime < (6 hours total quota / 60 minutes) / (1 trigger/minute * 60 minutes/hr * 24 hr/day )
  //     - max_runtime < (360 minutes quota) / (1440 minutes)
  //     - max_runtime < 15 seconds or 15000 milliseconds
  // Average runtime should be between 2 to 4 seconds (unless the inbox is full of threads of length 10000+)

  var config = Configuration.getCurrent();
  if (config.debug){
    // override GAS console logger and use our spreadsheet
    // defined as environment variable for debug configuration
    Logger = BetterLog.useSpreadsheet(config.sheets.logSheetId);
    Logger.level = BetterLogLevels.DEBUG;
  } else {
    Logger.level = BetterLogLevels.INFO;
  }

  // startTime is only used for profiling in debug mode
  // the call to config/logger is not included in timing
  var startTime = new Date().getTime();

  var threads = GmailApp.getInboxThreads(0,15); //we don't need to look at everything in the inbox just most recent 15 threads
  var messages = GmailApp.getMessagesForThreads(threads);
  // get all email addresses and aliases for the current user as a list
  var my_email_addresses = JSON.parse(PropertiesService.getScriptProperties().getProperty("email_addresses"));
  var threadsToUpdate = [];

  if (messages === null){
    Logger.warning("Mail Script `messages` = " + typeof messages);
    return;
  } else {

    for (var i = 0; i < messages.length; i++) {

      var len = 0;
      try{
        len = messages[i].length-1;
      }catch(e) {
        Logger.error("Mail Script Error : messages[i].length-1. Error message: " + e.message);
        // return early
        return;
      }

      var last_sender_email = getLastSenderEmail(messages[i][len].getFrom());
      // if we are not the last sender in the thread, then add thread to update list
      // we need to move new messages to the appropriate place within the priority inbox
      if (indexOf.call(my_email_addresses, last_sender_email) < 0) {
        threadsToUpdate.push(threads[i]);
      }
    }
  }

  if (threadsToUpdate.length > 0) {
    GmailApp.moveThreadsToInbox(threadsToUpdate);
    GmailApp.refreshThreads(threadsToUpdate);
  }

  Logger.debug("Function runtime in (ms): %s", new Date().getTime() - startTime);
}

// snooze conversation -- return the conversation to the inbox after XX days of last message count
function snooze(){
  // label variables
  // you must make the "snooze" label and at least one time label
  // time labels in your gmail interface must match those below
  // you can use a combination of labels
  var snoozeLabel = "snooze";
  var awakeLabel = "awake";
  var timeLabels = ["4w","1w","3d","1d"];

  var allLabels = GmailApp.getUserLabels();
  var threads = GmailApp.getUserLabelByName(snoozeLabel).getThreads();

  for (var j = 0; j < threads.length; j++) {

    var threadLabels = threads[j].getLabels();
    // filter for timelabels
    var snoozeTimes = filterTimeLabels(threadLabels,timeLabels);
    // add up times from labels - return in milliseconds
    // if no time-label applied, then it will be moved to the inbox the next time the script runs -- runs at midnight-1am GMT
    var timeLimit = sumTimeFromDateLabels(snoozeTimes);

    var lastMessageDate = threads[j].getLastMessageDate();
    var now = new Date();
    var timeBetweenDates = getTimeBetweenDates(lastMessageDate,now);

    if (timeBetweenDates >= timeLimit) {
      for (var i = 0; i < snoozeTimes.length; i++) {
        threads[j].removeLabel(GmailApp.getUserLabelByName(snoozeTimes[i]));
      }
      threads[j].removeLabel(GmailApp.getUserLabelByName(snoozeLabel));
      threads[j].addLabel(GmailApp.getUserLabelByName(awakeLabel));
      threads[j].moveToInbox();
      threads[j].refresh();
    }
  }
}

// nag - require reply from customer within XX days
// move thread to inbox only if there was no reply from the customer to the thread within specified time period
function nag() {
  // label variables -- update to match those in gmail interface if required
  var nagLabel = "nag";
  var replyFailLabel = "failure to reply";
  var timeLabels = ["4w","1w","3d","1d"];
  var my_email_addresses = JSON.parse(PropertiesService.getScriptProperties().getProperty("email_addresses"));

  var allLabels = GmailApp.getUserLabels();
  var threads = GmailApp.getUserLabelByName(nagLabel).getThreads();

  for (var j = 0; j < threads.length; j++) {
    // Last Date = Mon Oct 12 14:48:13 GMT+07:00 2015
    var threadLabels = threads[j].getLabels();
    var messages = threads[j].getMessages();
    var last_sender = getLastSenderEmail(messages[messages.length-1].getFrom());

    var nagTimes = filterTimeLabels(threadLabels,timeLabels);
    var timeLimit = sumTimeFromDateLabels(nagTimes);

    var lastMessageDate = threads[j].getLastMessageDate();
    var now = new Date();
    var timeBetweenDates = getTimeBetweenDates(lastMessageDate,now);

    if (timeBetweenDates >= timeLimit) {

      // if last message in the thread is **not** from our email_addresses
      // this means we got a reply within our nag timelimit
      // and we can remove the nagLabel
      if (indexOf.call(my_email_addresses, last_sender_email) < 0) {
        for (var i = 0; i < nagTimes.length; i++) {
          threads[j].removeLabel(GmailApp.getUserLabelByName(nagTimes[i]));
        }
        threads[j].removeLabel(GmailApp.getUserLabelByName(nagLabel));
        threads[j].refresh();
      } else {
        // the last message in the thread **is** from our email_addresses
        // therefore we assume we didn't get a reply
        // and can add the replyFailLabel

        for (var k = 0; k < nagTimes.length; k++) {
          // remove all nage time labels
          threads[j].removeLabel(GmailApp.getUserLabelByName(nagTimes[k]));
        }
        // remove nag label and apply the replyFailLabel
        threads[j].removeLabel(GmailApp.getUserLabelByName(nagLabel));
        threads[j].addLabel(GmailApp.getUserLabelByName(replyFailLabel));

        threads[j].moveToInbox();
        threads[j].refresh();
      }
    }
  }
}<|endoftext|>


<commit_before>/*$(document).ready(function() {
    var $header = $("#mainSearch"),
        $clone = $header.before($header.clone().addClass("clone"));

    $(window).on("scroll", function() {
        var fromTop = $("html,body").scrollTop();
        $(window).toggleClass("down", (fromTop > 400));
    });
});*/

	$(window).scroll(function(event) {
		console.log($(window).scrollTop());
		if($(window).scrollTop() >= 249) {
			$('.mainSearch').addClass('.down');
		} else {
			if($('.mainSearch').hasClass('.down')) {
				$('.mainSearch').removeClass('.down');
			}
		}

	});
<commit_msg>remove some dots<commit_after>/*$(document).ready(function() {
    var $header = $("#mainSearch"),
        $clone = $header.before($header.clone().addClass("clone"));

    $(window).on("scroll", function() {
        var fromTop = $("html,body").scrollTop();
        $(window).toggleClass("down", (fromTop > 400));
    });
});*/

	$(window).scroll(function(event) {
		console.log($(window).scrollTop());
		if($(window).scrollTop() >= 249) {
			$('.mainSearch').addClass('down');
		} else {
			if($('.mainSearch').hasClass('down')) {
				$('.mainSearch').removeClass('down');
			}
		}

	});
<|endoftext|>


<commit_before>$(function(){
    $(".home").fadeIn(4000);

    $(".back-to-top-link").click(function(e) {
        // e.preventDefault();
        $('html, body').animate({
            scrollTop: $("#top").offset().top
        }, 1000);
    });
    $(".about").click(function(e) {
        // e.preventDefault();
        $('html, body').animate({
            scrollTop: $("#about").offset().top
        }, 1000);
    });
    $(".music").click(function(e) {
        // e.preventDefault();
        $('html, body').animate({
            scrollTop: $("#music").offset().top
        }, 1000);
    });

    function registerServiceWorker(){
        if ('serviceWorker' in navigator ){
            navigator.serviceWorker.register('sw.js', { scope: '/' }).then(     () => { console.log('Service worker successfully registered');
            }).catch( error => { console.log('Registration failed', error) } )
        }
    }
    registerServiceWorker();
})
<commit_msg>service worker<commit_after>$(function(){
    $(".home").fadeIn(4000);

    $(".back-to-top-link").click(function(e) {
        // e.preventDefault();
        $('html, body').animate({
            scrollTop: $("#top").offset().top
        }, 1000);
    });
    $(".about").click(function(e) {
        // e.preventDefault();
        $('html, body').animate({
            scrollTop: $("#about").offset().top
        }, 1000);
    });
    $(".music").click(function(e) {
        // e.preventDefault();
        $('html, body').animate({
            scrollTop: $("#music").offset().top
        }, 1000);
    });

    function registerServiceWorker(){
        if ('serviceWorker' in navigator ){
            navigator.serviceWorker.register('sw.js', { scope: '/ICE-HEIST/' }).then(     () => { console.log('Service worker successfully registered');
            }).catch( error => { console.log('Registration failed', error) } )
        }
    }
    registerServiceWorker();
})
<|endoftext|>