<commit_before>/**
 * PhisiJs demo for "Let's Get Physical (with WebGL)" - 30 September 2015
 * (c) 2015 www.3dweb.cc
 * @author Pietro Grandi
 */

// put the variables you want to access from the console here
var container, renderer, scene, camera, letters;

function startScene() {
    'use strict';

    Physijs.scripts.worker = '/js/lib/physijs_worker.js';
    Physijs.scripts.ammo = '/js/lib/ammo.js';

    // boilerplate
    container = document.getElementById('theContainer');

    renderer = new THREE.WebGLRenderer();
    renderer.setClearColor(0xaabbff);
    renderer.setSize(640, 480);

    scene = new Physijs.Scene();
    scene.setGravity(new THREE.Vector3( 0, -30, 0 ));

    camera = new THREE.PerspectiveCamera(50, 640 / 480, 0.1, 8000);
    camera.position.set(0, 0, 40);

    container.appendChild(renderer.domElement);

    // warmer light from upper right
    var theLight1 = new THREE.DirectionalLight(0xffdddd, 1);
    theLight1.position.set(10, 10, 20);
    scene.add(theLight1);

    // colder light from upper left
    var theLight2 = new THREE.DirectionalLight(0xddddff, 0.7);
    theLight2.position.set(10, 10, -20);
    scene.add(theLight2);

    var size = 4;
    letters = buildText('3DWeb.cc');

    var posX = -size * (letters.length / 2);

    letters.map(function(letter, index) {
        scene.add(letter);
        letter.position.set(
            posX + (size * index) + 10,
            0,
            0
        );
        letter.__dirtyPosition = true;
    });

    scene.simulate();

    function random()
    {
        var result = '';

        while (result.length < 2)
        {
            result = (Math.round(Math.random()*1000).toString().slice(0,2))
        }

        return result;
    }

    function buildText(text)
    {
        var letters = text.split('').map(function(letter, index) {
            var material = new THREE.MeshLambertMaterial(
                {
                    color: ('#FF' + random() + random() )
                }
            );

            var physijsMaterial = Physijs.createMaterial(
                material,
                0.6, // high friction
                0.3 // low restitution
            );

            var letterGeometry = new THREE.TextGeometry(
                letter,
                {
                    size : 2,
                    height: 1
                }
            );

            var letterMesh = new Physijs.BoxMesh( letterGeometry, physijsMaterial );

            return letterMesh;
        });

        return letters;
    }

    function animate()
    {

        scene.simulate();

        renderer.render(scene, camera);

        requestAnimationFrame(animate);

    }

    animate();

}
<commit_msg>bouncing letters<commit_after>/**
 * PhisiJs demo for "Let's Get Physical (with WebGL)" - 30 September 2015
 * (c) 2015 www.3dweb.cc
 * @author Pietro Grandi
 */

// put the variables you want to access from the console here
var container, renderer, scene, camera, letters;

function startScene() {
    'use strict';

    Physijs.scripts.worker = '/js/lib/physijs_worker.js';
    Physijs.scripts.ammo = '/js/lib/ammo.js';

    // boilerplate
    container = document.getElementById('theContainer');

    renderer = new THREE.WebGLRenderer();
    renderer.setClearColor(0xaabbff);
    renderer.setSize(640, 480);

    scene = new Physijs.Scene();
    scene.setGravity(new THREE.Vector3( 0, -30, 0 ));

    camera = new THREE.PerspectiveCamera(50, 640 / 480, 0.1, 8000);
    camera.position.set(0, 0, 40);

    container.appendChild(renderer.domElement);

    // warmer light from upper right
    var theLight1 = new THREE.DirectionalLight(0xffdddd, 1);
    theLight1.position.set(10, 10, 20);
    scene.add(theLight1);

    // colder light from upper left
    var theLight2 = new THREE.DirectionalLight(0xddddff, 0.7);
    theLight2.position.set(10, 10, -20);
    scene.add(theLight2);

    var size = 6;
    letters = buildText('3DWeb.cc');

    var posX = -size * (letters.length / 2);

    letters.map(function(letter, index) {
        scene.add(letter);
        letter.position.set(
            posX + (size * index),
            10,
            0
        );
        letter.__dirtyPosition = true;
    });

    // ground

    var groundMaterial = new THREE.MeshLambertMaterial({ color: 0x4433aa });
    var ground = new Physijs.BoxMesh(
        new THREE.PlaneGeometry(20, 20),
        Physijs.createMaterial(groundMaterial, 0.1, 2.0)
    );
    ground.rotateX(-Math.PI/2);
    ground.__dirtyRotation = true;
    ground.position.setY(-4);
    ground.__dirtyPosition = true;

    var ground2 = new Physijs.BoxMesh(
        new THREE.PlaneGeometry(100, 40),
        Physijs.createMaterial(groundMaterial, 0.1, 0.6)
    );
    ground2.rotateX( -Math.PI / 2 );
    ground2.__dirtyRotation = true;
    ground2.position.setY(-12);
    ground2.__dirtyPosition = true;

    scene.add(ground);
    scene.add(ground2);

    scene.simulate();

    function random()
    {
        var result = '';

        while (result.length < 2)
        {
            result = (Math.round(Math.random()*1000).toString().slice(0,2))
        }

        return result;
    }

    function buildText(text)
    {
        var letters = text.split('').map(function(letter, index) {
            var material = new THREE.MeshLambertMaterial(
                {
                    color: ('#FF' + random() + random() )
                }
            );

            var physijsMaterial = Physijs.createMaterial(
                material,
                1.2, // high friction
                0.3 // low restitution
            );

            var letterGeometry = new THREE.TextGeometry(
                letter,
                {
                    size : 2,
                    height: 1
                }
            );

            var letterMesh = new Physijs.BoxMesh( letterGeometry, physijsMaterial );

            return letterMesh;
        });

        return letters;
    }

    function animate()
    {

        scene.simulate();

        renderer.render(scene, camera);

        requestAnimationFrame(animate);

    }

    animate();

}
<|endoftext|>


<commit_before>$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            // Prevent spam click and default submit behaviour
            $("#btnSubmit").attr("disabled", true);
            event.preventDefault();

            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "https://formspree.io/Stephen.Pino@utexas.edu",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
                success: function() {
                    // Enable button & show success message
                    $("#btnSubmit").attr("disabled", false);
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            });
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
    $('#success').html('');
});
<commit_msg>updating formspree<commit_after>$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            // Prevent spam click and default submit behaviour
            $("#btnSubmit").attr("disabled", true);
            event.preventDefault();

            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "https://formspree.io/Stephen.Pino@utexas.edu",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                dataType: 'json',
                cache: false,
                success: function() {
                    // Enable button & show success message
                    $("#btnSubmit").attr("disabled", false);
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            });
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
    $('#success').html('');
});
<|endoftext|>


<commit_before>// Contact Form Scripts

$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                method: 'POST',
                url: '//formspree.io/your@email.com',
                data: $('#contact-form').serialize(),
                datatype: 'json',
                success: function() {
                    // Success message
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            });
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});
<commit_msg>emailooof<commit_after>// Contact Form Scripts

$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                method: 'POST',
                url: '//formspree.io/itony215@gmail.com',
                data: $('#contact-form').serialize(),
                datatype: 'json',
                success: function() {
                    // Success message
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            });
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});
<|endoftext|>


<commit_before>(function() {
    var app = angular.module('myApp', []);
	var transport_list = (JSON.parse(localStorage.getItem('transport_DB')) === null) ? [] : JSON.parse(localStorage.getItem('transport_DB'));
    app.controller('LoginController', function() {
        console.log("Login Controller Initialized");
        this.detail = {};
        this.addLogin = function() {
            console.log("Inside Add Login Function");
            console.log(this.detail);
        };
    });
    app.controller('TransportDetails', function($scope) {
        console.log("Transport Details Initialized");
        this.detail = {};
		if(this.detail.box > 0){
			this.cartoon = true;
		}
        this.addTransDetails = function() {
			transport_list.push(this.detail);
			localStorage.setItem('transport_DB', JSON.stringify(transport_list));
			this.detail = {};
        };
		var content;
        this.updatePrice = function(item) {
			content = item;
            if (item != undefined) {
                this.detail.totalCost = item * this.detail.preCost;
            } else {
                this.detail.totalCost = 0;
            }

        }

		this.updatePerCost = function(item){
			 if (item != undefined) {
                this.detail.totalCost = item * content;
            } else {
                this.detail.totalCost = 0;
            }
		}

		this.disable = function(item, e){
			if(item >0  && e == 1){
				this.disable_cartoon = true;
			}else if(item > 0 && e == 2){
				this.disable_box = true;
			}
		}

    });

	 app.controller('TransportList', function() {
		 console.log("Transport List Initialized");
        this.trans_lists = transport_list;
        console.log(this.trans_list);
    });

	app.controller('ModuleSelect', function(){
		console.log("Module Select Initialized");
		this.selectMod = function(opt){
			$('#transport').removeClass('active1');
			$('#commission').removeClass('active1');
			if(opt == 1){
				$('#transport').addClass('active1');
			}else{
				$('#commission').addClass('active1');
			}
		}
		this.nextPage = function(){
			$('#transport').css('filter','grayscale(100%)');
			$('#commission').css('filter','grayscale(100%)');
			$('#page').css('filter','grayscale(100%)');
				$('#transport').css('cursor','default');
				$('#commission').css('cursor','default');
				document.getElementById('transport').style.pointerEvents = 'none';
				document.getElementById('commission').style.pointerEvents = 'none';
				$('#page_button').prop('disabled',true);
				$('#page1').fadeIn(1000).show();

		}

		this.editPage = function(){
			$('#page_edit').fadeIn(200).hide(500);
			$('#page_edit').css('filter','grayscale(0)');
			$('#page_button').fadeOut(200).show(500);
			$('#transport').css('border','none');
			$('#commission').css('border','none');
			$('#transport').css('filter','grayscale(0)');
			$('#commission').css('filter','grayscale(0)');
			$('#page').css('filter','grayscale(0)');
				$('#transport').css('cursor','pointer');
				$('#commission').css('cursor','pointer');
				document.getElementById('transport').style.pointerEvents = 'auto';
				document.getElementById('commission').style.pointerEvents = 'auto';
				$('#page_button').prop('disabled',false);
				$('#page1').css('display','none');
		}

	});
})();
<commit_msg>Update controller.js<commit_after>(function() {
    var app = angular.module('myApp', []);
	var transport_list = (JSON.parse(localStorage.getItem('transport_DB')) === null) ? [] : JSON.parse(localStorage.getItem('transport_DB'));
    app.controller('LoginController', function() {
        console.log("Login Controller Initialized");
        this.detail = {};
        this.addLogin = function() {
            console.log("Inside Add Login Function");
            console.log(this.detail);
        };
    });
    app.controller('TransportDetails', function($scope) {
        console.log("Transport Details Initialized");
        this.detail = {};
		if(this.detail.box > 0){
			this.cartoon = true;
		}
        this.addTransDetails = function() {
			transport_list.push(this.detail);
			localStorage.setItem('transport_DB', JSON.stringify(transport_list));
			this.detail = {};
        };
		var content;
        this.updatePrice = function(item) {
			content = item;
            if (item != undefined) {
                this.detail.totalCost = item * this.detail.preCost;
            } else {
                this.detail.totalCost = 0;
            }

        }

		this.updatePerCost = function(item){
			 if (item != undefined) {
                this.detail.totalCost = item * content;
            } else {
                this.detail.totalCost = 0;
            }
		}

		this.disable = function(item, e){
			if(item >0  && e == 1){
				this.disable_cartoon = true;
			}else if(item > 0 && e == 2){
				this.disable_box = true;
			}
		}

    });

	 app.controller('TransportList', function() {
		 console.log("Transport List Initialized");
        this.trans_lists = transport_list;
        console.log(this.trans_list);
    });

	app.controller('ModuleSelect', function(){
		console.log("Module Select Initialized");
		this.selectMod = function(opt){
			$('#transport').removeClass('active1');
			$('#commission').removeClass('active1');
			if(opt == 1){
				$('#transport').addClass('active1');
			}else{
				$('#commission').addClass('active1');
			}
		}
		this.nextPage = function(){
			$('#transport').css('filter','grayscale(100%)');
			$('#commission').css('filter','grayscale(100%)');
			$('#page').css('filter','grayscale(100%)');
				$('#transport').css('cursor','default');
				$('#commission').css('cursor','default');
				document.getElementById('transport').style.pointerEvents = 'none';
				document.getElementById('commission').style.pointerEvents = 'none';
				$('#page_button').prop('disabled',true);
				$('#page1').fadeIn(1000).show();

		}

		this.editPage = function(){
			$('#page_edit').css('filter','grayscale(0)');
			$('#transport').css('border','none');
			$('#commission').css('border','none');
			$('#transport').css('filter','grayscale(0)');
			$('#commission').css('filter','grayscale(0)');
			$('#page').css('filter','grayscale(0)');
				$('#transport').css('cursor','pointer');
				$('#commission').css('cursor','pointer');
				document.getElementById('transport').style.pointerEvents = 'auto';
				document.getElementById('commission').style.pointerEvents = 'auto';
				$('#page_button').prop('disabled',false);
				$('#page1').css('display','none');
		}

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


<commit_before>var grid;
var view;
var score;
var Controller = function(grid,view,score){
	this.grid = grid;
	this.view = view;
	this.score = score;
};

Controller.prototype.load = function(reload){

	if(reload){
		var remove = this.grid.getFramesNoEmpty();
		this.score.setValue(0);
		this.view.rePaint(remove,[]);
	}

	var number = Math.floor(Math.random() * 16);
	this.view.paint(this.grid.frames[number],'html','2',false);
	this.view.paint(this.grid.frames[number],'css','background-color','orange',false);
	this.grid.frames[number].val = '2';

	var number2 = Math.floor(Math.random() * 16);
	while(number2==number){
		number2 = Math.floor(Math.random() * 16);
	}

	this.view.paint(this.grid.frames[number2],'html','2',false);
	this.view.paint(this.grid.frames[number2],'css','background-color','orange',false);
	this.grid.frames[number2].val = '2';

	//Tests
	/*
	this.view.paint(this.grid.frames[0],'html','2048');
	this.view.paint(this.grid.frames[0],'css','background-color','orange');
	this.grid.frames[0].val = '4';

	this.view.paint(this.grid.frames[4],'html','2');
	this.view.paint(this.grid.frames[4],'css','background-color','orange');
	this.grid.frames[4].val = '2';

	this.view.paint(this.grid.frames[8],'html','2');
	this.view.paint(this.grid.frames[8],'css','background-color','orange');
	this.grid.frames[8].val = '2';

	this.view.paint(this.grid.frames[12],'html','8');
	this.view.paint(this.grid.frames[12],'css','background-color','orange');
	this.grid.frames[12].val = '8';

	this.view.paint(this.grid.frames[7],'html','8');
	this.view.paint(this.grid.frames[7],'css','background-color','orange');
	this.grid.frames[7].val = '8';

	this.view.paint(this.grid.frames[9],'html','2');
	this.view.paint(this.grid.frames[9],'css','background-color','orange');
	this.grid.frames[9].val = '2';

	this.view.paint(this.grid.frames[11],'html','8');
	this.view.paint(this.grid.frames[11],'css','background-color','orange');
	this.grid.frames[11].val = '8';

	this.view.paint(this.grid.frames[15],'html','4');
	this.view.paint(this.grid.frames[15],'css','background-color','orange');
	this.grid.frames[15].val = '4';
	*/
	grid = this.grid;
	view = this.view;
	score = this.score;
};

Controller.prototype.move = function(){

	var framesToMove = this.grid.getFramesNoEmpty();
	return framesToMove;
};

Controller.prototype.dirToMove = function(way,framesRemove){

	var dirs = [];
	var dirsaux = [];
	var line = [];
	var col = [];

	if(way=='right'){
		var count = 0;
		for(var i =0;i<this.grid.lines;i++){
		    line[i] = this.grid.getFramesLine(i);
			if(line[i].length>0){
				dirsaux[count] = toMoveFrames(line[i],'+','right',framesRemove);
				count++;
			}
		}

		for(var i=0;i<dirsaux.length;i++){
			dirs = dirs.concat(dirsaux[i]);
		}

	}else if(way=='left'){
		var count = 0;
		for(var i =0;i<this.grid.lines;i++){
		    line[i] = this.grid.getFramesLine(i);
			if(line[i].length>0){
				dirsaux[count] = toMoveFrames(line[i],'-','left',framesRemove);
				count++;
			}
		}

		for(var i=0;i<dirsaux.length;i++){
			dirs = dirs.concat(dirsaux[i]);
		}

	}else if(way=='up'){

		var count = 0;
		for(var i =0;i<this.grid.cols;i++){
		    col[i] = this.grid.getFramesCol(i);
			if(col[i].length>0){
				dirsaux[count] = toMoveFrames(col[i],'-','up',framesRemove);
				count++;
			}
		}

		for(var i=0;i<dirsaux.length;i++){
			dirs = dirs.concat(dirsaux[i]);
		}

	}else if(way=='down'){
		var count = 0;
		for(var i =0;i<this.grid.cols;i++){
		    col[i] = this.grid.getFramesCol(i);
			if(col[i].length>0){
				dirsaux[count] = toMoveFrames(col[i],'+','down',framesRemove);
				count++;
			}
		}

		for(var i=0;i<dirsaux.length;i++){
			dirs = dirs.concat(dirsaux[i]);
		}
	}

	console.log(dirs);
	return dirs;
};

Controller.prototype.addFrame = function(){

	var number = Math.floor(Math.random() * 16);
	while(!this.grid.frames[number].isEmpty()){
		number = Math.floor(Math.random() * 16);
	}
		this.view.paint(this.grid.frames[number],'html','2',true);
		this.view.paint(this.grid.frames[number],'css','background-color','orange',true);
		this.grid.frames[number].val = '2';
		console.log('Posicion nuevo incluido: ' + number);

};

var positionsOcupated = [];

/*Esta función deberia devolver las posiciones que se pintaran de la linea que le hemos pasado con su valor*/
var toMoveFrames = function(frames,dir,way,framesRemove){

	var dirs = [];
	for(var i=0;i<frames.length;i++){
		positionsOcupated[i] = false;
	}

	count = 0;
	if(dir=='+'){

		/* Si es mas,comenzaremos desde la ultima posicion del array de frames ya que los frames irán hacia allá */
		for(var i=frames.length-1;i>=0;i--){
			if(frames[i].isEmpty()){
				continue;
			}
			//console.log('Pos in array:' + i + '-> Frame:' + frames[i].val + ' ' + frames[i].pos);
			positionsOcupated[i] = true;

			if(i!=frames.length-1){
				/*Comprobamos los siguientes frames desde el que estamos hasta el ultimo para ver si estan vacios o no y asi
				poder colocarlo en un sitio u otro, esta funcion nos devolvera un object con la posicion a la que ira y el valor*/
				var o = movePositive(frames[i],i,way,frames.length-1,score);
				/*if(!o){
					o = new Object();
					o['pos'] = frames[i].pos;
					o['value'] = frames[i].val;
				}*/
				this.grid.frames[o.pos].val = o.value;

				if(frames[i].pos==o.pos && frames[i].val==o.value){
						var index = jQuery.inArray(frames[i],framesRemove);
						framesRemove.splice(index,1);
						continue;
				}

				var update = jQuery.inArray(o.pos,dirs);
				if(update>0){
					dirs.splice(update,1);
				}
				dirs.push(o);
			}else{

				var index = jQuery.inArray(frames[i],framesRemove);
				framesRemove.splice(index,1);
				/*
				var ob = new Object();
				ob['pos'] = frames[i].pos;
				ob['value'] = frames[i].val;

				dirs.push(ob);
				*/
			}
		}
	}else{

		/* Si es menos,comenzaremos desde la primera posicion del array de frames ya que los frames irán hacia allá */
		for(var i=0;i<frames.length;i++){
			if(frames[i].isEmpty()){
				continue;
			}
			positionsOcupated[i] = true;

			if(i!=0){
				/*Comprobamos los siguientes frames desde el que estamos hasta el ultimo para ver si estan vacios o no y asi
				poder colocarlo en un sitio u otro, esta funcion nos devolvera un object con la posicion a la que ira y el valor*/
				var o = moveNegative(frames[i],i,way,i,score);
				/*if(!o){
					o = new Object();
					o['pos'] = frames[i].pos;
					o['value'] = frames[i].val;
				}
				*/
				this.grid.frames[o.pos].val = o.value;

				if(frames[i].pos==o.pos && frames[i].val==o.value){
						var index = jQuery.inArray(frames[i],framesRemove);
						framesRemove.splice(index,1);
						continue;
				}

				//Compruebo que si ha sido introducido antes dicha posicion la elimino
				var update = jQuery.inArray(o.pos,dirs);
				if(update>0){
					dirs.splice(update,1);
				}
				dirs.push(o);
			}else{
				var index = jQuery.inArray(frames[i],framesRemove);
				framesRemove.splice(index,1);
				/*
				var ob = new Object();
				ob['pos'] = frames[i].pos;
				ob['value'] = frames[i].val;

				dirs.push(ob);
				*/
			}
		}
	}
	positionsOcupated = [];
	view.incrementScores(score.getValue());
	return dirs;

};

var movePositive = function(frame,pos,way,length,score){

	/*El frame se moverá hasta el frame mas allá que este vacío, dependiendo hacia donde se mueva y demás*/

	var o = new Object();
	for(var i = pos+1;i<=length;i++){
		if(i==length && positionsOcupated[i]==false){
			positionsOcupated[i] = true;
			positionsOcupated[pos] = false;
			if(way=='right'){
				o['pos'] = frame.line*frame.grid.cols + i;
			}else{
				o['pos'] = frame.col + frame.grid.lines*i;
			}
			o['value'] = frame.val;
			return o;
		}
		if(positionsOcupated[i]==false){
			continue;
		}else{
			if(way=='right'){
				var framePosInI = grid.getFrame(i,'line',frame.line);
			}else{
				var framePosInI = grid.getFrame(i,'col',frame.col);
			}
			var valPosInI = framePosInI.val;
			if(parseInt(frame.val)==valPosInI){
				positionsOcupated[pos] = false;
				o['pos'] = framePosInI.pos;
				o['value'] = String(parseInt(frame.val)*2);
				score.setValue(score.getValue() + parseInt(o.value));
				return o;
			}else{
				positionsOcupated[i-1] = true;
				if(pos!=i-1){
					positionsOcupated[pos] = false;
				}
				if(way=='right'){
					var frameFree = grid.getFrame(i-1,'line',frame.line);
					o['pos'] = frame.line*frame.grid.cols + (i-1);
				}else{
					var frameFree = grid.getFrame(i-1,'col',frame.col);
					o['pos'] = frame.col + frame.grid.lines*(i-1);
				}
				o['value'] = frame.val;
				return o;
			}
		}
	}
};

var moveNegative = function(frame,pos,way,length,score){

	var o = new Object();
	for(var i = pos - 1;i>=0;i--){
			if(i==0 && positionsOcupated[i]==false){
				positionsOcupated[i] = true;
				positionsOcupated[pos] = false;
				if(way=='left'){
					o['pos'] = frame.line*frame.grid.cols + i;
				}else if(way=='up'){
					o['pos'] = frame.col + frame.grid.lines*i;
				}
				o['value'] = frame.val;
				return o;
			}
			if(positionsOcupated[i]==false){
				continue;
			}else{
				if(way=='left'){
					var framePosInI = frame.grid.getFrame(i,'line',frame.line);
				}else{
					var framePosInI = frame.grid.getFrame(i,'col',frame.col);
				}
				var valPosInI = framePosInI.val;
				if(parseInt(frame.val)==valPosInI){
					positionsOcupated[pos] = false;
					o['pos'] = framePosInI.pos;
					o['value'] = String(parseInt(frame.val)*2);
					score.setValue(score.getValue() + parseInt(o.value));
					return o;
				}else{
					positionsOcupated[i+1] = true;
					if(pos!=i+1){
						positionsOcupated[pos] = false;
					}
					if(way=='left'){
						var frameFree = grid.getFrame(i+1,'line',frame.line);
						o['pos'] = frame.line*frame.grid.cols + (i+1);
					}else{
						var frameFree = grid.getFrame(i+1,'col',frame.col);
						o['pos'] = frame.col + frame.grid.lines*(i+1);
					}
					o['value'] = frame.val;
					return o;
				}
			}
		}

};<commit_msg>Delete comments<commit_after>var grid;
var view;
var score;
var Controller = function(grid,view,score){
	this.grid = grid;
	this.view = view;
	this.score = score;
};

Controller.prototype.load = function(reload){

	if(reload){
		var remove = this.grid.getFramesNoEmpty();
		this.score.setValue(0);
		this.view.rePaint(remove,[]);
	}

	var number = Math.floor(Math.random() * 16);
	this.view.paint(this.grid.frames[number],'html','2',false);
	this.view.paint(this.grid.frames[number],'css','background-color','orange',false);
	this.grid.frames[number].val = '2';

	var number2 = Math.floor(Math.random() * 16);
	while(number2==number){
		number2 = Math.floor(Math.random() * 16);
	}

	this.view.paint(this.grid.frames[number2],'html','2',false);
	this.view.paint(this.grid.frames[number2],'css','background-color','orange',false);
	this.grid.frames[number2].val = '2';

	//Tests
	/*
	this.view.paint(this.grid.frames[0],'html','2048');
	this.view.paint(this.grid.frames[0],'css','background-color','orange');
	this.grid.frames[0].val = '4';

	this.view.paint(this.grid.frames[4],'html','2');
	this.view.paint(this.grid.frames[4],'css','background-color','orange');
	this.grid.frames[4].val = '2';

	this.view.paint(this.grid.frames[8],'html','2');
	this.view.paint(this.grid.frames[8],'css','background-color','orange');
	this.grid.frames[8].val = '2';

	this.view.paint(this.grid.frames[12],'html','8');
	this.view.paint(this.grid.frames[12],'css','background-color','orange');
	this.grid.frames[12].val = '8';

	this.view.paint(this.grid.frames[7],'html','8');
	this.view.paint(this.grid.frames[7],'css','background-color','orange');
	this.grid.frames[7].val = '8';

	this.view.paint(this.grid.frames[9],'html','2');
	this.view.paint(this.grid.frames[9],'css','background-color','orange');
	this.grid.frames[9].val = '2';

	this.view.paint(this.grid.frames[11],'html','8');
	this.view.paint(this.grid.frames[11],'css','background-color','orange');
	this.grid.frames[11].val = '8';

	this.view.paint(this.grid.frames[15],'html','4');
	this.view.paint(this.grid.frames[15],'css','background-color','orange');
	this.grid.frames[15].val = '4';
	*/
	grid = this.grid;
	view = this.view;
	score = this.score;
};

Controller.prototype.move = function(){

	var framesToMove = this.grid.getFramesNoEmpty();
	return framesToMove;
};

Controller.prototype.dirToMove = function(way,framesRemove){

	var dirs = [];
	var dirsaux = [];
	var line = [];
	var col = [];

	if(way=='right'){
		var count = 0;
		for(var i =0;i<this.grid.lines;i++){
		    line[i] = this.grid.getFramesLine(i);
			if(line[i].length>0){
				dirsaux[count] = toMoveFrames(line[i],'+','right',framesRemove);
				count++;
			}
		}

		for(var i=0;i<dirsaux.length;i++){
			dirs = dirs.concat(dirsaux[i]);
		}

	}else if(way=='left'){
		var count = 0;
		for(var i =0;i<this.grid.lines;i++){
		    line[i] = this.grid.getFramesLine(i);
			if(line[i].length>0){
				dirsaux[count] = toMoveFrames(line[i],'-','left',framesRemove);
				count++;
			}
		}

		for(var i=0;i<dirsaux.length;i++){
			dirs = dirs.concat(dirsaux[i]);
		}

	}else if(way=='up'){

		var count = 0;
		for(var i =0;i<this.grid.cols;i++){
		    col[i] = this.grid.getFramesCol(i);
			if(col[i].length>0){
				dirsaux[count] = toMoveFrames(col[i],'-','up',framesRemove);
				count++;
			}
		}

		for(var i=0;i<dirsaux.length;i++){
			dirs = dirs.concat(dirsaux[i]);
		}

	}else if(way=='down'){
		var count = 0;
		for(var i =0;i<this.grid.cols;i++){
		    col[i] = this.grid.getFramesCol(i);
			if(col[i].length>0){
				dirsaux[count] = toMoveFrames(col[i],'+','down',framesRemove);
				count++;
			}
		}

		for(var i=0;i<dirsaux.length;i++){
			dirs = dirs.concat(dirsaux[i]);
		}
	}

	console.log(dirs);
	return dirs;
};

Controller.prototype.addFrame = function(){

	var number = Math.floor(Math.random() * 16);
	while(!this.grid.frames[number].isEmpty()){
		number = Math.floor(Math.random() * 16);
	}
		this.view.paint(this.grid.frames[number],'html','2',true);
		this.view.paint(this.grid.frames[number],'css','background-color','orange',true);
		this.grid.frames[number].val = '2';
		console.log('Posicion nuevo incluido: ' + number);

};

var positionsOcupated = [];

/*Esta función deberia devolver las posiciones que se pintaran de la linea que le hemos pasado con su valor*/
var toMoveFrames = function(frames,dir,way,framesRemove){

	var dirs = [];
	for(var i=0;i<frames.length;i++){
		positionsOcupated[i] = false;
	}

	count = 0;
	if(dir=='+'){

		/* Si es mas,comenzaremos desde la ultima posicion del array de frames ya que los frames irán hacia allá */
		for(var i=frames.length-1;i>=0;i--){
			if(frames[i].isEmpty()){
				continue;
			}
			//console.log('Pos in array:' + i + '-> Frame:' + frames[i].val + ' ' + frames[i].pos);
			positionsOcupated[i] = true;

			if(i!=frames.length-1){
				/*Comprobamos los siguientes frames desde el que estamos hasta el ultimo para ver si estan vacios o no y asi
				poder colocarlo en un sitio u otro, esta funcion nos devolvera un object con la posicion a la que ira y el valor*/
				var o = movePositive(frames[i],i,way,frames.length-1,score);
				this.grid.frames[o.pos].val = o.value;

				if(frames[i].pos==o.pos && frames[i].val==o.value){
						var index = jQuery.inArray(frames[i],framesRemove);
						framesRemove.splice(index,1);
						continue;
				}

				var update = jQuery.inArray(o.pos,dirs);
				if(update>0){
					dirs.splice(update,1);
				}
				dirs.push(o);
			}else{

				var index = jQuery.inArray(frames[i],framesRemove);
				framesRemove.splice(index,1);
			}
		}
	}else{

		/* Si es menos,comenzaremos desde la primera posicion del array de frames ya que los frames irán hacia allá */
		for(var i=0;i<frames.length;i++){
			if(frames[i].isEmpty()){
				continue;
			}
			positionsOcupated[i] = true;

			if(i!=0){
				/*Comprobamos los siguientes frames desde el que estamos hasta el ultimo para ver si estan vacios o no y asi
				poder colocarlo en un sitio u otro, esta funcion nos devolvera un object con la posicion a la que ira y el valor*/
				var o = moveNegative(frames[i],i,way,i,score);
				this.grid.frames[o.pos].val = o.value;

				if(frames[i].pos==o.pos && frames[i].val==o.value){
						var index = jQuery.inArray(frames[i],framesRemove);
						framesRemove.splice(index,1);
						continue;
				}

				//Compruebo que si ha sido introducido antes dicha posicion la elimino
				var update = jQuery.inArray(o.pos,dirs);
				if(update>0){
					dirs.splice(update,1);
				}
				dirs.push(o);
			}else{
				var index = jQuery.inArray(frames[i],framesRemove);
				framesRemove.splice(index,1);
			}
		}
	}
	positionsOcupated = [];
	view.incrementScores(score.getValue());
	return dirs;

};

var movePositive = function(frame,pos,way,length,score){

	/*El frame se moverá hasta el frame mas allá que este vacío, dependiendo hacia donde se mueva y demás*/

	var o = new Object();
	for(var i = pos+1;i<=length;i++){
		if(i==length && positionsOcupated[i]==false){
			positionsOcupated[i] = true;
			positionsOcupated[pos] = false;
			if(way=='right'){
				o['pos'] = frame.line*frame.grid.cols + i;
			}else{
				o['pos'] = frame.col + frame.grid.lines*i;
			}
			o['value'] = frame.val;
			return o;
		}
		if(positionsOcupated[i]==false){
			continue;
		}else{
			if(way=='right'){
				var framePosInI = grid.getFrame(i,'line',frame.line);
			}else{
				var framePosInI = grid.getFrame(i,'col',frame.col);
			}
			var valPosInI = framePosInI.val;
			if(parseInt(frame.val)==valPosInI){
				positionsOcupated[pos] = false;
				o['pos'] = framePosInI.pos;
				o['value'] = String(parseInt(frame.val)*2);
				score.setValue(score.getValue() + parseInt(o.value));
				return o;
			}else{
				positionsOcupated[i-1] = true;
				if(pos!=i-1){
					positionsOcupated[pos] = false;
				}
				if(way=='right'){
					var frameFree = grid.getFrame(i-1,'line',frame.line);
					o['pos'] = frame.line*frame.grid.cols + (i-1);
				}else{
					var frameFree = grid.getFrame(i-1,'col',frame.col);
					o['pos'] = frame.col + frame.grid.lines*(i-1);
				}
				o['value'] = frame.val;
				return o;
			}
		}
	}
};

var moveNegative = function(frame,pos,way,length,score){

	var o = new Object();
	for(var i = pos - 1;i>=0;i--){
			if(i==0 && positionsOcupated[i]==false){
				positionsOcupated[i] = true;
				positionsOcupated[pos] = false;
				if(way=='left'){
					o['pos'] = frame.line*frame.grid.cols + i;
				}else if(way=='up'){
					o['pos'] = frame.col + frame.grid.lines*i;
				}
				o['value'] = frame.val;
				return o;
			}
			if(positionsOcupated[i]==false){
				continue;
			}else{
				if(way=='left'){
					var framePosInI = frame.grid.getFrame(i,'line',frame.line);
				}else{
					var framePosInI = frame.grid.getFrame(i,'col',frame.col);
				}
				var valPosInI = framePosInI.val;
				if(parseInt(frame.val)==valPosInI){
					positionsOcupated[pos] = false;
					o['pos'] = framePosInI.pos;
					o['value'] = String(parseInt(frame.val)*2);
					score.setValue(score.getValue() + parseInt(o.value));
					return o;
				}else{
					positionsOcupated[i+1] = true;
					if(pos!=i+1){
						positionsOcupated[pos] = false;
					}
					if(way=='left'){
						var frameFree = grid.getFrame(i+1,'line',frame.line);
						o['pos'] = frame.line*frame.grid.cols + (i+1);
					}else{
						var frameFree = grid.getFrame(i+1,'col',frame.col);
						o['pos'] = frame.col + frame.grid.lines*(i+1);
					}
					o['value'] = frame.val;
					return o;
				}
			}
		}

};<|endoftext|>


<commit_before>
window.onload = function() {
	var d = new Date();
	var targetDate = Date.parse("Jun 16, "+d.getFullYear());
	var daysLeft = (targetDate-Date.parse(d))/(1000*60*60*24);
	document.getElementById('days').innerHTML = Math.floor(daysLeft);
	document.getElementById('countdown').style.opacity = 1;

	window.onscroll = function() {
		//console.log(document.body.scrollTop, window.innerHeight);
		if (document.body.scrollTop >
			document.getElementById('call').offsetTop - window.innerHeight + 150) {
			addClass('state-atcall')
		} else {
			removeClass('state-atcall')
		}
	}
	updateShareLinks();
};

function addClass(c) {
	if (document.body.className.indexOf(c) == -1) document.body.className += ' '+c;
}
function removeClass(c) {
	document.body.className = document.body.className.replace('/ ?'+c+' ?/', '');
}

function overprop(o, v) {
	o.parentNode.parentNode.className = (v === false) ? '' : 'state-'+o.className;
}

function nav(o, dir) {
	var prop = document.getElementById('prop');

	// if highlighted is now offscreen, highlight new
	var updateHighlight = function(dir) {
		var nn = prop.getElementsByTagName('li');
		var selClass = document.getElementById('propcontainer').className.replace('state-', '');
		//var selFoundInFirstFour = false;
		var selOffset = -1;
		for (var i=0; i<4; i++) {
			if (nn[i].className == selClass) selOffset=i //selFoundInFirstFour = true;
		}
		//if (!selFoundInFirstFour) {
		//	overprop(prop.getElementsByTagName('li')[which])
		//}
		overprop(prop.getElementsByTagName('li')[selOffset+dir])
	}

	if (dir > 0) {
		//prop.style.textIndent = '-220px';
		var n = prop.getElementsByTagName('li')[0];
		n.style.marginLeft = "-25%";
		setTimeout(function() {
			prop.appendChild(n);
			n.style.marginLeft = 0;
			updateHighlight(dir);
		}, 100);
	} else {
		var ns = prop.getElementsByTagName('li');
		var n = ns[0];
		n.style.marginLeft = "25%";
		setTimeout(function() {
			n.style.transition = 'none';
			n.style.marginLeft = 0;
			prop.insertBefore(ns[ns.length-1], ns[0]);
			setTimeout(function() {
				n.style.transition = 'margin-left .1s, margin-right .1s, opacity .2s';
			}, 110);
			updateHighlight(dir);
		}, 100);
	}

	return false;
}

var wanted = [''];
function want(o) {
	var w = o.parentNode.id;
	if (wanted.indexOf(w) == -1) wanted.push(w);
	document.body.className = wanted.join(' state-');
	updateShareLinks();
	return false;
}

function geo(d) {
	var validCountryCodes = ['AT', 'BG', 'CZ', 'FI', 'FR', 'DE', 'HU', 'IE', 'IT', 'LT', 'LU', 'MT', 'PL', 'PT', 'ES', 'SE', 'UK'];
	if (d && d.countryCode && validCountryCodes.indexOf(d.countryCode) > -1) {
		var iframeUrl = 'https://piphone.lqdn.fr/campaign/widget2/rapport_reda/horiz?country='+d.countryCode;
		document.getElementById('qdn').src = iframeUrl;
	}
}

var want2text = {
	'geoblocking': 'Overcome geoblocking',
	'borders': 'Extend your rights beyond borders',
	'contracts': 'Protect authors from unfair contracts',
	'quotes': 'Grant vloggers the right to quote',
	'link': 'Defend your right to link',
	'publicdomain': 'Safeguard the public domain',
	'libraries': 'Enable libraries to do their job online',
	'panorama': 'Ensure public space is for everyone',
	'education': 'Protect educational uses',
	'term': 'Enhance the availability of works',
	'drm': 'Reject digital locks',
	'filesharing': 'Legalise personal file sharing'
};

function updateShareLinks() {
	/*var icon;
	var metas = document.getElementsByTagName('meta');
	for (var i=0;i<metas.length;i++) { if (metas[i].getAttribute('property')=='og:image') icon=metas[i].getAttribute('content')) }*/

    var url = encodeURIComponent(document.location.href); // incl language?
    var title = encodeURIComponent(document.title);
    var text = encodeURIComponent('These urgently needed copyright reform plans are in danger:');
    var longText = '';
	var wanted2 = (!wanted || wanted[0]=='') ? ['', 'geoblocking', 'borders', 'contracts'] : wanted;
    for (var i=1;i<wanted2.length;i++) {
    	longText += want2text[wanted2[i]];
    	if (i > 0 && i < wanted2.length-1) longText += ' / ';
    }
    longText = encodeURIComponent(longText);
    var icon = encodeURIComponent('http://copywrongs.eu/img/copywrongs.png');

    var twitterAccount = 'senficon';
    var twitterAccountDesc = encodeURIComponent('MEP Julia Reda (European Pirate Party)');
    var twitterUrl = 'https://twitter.com/intent/tweet?original_referer='+url+'&related='+twitterAccount+'%3A'+twitterAccountDesc+'&text='+text+' '+longText+'&url='+url;

    var facebookAppID = 1420243108298307;
    var facebookUrl = 'https://www.facebook.com/dialog/feed?link='+url+'&picture='+icon+'&name='+title+'&caption='+text+'&description='+longText+'&e2e=%7B%7D&app_id='+facebookAppID+'&locale=en_US&sdk=joey&display=popup&next='+url;

    if (document.getElementById('twitter')) document.getElementById('twitter').href = twitterUrl;
    if (document.getElementById('facebook')) document.getElementById('facebook').href = facebookUrl;
}<commit_msg>FB share<commit_after>
window.onload = function() {
	var d = new Date();
	var targetDate = Date.parse("Jun 16, "+d.getFullYear());
	var daysLeft = (targetDate-Date.parse(d))/(1000*60*60*24);
	document.getElementById('days').innerHTML = Math.floor(daysLeft);
	document.getElementById('countdown').style.opacity = 1;

	window.onscroll = function() {
		//console.log(document.body.scrollTop, window.innerHeight);
		if (document.body.scrollTop >
			document.getElementById('call').offsetTop - window.innerHeight + 150) {
			addClass('state-atcall')
		} else {
			removeClass('state-atcall')
		}
	}
	updateShareLinks();
};

function addClass(c) {
	if (document.body.className.indexOf(c) == -1) document.body.className += ' '+c;
}
function removeClass(c) {
	document.body.className = document.body.className.replace('/ ?'+c+' ?/', '');
}

function overprop(o, v) {
	o.parentNode.parentNode.className = (v === false) ? '' : 'state-'+o.className;
}

function nav(o, dir) {
	var prop = document.getElementById('prop');

	// if highlighted is now offscreen, highlight new
	var updateHighlight = function(dir) {
		var nn = prop.getElementsByTagName('li');
		var selClass = document.getElementById('propcontainer').className.replace('state-', '');
		//var selFoundInFirstFour = false;
		var selOffset = -1;
		for (var i=0; i<4; i++) {
			if (nn[i].className == selClass) selOffset=i //selFoundInFirstFour = true;
		}
		//if (!selFoundInFirstFour) {
		//	overprop(prop.getElementsByTagName('li')[which])
		//}
		overprop(prop.getElementsByTagName('li')[selOffset+dir])
	}

	if (dir > 0) {
		//prop.style.textIndent = '-220px';
		var n = prop.getElementsByTagName('li')[0];
		n.style.marginLeft = "-25%";
		setTimeout(function() {
			prop.appendChild(n);
			n.style.marginLeft = 0;
			updateHighlight(dir);
		}, 100);
	} else {
		var ns = prop.getElementsByTagName('li');
		var n = ns[0];
		n.style.marginLeft = "25%";
		setTimeout(function() {
			n.style.transition = 'none';
			n.style.marginLeft = 0;
			prop.insertBefore(ns[ns.length-1], ns[0]);
			setTimeout(function() {
				n.style.transition = 'margin-left .1s, margin-right .1s, opacity .2s';
			}, 110);
			updateHighlight(dir);
		}, 100);
	}

	return false;
}

var wanted = [''];
function want(o) {
	var w = o.parentNode.id;
	if (wanted.indexOf(w) == -1) wanted.push(w);
	document.body.className = wanted.join(' state-');
	updateShareLinks();
	return false;
}

function geo(d) {
	var validCountryCodes = ['AT', 'BG', 'CZ', 'FI', 'FR', 'DE', 'HU', 'IE', 'IT', 'LT', 'LU', 'MT', 'PL', 'PT', 'ES', 'SE', 'UK'];
	if (d && d.countryCode && validCountryCodes.indexOf(d.countryCode) > -1) {
		var iframeUrl = 'https://piphone.lqdn.fr/campaign/widget2/rapport_reda/horiz?country='+d.countryCode;
		document.getElementById('qdn').src = iframeUrl;
	}
}

var want2text = {
	'geoblocking': 'Overcome geoblocking',
	'borders': 'Extend your rights beyond borders',
	'contracts': 'Protect authors from unfair contracts',
	'quotes': 'Grant vloggers the right to quote',
	'link': 'Defend your right to link',
	'publicdomain': 'Safeguard the public domain',
	'libraries': 'Enable libraries to do their job online',
	'panorama': 'Ensure public space is for everyone',
	'education': 'Protect educational uses',
	'term': 'Enhance the availability of works',
	'drm': 'Reject digital locks',
	'filesharing': 'Legalise personal file sharing'
};

function updateShareLinks() {
	/*var icon;
	var metas = document.getElementsByTagName('meta');
	for (var i=0;i<metas.length;i++) { if (metas[i].getAttribute('property')=='og:image') icon=metas[i].getAttribute('content')) }*/

    var url = encodeURIComponent(document.location.href); // incl language?
    var title = encodeURIComponent(document.title);
    var text = encodeURIComponent('These urgently needed copyright reform plans are in danger:');
    var longText = '';
	var wanted2 = (!wanted || wanted.length==1) ? ['', 'geoblocking', 'borders', 'contracts'] : wanted;
    for (var i=1;i<wanted2.length;i++) {
    	longText += want2text[wanted2[i]];
    	if (i > 0 && i < wanted2.length-1) longText += ' / ';
    }
    longText = encodeURIComponent(longText);
    var icon = encodeURIComponent('http://copywrongs.eu/img/copywrongs.png');

    var twitterAccount = 'senficon';
    var twitterAccountDesc = encodeURIComponent('MEP Julia Reda (European Pirate Party)');
    var twitterUrl = 'https://twitter.com/intent/tweet?original_referer='+url+'&related='+twitterAccount+'%3A'+twitterAccountDesc+'&text='+text+' '+longText+'&url='+url;

    var facebookAppID = 1420243108298307;
    var facebookUrl = 'https://www.facebook.com/dialog/feed?link='+url+'&picture='+icon+'&name='+title+'&caption='+text+'&description='+longText+'&e2e=%7B%7D&app_id='+facebookAppID+'&locale=en_US&sdk=joey&display=popup&next='+url;

    if (document.getElementById('twitter')) document.getElementById('twitter').href = twitterUrl;
    if (document.getElementById('facebook')) document.getElementById('facebook').href = facebookUrl;
}<|endoftext|>


<commit_before>define(function(){
	"use restrict";

	var createDropZone = function(){
		var dropzone = document.createElement("li");
		dropzone.style.height="50px";
		dropzone.style.zIndex="-1";
		dropzone.style.padding = "10px";
		var div = document.createElement("div");
		div.style.height="100%";
		div.style.border="dashed 3px gray";
		div.align ="center";
		var span = document.createElement("h2");
		span.textContent="Drop Here";
		span.onselectstart = function() { return false; };
		span.style.color="gray";
		div.appendChild(span);
		dropzone.appendChild(div);
		return dropzone;
	};
	var contextMenu;
	var createContextOption = function(text, onclick){
		var li = document.createElement("li");
		var span = document.createElement("span");
		li.appendChild(span);
		span.textContent=text;
		li.onclick= function(event){
			contextMenu.parentElement.remove(contextMenu);
			onclick.call(li, event);
		};
		return li;
	}

	var createContextMenu = function(board){
		var menu = document.createElement("ul");
		menu.style.board="solid 1px gray";
		menu.appendChild(createContextOption("Close", onBoardClose));
		menu.appendChild(createContextOption("Remove", onBoardRemove));
		return menu;
	};

	var onBoardRemove = function(){

	};

	var onBoardClose = function(){

	};

	var dropzone = createDropZone();
	var CopyOptions = function(defaultOption, option){
		var op = {};
		for(var key in defaultOption){
			op[key] = option[key] || defaultOption[key];
		}

		return op;
	};

	var findPageOffset =function (element){
		var top = element.offsetTop, left = element.offsetLeft, start = element;
		var current = element.parentElement;
		while (current !== null){
			left += current.offsetLeft;
			top += current.offsetTop;
			current = current.offsetParent;
		}
		return {top: top-window.scrollY, left: left-window.scrollX};
	};

	var start = false, li, dragObj = null, X, Y, original;
	var dragstartHander = function(event){
		start=true;
		dragObj = this;
		li = dragObj.element.parentElement;
		original = findPageOffset(li);
		li.parentElement.insertBefore(dropzone, li);
		li.style.position="fixed";
		var lis = document.getElementsByClassName("boardboardLi");
		for(var i=0; i<lis.length; i++){
			lis[i].style.zIndex ="20";
		}
		li.style.zIndex ="0";
		li.style.left = original.left+"px";
		li.style.top =  original.top+"px";
		dropzone.style.height = li.scrollHeight+"px";
		X = event.pageX, Y = event.pageY;

	};

	var dragHandler = function(event){
		if(start && dragObj){
			event.preventDefault();
			var xPage = event.pageX, yPage = event.pageY;//--
			var moveX = xPage - X + original.left;
			var moveY = yPage - Y +  original.top;
			li.style.left = moveX+"px";
			li.style.top =  moveY+"px";
		}
	};

	var dragendHandler = function(event){
		start=false, li = null;
		if(dragObj){
			var liElement = dragObj.element.parentElement;
			liElement.style.position="relative";
			liElement.style.left="0px";
			liElement.style.zIndex="20";
			liElement.style.top="0px";
			if(dropzone.parentElement){
				dropzone.parentElement.insertBefore(dragObj.element.parentElement, dropzone);
				dropzone.parentElement.removeChild(dropzone);
			}
			liElement.style.zIndex = null;
			dragObj = null;
		}

	};

	var mouseOverLi = function(event){
		if(start && dragObj){
			if(dropzone.parentElement && dropzone.parentElement!== this.parentElement){
				dropzone.parentElement.removeChild(dropzone);
			}
			this.parentElement.insertBefore(dropzone, this);
		}
	};
	document.onmousemove = dragHandler;
	document.onmouseup = dragendHandler;

	var createTitle = function(){
		var title = document.createElement("div");
		title.classList.add("boardTitle");
		title.style.backgroundColor = this.option.color;// || "#469CD6";
		title.style.height ="20px";
		title.style.padding = "3px 10px 3px 10px";
		var span = document.createElement("span");
		span.textContent=this.option.title;
		//span.style.color="white";
		span.style.fontWeight="bold";
		span.style.cursor="move";
		title.appendChild(span);
		/*var icon = createIcon();
		icon.style.width="15px";
		icon.style.display = "inline-block";
		icon.style.float = "right";
		icon.align="center";
		title.appendChild(icon);*/
		span.onmousedown = dragstartHander.bind(this);
		return title;
	};

	var createIcon = function(color){
		var icon = document.createElement("div");
		for(var i=0; i<3; i++){
			icon.appendChild(createRow("#469CD6"));
		}
		icon.align="center";
		icon.style.cursor="pointer";
		icon.onmouseover = function(){
			for(var i=0; i<icon.childElementCount; i++){
				icon.children[i].style.borderColor="#EFC433";
			}
		};
		icon.onmouseout =function(){
			for(var i=0; i<icon.childElementCount; i++){
				icon.children[i].style.borderColor="#469CD6";
			}
		}
		return icon;
	}

	var createRow = function(color){
		var a = document.createElement("div");
		a.style.border="solid";
		a.style.borderWidth="1px";
		a.style.borderColor=color;
		a.style.margin="2px";
		return a;
	}

	var createContent = function(option){
		var content = document.createElement("div");
		content.classList.add("boardContent");
		//content.style.padding = "3px 10px 3px 10px";
		var board = this;
		if(option.contentUrl){
			var request = new XMLHttpRequest();
			request.open("GET", location.href.split("index.html")[0]+option.contentUrl);
			request.send(null);
			request.onreadystatechange = function(){
				if (request.readyState === XMLHttpRequest.DONE) {
					if (request.status === 200) {
						content.innerHTML = request.responseText;
						board.element.parentElement.style.height = board.element.scrollHeight+"px";
					} else {
						throw new Error("Load HTML Error", "dash-board.js");
					}
				}
			};
		}else if(option.content){
			content.innerHTML=option.content;
		}
		content.style.minHeight = (this.option.minHeight-20)+"px";
		return content;
	}

	var findOffset =function (element){
		var top = 0, left = 0, start = element;
		var actualTop = element.offsetTop;
		var current = element.parentElement;
		while (current !== null && current!=this.option.element){
			left += current.offsetLeft;
			top += current.offsetTop;
			current = current.offsetParent;
		}
		return {top: top, left: left};
	};

	var boardDefalt ={
		element: document.createElement("div"),
		title: '',
		minHeight: 50,
		column: undefined,
		contentUrl:undefined,
		content: undefined,
		removeble: true,
		theme: undefined,
		onLoad: function(){}
	};

	var Board = function(options){
		var option = CopyOptions(boardDefalt, options);
		Object.defineProperties(this, {
			'option':{
				get: function(){return option;}
			},'element':{
				get: function(){return this.option.element;}
			}, 'column':{
				get: function(){return option.column;},
				set: function(val){!isNaN(val) && (option.column = val);}
			}
		});
		var init = function(){
			var div = document.createElement("div");
			div.classList.add("boardboard");
			div.style.minHeight = this.option.minHeight+"px";
			div.style.width = "100%";
			var title = createTitle.apply(this);
			div.appendChild(title);
			div.appendChild(createContent.call(this, this.option));
			return div;
		};
		this.option.element = init.apply(this);
	};

	var boardDefaultOptions = {
		element: document.body,
		column: 2,
		onLoad: function(){},
		theme: 'defaultTheme'
	};
	var createUl = function(parent, totalColumn, i){
		var ul = document.createElement("ul");
		ul.style.position = "absolute";
		ul.style.margin = "0px";
		ul.style.listStyle="none";
		ul.style.padding="0px";

		ul.style.display = "inline-block";
		parent.appendChild(ul);
		ul.style.width = parent.scrollWidth/totalColumn +"px";
		ul.style.left = parent.scrollWidth/totalColumn * i +"px";
		var li = standardLi();
		li.style.height="20px";
		ul.appendChild(li);
		return ul;
	};

	var findLongestUl = function(columns){
		if(!columns) throw new Error("UL Columns not found!", "dash-board.js");
		var index=0;
		for(var i=1; i<columns.length; i++){
			if(columns[i].scrollHeight > columns[index].scrollHeight){
				index=i;
			}
		}
		return index;
	}

	var DashBoard = function(options){
		var dashBoard = this, columns=[];
		var boards = [];
		var option = CopyOptions(boardDefaultOptions, options);
		if(typeof option.element === 'string'){
			option.element = document.getElementById(option.element) || document.body;
		}
		if(option.column <0) option.column=2;
		option.element.style.position="relative";
		option.element.style.zIndex="999";
		option.element.classList.add("dashBoard");

		Object.defineProperties(this, {
			'boards':{
				get: function(){return boards;}
			},'option':{
				get: function(){return option;}
			},'columns':{
				get: function(){return columns;}
			},'right':{
				get: function(){return right;}
			}
		});

		for(var i=0; i<option.column; i++){
			columns.push(createUl.call(this, this.option.element, this.option.column, i));
		}
		//option.onNewBoard.call(this);
		var i = findLongestUl(columns);
		option.element.style.height = columns[i].scrollHeight + "px";
		option.element.style.width =  option.element.scrollWidth + "px";
	};

	var standardLi = function(){
		var li = document.createElement("li");
		li.style.position = "relative";
		li.onmouseover=mouseOverLi.bind(li);
		li.classList.add("boardboardLi");
		li.style.padding = "10px";
		return li;
	};

	var findShortestUl = function(columns){
		if(!columns) throw new Error("UL Columns not found!", "dash-board.js");
		var index=0;
		for(var i=1; i<columns.length; i++){
			if(columns[i].scrollHeight < columns[index].scrollHeight){
				index=i;
			}
		}
		return index;
	}

	var createLi = function(board, columns){
		var li = standardLi(), ul;
		if(isNaN(board.column)){
			board.column = findShortestUl(columns);
		}else{
			board.column>=1 && board.column--;
		}
		ul = columns[board.column];
		ul.insertBefore(li, ul.lastChild);
		var offset = findOffset.call(this, li);
		li.appendChild(board.element);
		li.style.height = board.element.scrollHeight+"px";
		li.style.width = board.element.scrollWidth+"px";
		li.classList.add(board.option.theme || this.option.theme);
		return li;
	};

	DashBoard.prototype={
		addBoard : function(options){
			var board = new Board(options);
			var column = board.column;
			createLi.call(this, board, this.columns);
			this.boards.push(board);
			var i = findLongestUl(this.columns);
			this.option.element.style.height =  this.columns[i].scrollHeight + "px";

			board.parent = this;
			board.option.onLoad.call(this);
			return this;
		},
		getBoard : function(index){
			if(isNaN(index)){
				for(var i in this.boards){
					if(this.boards[i].name === index){
						return this.boards[i];
					}
				}
			}else{
				return this.boards[index];
			}
			throw new Error('Index Not Found.','DashBoard');
		}
	}

	return DashBoard;
});<commit_msg>observer<commit_after>define(function(){
	"use restrict";

	var MutationObserver = window.MutationObserver
	|| window.WebKitMutationObserver
	|| window.MozMutationObserver;

	var createDropZone = function(){
		var dropzone = document.createElement("li");
		dropzone.style.height="50px";
		dropzone.style.zIndex="-1";
		dropzone.style.padding = "10px";
		var div = document.createElement("div");
		div.style.height="100%";
		div.style.border="dashed 3px gray";
		div.align ="center";
		var span = document.createElement("h2");
		span.textContent="Drop Here";
		span.onselectstart = function() { return false; };
		span.style.color="gray";
		div.appendChild(span);
		dropzone.appendChild(div);
		return dropzone;
	};
	var contextMenu;
	var createContextOption = function(text, onclick){
		var li = document.createElement("li");
		var span = document.createElement("span");
		li.appendChild(span);
		span.textContent=text;
		li.onclick= function(event){
			contextMenu.parentElement.remove(contextMenu);
			onclick.call(li, event);
		};
		return li;
	}

	var createContextMenu = function(board){
		var menu = document.createElement("ul");
		menu.style.board="solid 1px gray";
		menu.appendChild(createContextOption("Close", onBoardClose));
		menu.appendChild(createContextOption("Remove", onBoardRemove));
		return menu;
	};

	var onBoardRemove = function(){

	};

	var onBoardClose = function(){

	};

	var dropzone = createDropZone();
	var CopyOptions = function(defaultOption, option){
		var op = {};
		for(var key in defaultOption){
			op[key] = option[key] || defaultOption[key];
		}

		return op;
	};

	var findPageOffset =function (element){
		var top = element.offsetTop, left = element.offsetLeft, start = element;
		var current = element.parentElement;
		while (current !== null){
			left += current.offsetLeft;
			top += current.offsetTop;
			current = current.offsetParent;
		}
		return {top: top-window.scrollY, left: left-window.scrollX};
	};

	var start = false, li, dragObj = null, X, Y, original;
	var dragstartHander = function(event){
		start=true;
		dragObj = this;
		li = dragObj.element.parentElement;
		original = findPageOffset(li);
		li.parentElement.insertBefore(dropzone, li);
		li.style.position="fixed";
		var lis = document.getElementsByClassName("boardboardLi");
		for(var i=0; i<lis.length; i++){
			lis[i].style.zIndex ="20";
		}
		li.style.zIndex ="0";
		li.style.left = original.left+"px";
		li.style.top =  original.top+"px";
		dropzone.style.height = li.scrollHeight+"px";
		X = event.pageX, Y = event.pageY;

	};

	var dragHandler = function(event){
		if(start && dragObj){
			event.preventDefault();
			var xPage = event.pageX, yPage = event.pageY;//--
			var moveX = xPage - X + original.left;
			var moveY = yPage - Y +  original.top;
			li.style.left = moveX+"px";
			li.style.top =  moveY+"px";
		}
	};

	var dragendHandler = function(event){
		start=false, li = null;
		if(dragObj){
			var liElement = dragObj.element.parentElement;
			liElement.style.position="relative";
			liElement.style.left="0px";
			liElement.style.zIndex="20";
			liElement.style.top="0px";
			if(dropzone.parentElement){
				dropzone.parentElement.insertBefore(dragObj.element.parentElement, dropzone);
				dropzone.parentElement.removeChild(dropzone);
			}
			liElement.style.zIndex = null;
			dragObj = null;
		}

	};

	var mouseOverLi = function(event){
		if(start && dragObj){
			if(dropzone.parentElement && dropzone.parentElement!== this.parentElement){
				dropzone.parentElement.removeChild(dropzone);
			}
			this.parentElement.insertBefore(dropzone, this);
		}
	};
	document.onmousemove = dragHandler;
	document.onmouseup = dragendHandler;

	var createTitle = function(){
		var title = document.createElement("div");
		title.classList.add("boardTitle");
		title.style.backgroundColor = this.option.color;// || "#469CD6";
		title.style.height ="20px";
		title.style.padding = "3px 10px 3px 10px";
		var span = document.createElement("span");
		span.textContent=this.option.title;
		//span.style.color="white";
		span.style.fontWeight="bold";
		span.style.cursor="move";
		title.appendChild(span);
		/*var icon = createIcon();
		icon.style.width="15px";
		icon.style.display = "inline-block";
		icon.style.float = "right";
		icon.align="center";
		title.appendChild(icon);*/
		span.onmousedown = dragstartHander.bind(this);
		return title;
	};

	var createIcon = function(color){
		var icon = document.createElement("div");
		for(var i=0; i<3; i++){
			icon.appendChild(createRow("#469CD6"));
		}
		icon.align="center";
		icon.style.cursor="pointer";
		icon.onmouseover = function(){
			for(var i=0; i<icon.childElementCount; i++){
				icon.children[i].style.borderColor="#EFC433";
			}
		};
		icon.onmouseout =function(){
			for(var i=0; i<icon.childElementCount; i++){
				icon.children[i].style.borderColor="#469CD6";
			}
		}
		return icon;
	}

	var createRow = function(color){
		var a = document.createElement("div");
		a.style.border="solid";
		a.style.borderWidth="1px";
		a.style.borderColor=color;
		a.style.margin="2px";
		return a;
	}

	var createContent = function(option){
		var content = document.createElement("div");
		content.classList.add("boardContent");
		//content.style.padding = "3px 10px 3px 10px";
		var board = this;
		if(option.contentUrl){
			var request = new XMLHttpRequest();
			request.open("GET", location.href.split("index.html")[0]+option.contentUrl);
			request.send(null);
			request.onreadystatechange = function(){
				if (request.readyState === XMLHttpRequest.DONE) {
					if (request.status === 200) {
						content.innerHTML = request.responseText;
						board.element.parentElement.style.height = board.element.scrollHeight+"px";
					} else {
						throw new Error("Load HTML Error", "dash-board.js");
					}
				}
			};
		}else if(option.content){
			content.innerHTML=option.content;
		}
		content.style.minHeight = (this.option.minHeight-20)+"px";
		return content;
	}

	var findOffset =function (element){
		var top = 0, left = 0, start = element;
		var actualTop = element.offsetTop;
		var current = element.parentElement;
		while (current !== null && current!=this.option.element){
			left += current.offsetLeft;
			top += current.offsetTop;
			current = current.offsetParent;
		}
		return {top: top, left: left};
	};

	var boardDefalt ={
		element: document.createElement("div"),
		title: '',
		minHeight: 50,
		column: undefined,
		contentUrl:undefined,
		content: undefined,
		removeble: true,
		theme: undefined,
		onLoad: function(){}
	};

	var Board = function(options){
		var option = CopyOptions(boardDefalt, options);
		Object.defineProperties(this, {
			'option':{
				get: function(){return option;}
			},'element':{
				get: function(){return this.option.element;}
			}, 'column':{
				get: function(){return option.column;},
				set: function(val){!isNaN(val) && (option.column = val);}
			}
		});
		var init = function(){
			var div = document.createElement("div");
			div.classList.add("boardboard");
			div.style.minHeight = this.option.minHeight+"px";
			div.style.width = "100%";
			var title = createTitle.apply(this);
			div.appendChild(title);
			div.appendChild(createContent.call(this, this.option));
			return div;
		};
		this.option.element = init.apply(this);
	};

	var boardDefaultOptions = {
		element: document.body,
		column: 2,
		onLoad: function(){},
		theme: 'defaultTheme'
	};
	var createUl = function(parent, totalColumn, i){
		var ul = document.createElement("ul");
		ul.style.position = "absolute";
		ul.style.margin = "0px";
		ul.style.listStyle="none";
		ul.style.padding="0px";

		ul.style.display = "inline-block";
		parent.appendChild(ul);
		ul.style.width = parent.scrollWidth/totalColumn +"px";
		ul.style.left = parent.scrollWidth/totalColumn * i +"px";
		var li = standardLi();
		li.style.height="20px";
		ul.appendChild(li);
		return ul;
	};

	var findLongestUl = function(columns){
		if(!columns) throw new Error("UL Columns not found!", "dash-board.js");
		var index=0;
		for(var i=1; i<columns.length; i++){
			if(columns[i].scrollHeight > columns[index].scrollHeight){
				index=i;
			}
		}
		return index;
	}

	var DashBoard = function(options){
		var dashBoard = this, columns=[];
		var boards = [];
		var option = CopyOptions(boardDefaultOptions, options);
		if(typeof option.element === 'string'){
			option.element = document.getElementById(option.element) || document.body;
		}
		if(option.column <0) option.column=2;
		option.element.style.position="relative";
		option.element.style.zIndex="999";
		option.element.classList.add("dashBoard");

		Object.defineProperties(this, {
			'boards':{
				get: function(){return boards;}
			},'option':{
				get: function(){return option;}
			},'columns':{
				get: function(){return columns;}
			},'right':{
				get: function(){return right;}
			}
		});

		for(var i=0; i<option.column; i++){
			columns.push(createUl.call(this, this.option.element, this.option.column, i));
		}
		//option.onNewBoard.call(this);
		var i = findLongestUl(columns);
		option.element.style.height = columns[i].scrollHeight + "px";
		option.element.style.width =  option.element.scrollWidth + "px";
	};

	var standardLi = function(){
		var li = document.createElement("li");
		li.style.position = "relative";
		li.onmouseover=mouseOverLi.bind(li);
		li.classList.add("boardboardLi");
		li.style.padding = "10px";
		return li;
	};

	var findShortestUl = function(columns){
		if(!columns) throw new Error("UL Columns not found!", "dash-board.js");
		var index=0;
		for(var i=1; i<columns.length; i++){
			if(columns[i].scrollHeight < columns[index].scrollHeight){
				index=i;
			}
		}
		return index;
	};

	var panelChangeReactor = function(mutation, board){
		board.element.parentElement.style.height = board.element.scrollHeight+"px";
	}

	var createLi = function(board, columns){
		var li = standardLi(), ul;
		if(isNaN(board.column)){
			board.column = findShortestUl(columns);
		}else{
			board.column>=1 && board.column--;
		}
		ul = columns[board.column];
		ul.insertBefore(li, ul.lastChild);
		var offset = findOffset.call(this, li);
		li.appendChild(board.element);
		li.style.height = board.element.scrollHeight+"px";
		li.style.width = board.element.scrollWidth+"px";
		li.classList.add(board.option.theme || this.option.theme);

		var observer = new MutationObserver(function(mutation){
			panelChangeReactor.call(this, mutation, board);
		});
		var observeoptions = {
		  'childList': true,
		  'subtree': true
		} ;
		observer.observe(li, observeoptions);

		return li;
	};

	DashBoard.prototype={
		addBoard : function(options){
			var board = new Board(options);
			var column = board.column;
			createLi.call(this, board, this.columns);
			this.boards.push(board);
			var i = findLongestUl(this.columns);
			this.option.element.style.height =  this.columns[i].scrollHeight + "px";

			board.parent = this;
			board.option.onLoad.call(this);
			return this;
		},
		getBoard : function(index){
			if(isNaN(index)){
				for(var i in this.boards){
					if(this.boards[i].name === index){
						return this.boards[i];
					}
				}
			}else{
				return this.boards[index];
			}
			throw new Error('Index Not Found.','DashBoard');
		}
	}

	return DashBoard;
});<|endoftext|>


<commit_before>/*
* jQuery UI Depends:
*        jquery.ui.autocomplete.js
*        jquery.ui.button.js
*        jquery.ui.core.js
*        jquery.ui.widget.js
*        jquery.ui.position.js
*        jquery.ui.menu.js
*/

nb.define('select', {
    events: {
        'init': 'onInit'
        //'open' { event, ui}
        //'close' { event, ui}
    },

    onInit: function () {
        var that = this;
        nb.init(that);
        that.data = that.data();

        // find elements and values
        var c = that.children();
        that.button = c[0];
        that.$fallback = $(that.node).find('.nb-select__fallback');
        that.$selected = that.$fallback.children(':selected');

        that.value = that.$selected.val() ? that.$selected.text() : '';

        this.button.setText(that.value)

        // preparing control depending on configuration and content
        that.controlPrepare();
    },

    /**
     * preparing control depending on configuration and content
     */
    controlPrepare: function () {
        var that = this;
        // preparing position parameters for popup from direction data
        var position = {};
        position.collision = 'flip';

        if (that.data.within) {
            position.within = that.data.within;
        }

        if (that.data.direction == 'top') {
            position.my = "left bottom";
            position.at = "left top";

        } else {
            position.my = "left top";
            position.at = "left bottom";
        }

        // select JUI control init
        $(that.node).autocomplete({
            delay: 0,
            minLength: 0,
            autoFocus: false,
            position: position,
            appendTo: that.node,
            source: function (request, response) {
                response(that.$fallback.children('option').map(function () {
                    return {
                        label: $(this).text(),
                        value: $(this).val(),
                        option: this
                    };
                }));
            },
            select: function (event, ui) {
                ui.item.option.selected = true;

                that.$jUI._trigger('selected', event, {
                    item: ui.item.option
                });
            },
            // delegate handler on 'outer' click on open
            open: function (event, ui) {
                that.$jUI._on(that.$jUI.document, {
                    // on 'outer' mousedown close control
                    mousedown: function (e) {
                        if (e.which == 1 && !$.contains(that.$jUI.element.get(0), e.target)) {
                            this.close();
                        }
                    }
                })
                that.trigger('open', {
                    event: event,
                    ui: ui
                });
            },

            close: function (event, ui) {
                that.$jUI._off(that.$jUI.document, 'mousedown');
                that.trigger('close', {
                    event: event,
                    ui: ui
                });
            }
        }).addClass('ui-widget ui-widget-content');

        that.$jUI = $(that.node).data('uiAutocomplete')

        // redefine one menu item rendering method, fires every time, then popup opening
        that.$jUI._renderItem = function (ul, item) {
            var $itemNode = $('

');

            if (item.option.selected) {
                $itemNode.addClass('nb-select__item_selected_yes');
            }

            $itemNode.data('ui-autocomplete-item', item);
            $itemNode.append('' + item.label + '');
            $itemNode.appendTo(ul);

            return $itemNode;
        };

        // redefine valueMethod, extend with button text changing and fallback select value changing
        // if value not provided, return current value of fallback select
        that.$jUI.valueMethod = function (value) {
            if (value) {
                var text = that.$fallback.children('[value="' + value + '"]').text()
                that.setValue({
                    value: value,
                    text: text
                });
            }
            return that.$selected.val();
        };

        // add click event for button
        $(that.button.node).click(function (evt) {
            // иначе сабмитит форму при клике
            evt.preventDefault();
            // close if already visible
            if ($(that.node).autocomplete('widget').css('display') == 'block') {
                $(that.node).autocomplete('close');
                return;
            }
            // pass empty string as value to search for, displaying all results
            $(that.node).autocomplete('search', '');
            $(that.node).focus();
        });
    },

    /**
     * Changes a value of control, text on the button and select value it the fallback
     *
     * @param name — event id that caused the change
     * @param params — {
         *     text: '..'
         *     value: '..'
         * }
     * @fires 'nb-select_changed'
     */
    setValue: function (params) {
        this.value = params.value;
        this.text = params.text;
        this.$selected.removeAttr('selected');

        this.$selected = this.$fallback.children('[value="' + this.value + '"]').attr('selected', 'selected');
        this.button.setText(this.text);

        this.trigger('nb-select_changed');

        this.$fallback.val(params.value);
        return this
    },

    /**
     * Returns state of the select
     *
     * @return {Object} -
         * {
         *     value: '..'
         *     text: '..'
         * }
     */
    getState: function () {
        return {
            value: this.value,
            text: this.text
        }
    }

});

<commit_msg>change setValue -> setState<commit_after>/*
* jQuery UI Depends:
*        jquery.ui.autocomplete.js
*        jquery.ui.button.js
*        jquery.ui.core.js
*        jquery.ui.widget.js
*        jquery.ui.position.js
*        jquery.ui.menu.js
*/

nb.define('select', {
    events: {
        'init': 'onInit'
        //'open' { event, ui}
        //'close' { event, ui}
    },

    onInit: function () {
        var that = this;
        nb.init(that);
        that.data = that.data();

        // find elements and values
        var c = that.children();
        that.button = c[0];
        that.$fallback = $(that.node).find('.nb-select__fallback');
        that.$selected = that.$fallback.children(':selected');

        that.value = that.$selected.val() ? that.$selected.text() : '';

        this.button.setText(that.value)

        // preparing control depending on configuration and content
        that.controlPrepare();
    },

    /**
     * preparing control depending on configuration and content
     */
    controlPrepare: function () {
        var that = this;
        // preparing position parameters for popup from direction data
        var position = {};
        position.collision = 'flip';

        if (that.data.within) {
            position.within = that.data.within;
        }

        if (that.data.direction == 'top') {
            position.my = "left bottom";
            position.at = "left top";

        } else {
            position.my = "left top";
            position.at = "left bottom";
        }

        // select JUI control init
        $(that.node).autocomplete({
            delay: 0,
            minLength: 0,
            autoFocus: false,
            position: position,
            appendTo: that.node,
            source: function (request, response) {
                response(that.$fallback.children('option').map(function () {
                    return {
                        label: $(this).text(),
                        value: $(this).val(),
                        option: this
                    };
                }));
            },
            select: function (event, ui) {
                ui.item.option.selected = true;

                that.$jUI._trigger('selected', event, {
                    item: ui.item.option
                });
            },
            // delegate handler on 'outer' click on open
            open: function (event, ui) {
                that.$jUI._on(that.$jUI.document, {
                    // on 'outer' mousedown close control
                    mousedown: function (e) {
                        if (e.which == 1 && !$.contains(that.$jUI.element.get(0), e.target)) {
                            this.close();
                        }
                    }
                })
                that.trigger('open', {
                    event: event,
                    ui: ui
                });
            },

            close: function (event, ui) {
                that.$jUI._off(that.$jUI.document, 'mousedown');
                that.trigger('close', {
                    event: event,
                    ui: ui
                });
            }
        }).addClass('ui-widget ui-widget-content');

        that.$jUI = $(that.node).data('uiAutocomplete')

        // redefine one menu item rendering method, fires every time, then popup opening
        that.$jUI._renderItem = function (ul, item) {
            var $itemNode = $('

');

            if (item.option.selected) {
                $itemNode.addClass('nb-select__item_selected_yes');
            }

            $itemNode.data('ui-autocomplete-item', item);
            $itemNode.append('' + item.label + '');
            $itemNode.appendTo(ul);

            return $itemNode;
        };

        // redefine valueMethod, extend with button text changing and fallback select value changing
        // if value not provided, return current value of fallback select
        that.$jUI.valueMethod = function (value) {
            if (value) {
                var text = that.$fallback.children('[value="' + value + '"]').text()
                that.setState({
                    value: value,
                    text: text
                });
            }
            return that.$selected.val();
        };

        // add click event for button
        $(that.button.node).click(function (evt) {
            // иначе сабмитит форму при клике
            evt.preventDefault();
            // close if already visible
            if ($(that.node).autocomplete('widget').css('display') == 'block') {
                $(that.node).autocomplete('close');
                return;
            }
            // pass empty string as value to search for, displaying all results
            $(that.node).autocomplete('search', '');
            $(that.node).focus();
        });
    },

    /**
     * Changes a value of control, text on the button and select value it the fallback
     *
     * @param name — event id that caused the change
     * @param params — {
         *     text: '..'
         *     value: '..'
         * }
     * @fires 'nb-select_changed'
     */
    setState: function (params) {
        this.value = params.value;
        this.text = params.text;
        this.$selected.removeAttr('selected');

        this.$selected = this.$fallback.children('[value="' + this.value + '"]').attr('selected', 'selected');
        this.button.setText(this.text);

        this.trigger('nb-select_changed');

        this.$fallback.val(params.value);
        return this
    },

    /**
     * Returns state of the select
     *
     * @return {Object} -
         * {
         *     value: '..'
         *     text: '..'
         * }
     */
    getState: function () {
        return {
            value: this.value,
            text: this.text
        }
    }

});

<|endoftext|>


<commit_before>// Copyright 2013-2015, University of Colorado Boulder

/**
 * Configuration file for development and production deployments.
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

require.config( {
  deps: [ 'dot-main' ],

  paths: {

    // plugins
    image: '../../chipper/js/requirejs-plugins/image',
    ifphetio: '../../chipper/js/requirejs-plugins/ifphetio',

    // third-party libs
    text: '../../sherpa/lib/text-2.0.12',
    DOT: '../../dot/js',
    PHET_CORE: '../../phet-core/js',
    AXON: '../../axon/js',

    // Needs to be compatible in the sim, and also with scenery unit tests.
    BRAND: '../../brand/' + (window.phet && phet.chipper && phet.chipper.brand ? phet.chipper.brand : 'adapted-from-phet') + '/js',

    TANDEM: '../../tandem/js',
    REPOSITORY: '..'
  },

  // optional cache buster to make browser refresh load all included scripts, can be disabled with ?cacheBuster=false
  urlArgs: Date.now()
} );
<commit_msg>remove BRAND from config files, https://github.com/phetsims/phet-io/issues/1106 https://github.com/phetsims/scenery/issues/626<commit_after>// Copyright 2013-2015, University of Colorado Boulder

/**
 * Configuration file for development and production deployments.
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

require.config( {
  deps: [ 'dot-main' ],

  paths: {

    // plugins
    image: '../../chipper/js/requirejs-plugins/image',
    ifphetio: '../../chipper/js/requirejs-plugins/ifphetio',

    // third-party libs
    text: '../../sherpa/lib/text-2.0.12',
    DOT: '../../dot/js',
    PHET_CORE: '../../phet-core/js',
    AXON: '../../axon/js',

    TANDEM: '../../tandem/js',
    REPOSITORY: '..'
  },

  // optional cache buster to make browser refresh load all included scripts, can be disabled with ?cacheBuster=false
  urlArgs: Date.now()
} );
<|endoftext|>


<commit_before>/*
 * Markdown Extra Syntax
 * ---------------------
 *
 * - Fenced Code with Highlight
 *
 *   ```javascript
 *   var foo = "bar";
 *   ```
 *
 * - Highlight Code with Inserted Code
 *
 *   ````javascript
 *   var foo = "bar";
 *   ````
 *
 * - Just insert code
 *
 *   `````javascript
 *   var foo = "bar";
 *   `````
 * */

var rFenceCode = /(\s*)(`{3,}|~{3,}) *(.*) *\n([\s\S]+?)\s*(\2)(\n+|$)/g;
var rLang = /([^\s]+)\s*(.+)?\s*(.+)?/;

var langMap = {
  'css': 'css',
  'htm': 'html',
  'html': 'html',
  'javascript': 'javascript',
  'js': 'javascript',
  'json': 'javascript'
};

var injectFn = {
  'javascript': function (code) {
    return '';
  },
  'css': function (code) {
    return '';
  },
  'html': function (code) {
    return '
' + code + '
';
  }
};

function getLanguage(lang) {
  if (lang && langMap[lang]) {
    lang = langMap[lang];
  }
  return lang;
}

function escapeCode(lang, code) {
  if (injectFn[lang]) {
    code = injectFn[lang](code);
  }
  return '\n<escape>' + code + '</escape>\n';
}

function syntaxExtra(raw, start, startQuote, language, options, content, endQuote, end) {
  var quoteCount = startQuote.length;

  var hide = quoteCount >= 5;
  var inject = (quoteCount === 4 || hide);

  if (!inject) {
    return raw;
  }
  //language = language.slice(0, -1);
  language = language.toLowerCase();
  language = getLanguage(language);

  if (['javascript', 'css', 'html'].indexOf(language) !== -1) {
    inject = inject && true;
  }

  if (!inject) {
    return raw;
  }
  // 替换为原生的 3 个反引号
  var meta = language + (options ? (' ' + options) : '');
  var native = start + '```' + meta + '\n' + content + '\n```' + end;
  var injected = escapeCode(language, content);

  return hide ? injected : (native + injected);
}

var blockTags = [
  'quote',
  'blockquote',
  'code',
  'codeblock',
  'pullquote'
];

var inlineTags = [
  'jsfiddle',
  'gist',
  'iframe',
  'img',
  'link',
  'include_code',
  'youtube',
  'vimeo',
  'post_path',
  'post_link',
  'asset_path',
  'asset_img',
  'asset_link'
];

function wrapBlockTag(language, options, content) {
  return '' +
    '{% ' + language + (options ? (' ' + options) : '') + ' %}\n' +
    content + '\n' +
    '{% end' + language + ' %}\n';
}

function wrapInlineTag(language, options) {
  return '{% ' + language + (options ? (' ' + options) : '') + ' %}';
}

function syntaxSugar(raw, language, options, content) {
  var blockIndex = blockTags.indexOf(language);
  var inlineIndex = inlineTags.indexOf(language);
  if (blockIndex === -1 && inlineIndex === -1) {
    return raw;
  }

  return blockIndex > -1
    ? wrapBlockTag(language, options, content)
    : inlineIndex > -1
    ? wrapInlineTag(language, options)
    : raw;
}

module.exports = function (data) {
  var source = data.source;
  var ext = source.substring(source.lastIndexOf('.')).toLowerCase();
  if ('.js.css.html.htm'.indexOf(ext) > -1) {
    return;
  }

  data.content = data.content
    .replace(rFenceCode, function (raw, start, startQuote, meta, content, endQuote, end) {
      if (!meta) {
        return raw;
      }

      var match = meta.match(rLang);

      var language;
      var options;
      if (match) {
        language = match[1] || '';
        options = match[2] || '';
      }

      if (!language) {
        return raw;
      }

      var quoteCount = startQuote.length;

      return quoteCount >= 4
        ? syntaxExtra(raw, start, startQuote, language, options, content, endQuote, end)
        : quoteCount === 3
        ? syntaxSugar(raw, language, options, content)
        : raw;

    });
};<commit_msg>extra-syntax<commit_after>/*
 * Markdown Extra Syntax
 * ---------------------
 *
 * - Fenced Code with Highlight
 *
 *   ```javascript
 *   var foo = "bar";
 *   ```
 *
 * - Highlight Code with Inserted Code
 *
 *   ```javascript+
 *   var foo = "bar";
 *   ```
 *
 *  or
 *
 *   ````javascript
 *   var foo = "bar";
 *   ````
 *
 * - Just insert code
 *
 *   ```javascript-
 *   var foo = "bar";
 *   ```
 *
 *  or
 *
 *   `````javascript
 *   var foo = "bar";
 *   `````
 * */

var rFenceCode = /(\s*)(`{3,}|~{3,}) *(.*) *\n?([\s\S]+?)\s*(\2)(\n+|$)/g;
var rLang = /([^\s]+)\s*(.+)?\s*(.+)?/;

var langMap = {
  'css': 'css',
  'htm': 'html',
  'html': 'html',
  'javascript': 'javascript',
  'js': 'javascript',
  'json': 'javascript'
};

var injectFn = {
  'javascript': function (code) {
    return '';
  },
  'css': function (code) {
    return '';
  },
  'html': function (code) {
    return '
' + code + '
';
  }
};

function getLanguage(lang) {
  if (lang && langMap[lang]) {
    lang = langMap[lang];
  }
  return lang;
}

function canInject(lang) {
  return ['javascript', 'css', 'html'].indexOf(lang) !== -1;
}

function escapeCode(lang, code) {
  if (injectFn[lang]) {
    code = injectFn[lang](code);
  }
  return '\n<escape>' + code + '</escape>\n';
}

var blockTags = [
  'quote',
  'blockquote',
  'code',
  'codeblock',
  'pullquote',
  'div',
  'section'
];

var inlineTags = [
  'jsfiddle',
  'gist',
  'iframe',
  'img',
  'link',
  'include_code',
  'youtube',
  'vimeo',
  'post_path',
  'post_link',
  'asset_path',
  'asset_img',
  'asset_link'
];

function wrapBlockTag(language, options, content) {
  return '' +
      '{% ' + language + (options ? (' ' + options) : '') + ' %}\n' +
      content + '\n' +
      '{% end' + language + ' %}\n';
}

function wrapInlineTag(language, options) {
  return '{% ' + language + (options ? (' ' + options) : '') + ' %}';
}

function syntaxSugar(raw, language, options, content) {
  var blockIndex = blockTags.indexOf(language);
  var inlineIndex = inlineTags.indexOf(language);
  if (blockIndex === -1 && inlineIndex === -1) {
    return raw;
  }

  return blockIndex > -1
      ? wrapBlockTag(language, options, content)
      : inlineIndex > -1
      ? wrapInlineTag(language, options)
      : raw;
}

function syntaxExtra(raw, start, startQuote, language, options, content, endQuote, end) {
  var quoteCount = startQuote.length;

  var hide = quoteCount >= 5;
  var inject = (quoteCount === 4 || hide);

  if (!inject) {
    return raw;
  }

  language = language.toLowerCase();
  language = getLanguage(language);

  inject = inject && canInject(language);

  if (!inject) {
    return raw;
  }

  // 替换为原生的 3 个反引号
  var meta = language + (options ? (' ' + options) : '');
  var native = start + '```' + meta + '\n' + content + '\n```' + end;
  var injected = escapeCode(language, content);

  return hide ? injected : (native + injected);
}

module.exports = function (data) {
  var source = data.source;
  var ext = source.substring(source.lastIndexOf('.')).toLowerCase();

  // 不处理静态文件
  if ('.js.css.html.htm'.indexOf(ext) > -1) {
    return;
  }

  data.content = data.content
      .replace(rFenceCode, function (raw, start, startQuote, meta, content, endQuote, end) {
        if (!meta) {
          return raw;
        }

        var match = meta.match(rLang);
        var language;
        var options;

        if (match) {
          language = match[1] || '';
          options = match[2] || '';
        }

        if (!language) {
          return raw;
        }

        var ext = language.substr(language.length - 1);
        if (ext === '+' || ext === '-') {
          var fixedLang = language.substr(0, language.length - 1);
          fixedLang = fixedLang.toLowerCase();
          fixedLang = getLanguage(fixedLang);

          if (canInject(fixedLang)) {
            language = fixedLang;

            startQuote = endQuote = ext === '+' ? '````' : '`````';
          }
        }

        var quoteCount = startQuote.length;

        return quoteCount >= 4
            ? syntaxExtra(raw, start, startQuote, language, options, content, endQuote, end)
            : quoteCount === 3
            ? syntaxSugar(raw, language, options, content)
            : raw;

      });
};
<|endoftext|>