<commit_before>

const expect = require('chai').expect;
const RG = require('../../../client/src/battles');

const Actor = RG.Actor.Rogue;

const updateSystems = function(systems) {
    for (let i = 0; i < systems.length; i++) {
        systems[i].update();
    }
};

describe('How dice are cast and what values they give', function() {
    it('Produces random values based on constructor arguments', function() {
        const die = new RG.Die(1, 10, 1);
        for (let i = 0; i < 100; i++) {
            const val = die.roll();
            expect(val >= 2).to.equal(true);
            expect(val <= 11).to.equal(true);
        }

        const factDie = RG.FACT.createDie('2d4 + 2');
        for (let i = 0; i < 100; i++) {
            const val = factDie.roll();
            expect(val >= 4).to.equal(true);
            expect(val <= 10).to.equal(true);
        }
    });

    it('Works also with string args', function() {
        const die = new RG.Die('1', '10', '1');
        for (let i = 0; i < 100; i++) {
            const val = die.roll();
            expect(val >= 2).to.equal(true);
            expect(val <= 11).to.equal(true);
        }

        const dieStr = die.toString();
        expect(dieStr).to.equal('1d10 + 1');

        const die2 = new RG.Die(1, 10, 1);
        expect(die2.equals(die)).to.equal(true);
        expect(die.equals(die2)).to.equal(true);

        const die3 = new RG.Die(0, 0, 0);
        for (let j = 0; j < 20; j++) {expect(die3.roll()).to.equal(0);}

        die3.copy(die);
        expect(die3.equals(die)).to.equal(true);
    });
});

const createSystems = function() {
    const mSystem = new RG.System.Missile('Missile', ['Missile']);
    const dSystem = new RG.System.Damage('Damage', ['Damage']);
    return [mSystem, dSystem];
};

const createMissile = function(obj) {
    const mEnt = new RG.Item.Missile('missile');
    const mComp = new RG.Component.Missile(obj.src);
    mComp.setDamage(obj.d);
    mEnt.add('Missile', mComp);
    mComp.setTargetXY(obj.x, obj.y);
    mComp.setRange(obj.r);
    return mComp;
};

describe('How missile is fired and hits a wall', function() {
    it('Starts from source and flies to target', function() {
        const systems = createSystems();

        const level = RG.FACT.createLevel('arena', 30, 30);
        // Archer to fire the missiles
        const srcEnt = new Actor('archer');

        level.addActor(srcEnt, 1, 1);

        const mEnt = new RG.Item.Missile('missile');
        const mComp = new RG.Component.Missile(srcEnt);
        mEnt.add('Missile', mComp);

        expect(mComp.getX()).to.equal(1);
        expect(mComp.getY()).to.equal(1);
        mComp.setTargetXY(1, 4);
        mComp.setRange(3);

        updateSystems(systems);
        expect(mComp.getX()).to.equal(1);
        expect(mComp.getY()).to.equal(4);
        expect(mComp.inTarget()).to.equal(true);
        expect(mComp.isFlying()).to.equal(false);

        // Now item should be lying around in the slot
        const targetCell = level.getMap().getCell(1, 4);
        expect(targetCell.hasProp('items')).to.equal(true);
    });

    it('Stops and hits a wall', function() {
        const systems = createSystems();

        const level = RG.FACT.createLevel('arena', 30, 30);
        // Archer to fire the missiles
        const srcEnt = new Actor('archer');
        level.addActor(srcEnt, 1, 1);

        const wall = new RG.Element.Base('wall');
        const map = level.getMap();
        const cell = map.getCell(1, 3);
        cell.setProp('elements', wall);

        const mEnt = new RG.Item.Missile('missile');
        const mComp = new RG.Component.Missile(srcEnt);
        mEnt.add('Missile', mComp);
        mComp.setTargetXY(1, 4);
        mComp.setRange(3);

        updateSystems(systems);
        expect(mComp.getX()).to.equal(1);
        expect(mComp.getY()).to.equal(2);
        expect(mComp.inTarget()).to.equal(false);
        expect(mComp.isFlying()).to.equal(false);

        const targetCell = level.getMap().getCell(1, 2);
        expect(targetCell.hasProp('items')).to.equal(true);

    });

    it('Stops and hits an entity (actor)', function() {
        const systems = createSystems();

        const level = RG.FACT.createLevel('arena', 30, 30);
        // Archer to fire the missiles
        const srcEnt = new Actor('archer');
        level.addActor(srcEnt, 1, 1);
        const targetEnt = new Actor('prey');
        const targetHP = targetEnt.get('Health').getHP();

        targetEnt.get('Combat').setDefense(0);
        level.addActor(targetEnt, 1, 6);

        // const mEnt = new RG.Item.Missile('missile');
        const mComp = createMissile({src: srcEnt, x: 1, y: 6, r: 10, d: 5});
        mComp.setAttack(1);

        updateSystems(systems);
        expect(mComp.getX()).to.equal(1);
        expect(mComp.getY()).to.equal(6);
        expect(mComp.inTarget()).to.equal(true);
        expect(mComp.isFlying()).to.equal(false);

        const currHP = targetEnt.get('Health').getHP();
        expect(targetEnt.has('Damage')).to.equal(false);
        expect(currHP).to.equal(targetHP - 5);

        const targetCell = level.getMap().getCell(1, 6);
        expect(targetCell.hasProp('items')).to.equal(true);
        expect(targetCell.hasPropType('missile')).to.equal(true);
    });

    it('Stops after reaching maximum range', function() {
        const systems = createSystems();
        const level = RG.FACT.createLevel('arena', 30, 30);
        // Archer to fire the missiles
        const srcEnt = new Actor('archer');
        level.addActor(srcEnt, 1, 1);

        const mComp = createMissile({src: srcEnt, x: 1, y: 6, r: 4, d: 5});

        updateSystems(systems);
        expect(mComp.getX()).to.equal(1);
        expect(mComp.getY()).to.equal(5);
        expect(mComp.inTarget()).to.equal(false);
        expect(mComp.isFlying()).to.equal(false);

        const targetCell = level.getMap().getCell(1, 5);
        expect(targetCell.hasProp('items')).to.equal(true);
        expect(targetCell.hasPropType('missile')).to.equal(true);
    });

    it('Missile passes through ethereal beings', function() {
        const systems = createSystems();
        const level = RG.FACT.createLevel('arena', 30, 30);
        const srcEnt = new Actor('archer');
        level.addActor(srcEnt, 1, 1);

        const mComp = createMissile({src: srcEnt, x: 1, y: 6, r: 4, d: 5});

        // Create a spirit and normal actor
        // TODO
    });
});

describe('How missile weapons affect missiles', () => {
    it('adds to the default range of missile', () => {
        const rifle = new RG.Item.MissileWeapon('rifle');
        rifle.setAttack(1);
        rifle.setAttackRange(4);
        rifle.setDamageDie('1d1+1');
        const ammo = new RG.Item.Ammo('rifle bullet');
        ammo.setAttack(2);
        ammo.setAttackRange(2);
        ammo.setDamageDie('3d1+3');
        const actor = new RG.Actor.Rogue('rogue');
        actor.get('Stats').setAccuracy(0);
        actor.get('Stats').setAgility(0);
        const invEq = actor.getInvEq();

        invEq.addItem(rifle);
        invEq.addItem(ammo);
        expect(invEq.equipItem(rifle)).to.equal(true);
        expect(invEq.equipItem(ammo)).to.equal(true);

        const attack = RG.getMissileAttack(actor, ammo);
        expect(attack).to.equal(3);

        const damage = RG.getMissileDamage(actor, ammo);
        expect(damage).to.equal(8);

        const range = RG.getMissileRange(actor, ammo);
        expect(range).to.equal(6);

    });
});
<commit_msg>Added a check to see that melee weapon does not give missile attack bonus.<commit_after>

const expect = require('chai').expect;
const RG = require('../../../client/src/battles');

const Actor = RG.Actor.Rogue;

const updateSystems = function(systems) {
    for (let i = 0; i < systems.length; i++) {
        systems[i].update();
    }
};

describe('How dice are cast and what values they give', function() {
    it('Produces random values based on constructor arguments', function() {
        const die = new RG.Die(1, 10, 1);
        for (let i = 0; i < 100; i++) {
            const val = die.roll();
            expect(val >= 2).to.equal(true);
            expect(val <= 11).to.equal(true);
        }

        const factDie = RG.FACT.createDie('2d4 + 2');
        for (let i = 0; i < 100; i++) {
            const val = factDie.roll();
            expect(val >= 4).to.equal(true);
            expect(val <= 10).to.equal(true);
        }
    });

    it('Works also with string args', function() {
        const die = new RG.Die('1', '10', '1');
        for (let i = 0; i < 100; i++) {
            const val = die.roll();
            expect(val >= 2).to.equal(true);
            expect(val <= 11).to.equal(true);
        }

        const dieStr = die.toString();
        expect(dieStr).to.equal('1d10 + 1');

        const die2 = new RG.Die(1, 10, 1);
        expect(die2.equals(die)).to.equal(true);
        expect(die.equals(die2)).to.equal(true);

        const die3 = new RG.Die(0, 0, 0);
        for (let j = 0; j < 20; j++) {expect(die3.roll()).to.equal(0);}

        die3.copy(die);
        expect(die3.equals(die)).to.equal(true);
    });
});

const createSystems = function() {
    const mSystem = new RG.System.Missile('Missile', ['Missile']);
    const dSystem = new RG.System.Damage('Damage', ['Damage']);
    return [mSystem, dSystem];
};

const createMissile = function(obj) {
    const mEnt = new RG.Item.Missile('missile');
    const mComp = new RG.Component.Missile(obj.src);
    mComp.setDamage(obj.d);
    mEnt.add('Missile', mComp);
    mComp.setTargetXY(obj.x, obj.y);
    mComp.setRange(obj.r);
    return mComp;
};

describe('How missile is fired and hits a wall', function() {
    it('Starts from source and flies to target', function() {
        const systems = createSystems();

        const level = RG.FACT.createLevel('arena', 30, 30);
        // Archer to fire the missiles
        const srcEnt = new Actor('archer');

        level.addActor(srcEnt, 1, 1);

        const mEnt = new RG.Item.Missile('missile');
        const mComp = new RG.Component.Missile(srcEnt);
        mEnt.add('Missile', mComp);

        expect(mComp.getX()).to.equal(1);
        expect(mComp.getY()).to.equal(1);
        mComp.setTargetXY(1, 4);
        mComp.setRange(3);

        updateSystems(systems);
        expect(mComp.getX()).to.equal(1);
        expect(mComp.getY()).to.equal(4);
        expect(mComp.inTarget()).to.equal(true);
        expect(mComp.isFlying()).to.equal(false);

        // Now item should be lying around in the slot
        const targetCell = level.getMap().getCell(1, 4);
        expect(targetCell.hasProp('items')).to.equal(true);
    });

    it('Stops and hits a wall', function() {
        const systems = createSystems();

        const level = RG.FACT.createLevel('arena', 30, 30);
        // Archer to fire the missiles
        const srcEnt = new Actor('archer');
        level.addActor(srcEnt, 1, 1);

        const wall = new RG.Element.Base('wall');
        const map = level.getMap();
        const cell = map.getCell(1, 3);
        cell.setProp('elements', wall);

        const mEnt = new RG.Item.Missile('missile');
        const mComp = new RG.Component.Missile(srcEnt);
        mEnt.add('Missile', mComp);
        mComp.setTargetXY(1, 4);
        mComp.setRange(3);

        updateSystems(systems);
        expect(mComp.getX()).to.equal(1);
        expect(mComp.getY()).to.equal(2);
        expect(mComp.inTarget()).to.equal(false);
        expect(mComp.isFlying()).to.equal(false);

        const targetCell = level.getMap().getCell(1, 2);
        expect(targetCell.hasProp('items')).to.equal(true);

    });

    it('Stops and hits an entity (actor)', function() {
        const systems = createSystems();

        const level = RG.FACT.createLevel('arena', 30, 30);
        // Archer to fire the missiles
        const srcEnt = new Actor('archer');
        level.addActor(srcEnt, 1, 1);
        const targetEnt = new Actor('prey');
        const targetHP = targetEnt.get('Health').getHP();

        targetEnt.get('Combat').setDefense(0);
        level.addActor(targetEnt, 1, 6);

        // const mEnt = new RG.Item.Missile('missile');
        const mComp = createMissile({src: srcEnt, x: 1, y: 6, r: 10, d: 5});
        mComp.setAttack(1);

        updateSystems(systems);
        expect(mComp.getX()).to.equal(1);
        expect(mComp.getY()).to.equal(6);
        expect(mComp.inTarget()).to.equal(true);
        expect(mComp.isFlying()).to.equal(false);

        const currHP = targetEnt.get('Health').getHP();
        expect(targetEnt.has('Damage')).to.equal(false);
        expect(currHP).to.equal(targetHP - 5);

        const targetCell = level.getMap().getCell(1, 6);
        expect(targetCell.hasProp('items')).to.equal(true);
        expect(targetCell.hasPropType('missile')).to.equal(true);
    });

    it('Stops after reaching maximum range', function() {
        const systems = createSystems();
        const level = RG.FACT.createLevel('arena', 30, 30);
        // Archer to fire the missiles
        const srcEnt = new Actor('archer');
        level.addActor(srcEnt, 1, 1);

        const mComp = createMissile({src: srcEnt, x: 1, y: 6, r: 4, d: 5});

        updateSystems(systems);
        expect(mComp.getX()).to.equal(1);
        expect(mComp.getY()).to.equal(5);
        expect(mComp.inTarget()).to.equal(false);
        expect(mComp.isFlying()).to.equal(false);

        const targetCell = level.getMap().getCell(1, 5);
        expect(targetCell.hasProp('items')).to.equal(true);
        expect(targetCell.hasPropType('missile')).to.equal(true);
    });

    it('Missile passes through ethereal beings', function() {
        const systems = createSystems();
        const level = RG.FACT.createLevel('arena', 30, 30);
        const srcEnt = new Actor('archer');
        level.addActor(srcEnt, 1, 1);

        const mComp = createMissile({src: srcEnt, x: 1, y: 6, r: 4, d: 5});

        // Create a spirit and normal actor
        // TODO
    });
});

describe('How missile weapons affect missiles', () => {
    it('adds to the default range of missile', () => {
        const sword = new RG.Item.Weapon('sword');
        sword.setAttack(10);
        const rifle = new RG.Item.MissileWeapon('rifle');
        rifle.setAttack(1);
        rifle.setAttackRange(4);
        rifle.setDamageDie('1d1+1');
        const ammo = new RG.Item.Ammo('rifle bullet');
        ammo.setAttack(2);
        ammo.setAttackRange(2);
        ammo.setDamageDie('3d1+3');
        const actor = new RG.Actor.Rogue('rogue');
        actor.get('Stats').setAccuracy(0);
        actor.get('Stats').setAgility(0);
        actor.get('Combat').setAttack(0);
        const invEq = actor.getInvEq();

        invEq.addItem(sword);
        invEq.addItem(rifle);
        invEq.addItem(ammo);
        expect(invEq.equipItem(sword)).to.equal(true);
        expect(invEq.equipItem(rifle)).to.equal(true);
        expect(invEq.equipItem(ammo)).to.equal(true);

        const attack = RG.getMissileAttack(actor, ammo);
        expect(attack).to.equal(3);

        const damage = RG.getMissileDamage(actor, ammo);
        expect(damage).to.equal(8);

        const range = RG.getMissileRange(actor, ammo);
        expect(range).to.equal(6);

    });
});
<|endoftext|>


<commit_before>//Variables
var activeCameras = 0;
var maxCameras = 4;
var selectedCamera = 0;

//Funcion para cargar una camara nueva
function loadNewCamera(){
    if (activeCameras >= maxCameras || !RoomInit)
        return;
    else {
        activePoints.push(0);
        activeCameras += 1;

        //Crear una camara
        var img = $('<img/>', { src : './img/camera/camera.png', alt : 'Image', class: 'img-responsive', onclick : 'loadCamera(' + activeCameras + ')' });
        var a = $('<a/>', {});
        var div = $('<div/>', {class: 'col-xs-3', id : 'camera'+activeCameras });
        //Aniadir la camara
        $('#cameras').append(div.append(a.append(img)));

        newCamera = new Camera('camara'+activeCameras, './img/camera/cameraT.png', 0, 0);

        loadCamera(activeCameras);
    }

    $('#btnAddPoint').removeAttr('disabled');
    $('#btnRemPoint').attr('disabled','disabled');
}

//Funcion para seleccionar una camara ya creada
function loadCamera( id ){
    selectedCamera = id;

    //Actualizar el canvas
    updateCamera();
    updatePoints();
    updateLines();

    //Seleccionar en el menú
    updateCameraBorder( id );

    // Actualizar la ficha
        // Camara
    $('.camera').each(function (i, obj) { //Buscar el objeto SVG
        var aux = obj.getAttributeNS(null, 'nombre').substr(6, 1); //Indice
        if (selectedCamera == aux) updateFileCoords('camera', obj.getAttributeNS(null, 'cX'), obj.getAttributeNS(null, 'cY'));
    });
        //Puntos
    $('#pointAccordion').empty(); //Limpia todos los hijos
    for (i = 0; i < activePoints[selectedCamera-1]; i++) //Crea los hijos correspondientes (no se actualizan aun)
        createFilePoint(i+1);

    // Actualizar botones de la interfaz
    if (activePoints[selectedCamera-1] > 0)
        $('#btnRemPoint').removeAttr('disabled');
    else
        $('#btnRemPoint').attr('disabled','disabled');
}

function removeCamera( id ) {
    $('#camera'+id).remove();

    updateCameraIndex( id );

    if (selectedCamera == id)
        loadCamera(1);

    activeCameras -= 1;
    activePoints.splice( id-1 , 1 );

    if (activeCameras == 0)
        $('#btnAddPoint').attr('disabled','disabled');
}

//Activa el borde en el carousel para la cámara activa
function updateCameraBorder( id ){
    for (i=1; i<=activeCameras; i++){
        $('#camera'+i+' img').css('border', '0px solid #D80000');
    }
    $('#camera' + id + ' img').css('border', '2px solid #D80000');
}

// Activar los puntos de control correspondientes a la camara cargada
function updateCamera() {
    $('.camera').each(function (i, obj) {
        var aux = obj.getAttributeNS(null, 'nombre').substr(6, 1); //Indice de la camara a la que pertenece

        if (selectedCamera == aux){ // Traer al frente
            document.getElementById('camera_level').appendChild(obj);
        }
        else{ //Llevar al fondo
            document.getElementById('hidden_level').appendChild(obj);
        }
    });
}

// Activar los puntos de control correspondientes a la camara cargada
function updatePoints() {
    $('.point').each(function (i, obj) {
        var aux = obj.getAttributeNS(null, 'nombre').substr(5, 1); //Indice de la camara a la que pertenece

        if (selectedCamera == aux){ // Traer al frente
            document.getElementById('point_level').appendChild(obj);
        }
        else{ //Llevar al fondo
            document.getElementById('hidden_level').appendChild(obj);
        }
    });
}

// Activar los puntos de control correspondientes a la camara cargada
function updateLines() {
    $('.line').each(function (i, obj) {
        var aux = obj.getAttributeNS(null, 'name').substr(5, 1); //Indice de la linea a la que pertenece

        if (selectedCamera == aux){ // Traer al frente
            document.getElementById('line_level').appendChild(obj);
        }
        else{ //Llevar al fondo
            document.getElementById('hidden_level').appendChild(obj);
        }
    });
}

//Cambia los nombres de las etiquetas correspondientes al índice anterior
//Por ejemplo: camara2 -> camara1
function updateCameraIndex( deletedIndex ) {
    for (i = deletedIndex; i <= activeCameras; i++) {
        var indice = (i - 1);

        var nuevoNombre = 'loadCamera(' + indice + ')';
        $('#camera' + i + ' img').attr('onclick', nuevoNombre);

        nuevoNombre = 'camera' + indice;
        $('#camera' + i).attr('id', nuevoNombre);
    }
}
<commit_msg>Error al borrar primera camara<commit_after>//Variables
var activeCameras = 0;
var maxCameras = 4;
var selectedCamera = 0;

//Funcion para cargar una camara nueva
function loadNewCamera(){
    if (activeCameras >= maxCameras || !RoomInit)
        return;
    else {
        activePoints.push(0);
        activeCameras += 1;

        //Crear una camara
        var img = $('<img/>', { src : './img/camera/camera.png', alt : 'Image', class: 'img-responsive', onclick : 'loadCamera(' + activeCameras + ')' });
        var a = $('<a/>', {});
        var div = $('<div/>', {class: 'col-xs-3', id : 'camera'+activeCameras });
        //Aniadir la camara
        $('#cameras').append(div.append(a.append(img)));

        newCamera = new Camera('camara'+activeCameras, './img/camera/cameraT.png', 0, 0);

        loadCamera(activeCameras);
    }

    $('#btnAddPoint').removeAttr('disabled');
    $('#btnRemPoint').attr('disabled','disabled');
}

//Funcion para seleccionar una camara ya creada
function loadCamera( id ){
    selectedCamera = id;

    //Actualizar el canvas
    updateCamera();
    updatePoints();
    updateLines();

    //Seleccionar en el menú
    updateCameraBorder( id );

    // Actualizar la ficha
        // Camara
    $('.camera').each(function (i, obj) { //Buscar el objeto SVG
        var aux = obj.getAttributeNS(null, 'nombre').substr(6, 1); //Indice
        if (selectedCamera == aux) updateFileCoords('camera', obj.getAttributeNS(null, 'cX'), obj.getAttributeNS(null, 'cY'));
    });
        //Puntos
    $('#pointAccordion').empty(); //Limpia todos los hijos

    for (i = 0; i < activePoints[selectedCamera-1]; i++) //Crea los hijos correspondientes (no se actualizan aun)
        createFilePoint(i+1);

    // Actualizar botones de la interfaz
    if (activePoints[selectedCamera-1] > 0)
        $('#btnRemPoint').removeAttr('disabled');
    else
        $('#btnRemPoint').attr('disabled','disabled');
}

function removeCamera( id ) {
    $('#camera'+id).remove();

    updateCameraIndex( id );

    activeCameras -= 1;
    activePoints.splice( id-1 , 1 );

    if (selectedCamera == id)
        loadCamera(1);

    if (activeCameras == 0)
        $('#btnAddPoint').attr('disabled','disabled');
}

//Activa el borde en el carousel para la cámara activa
function updateCameraBorder( id ){
    for (i=1; i<=activeCameras; i++){
        $('#camera'+i+' img').css('border', '0px solid #D80000');
    }
    $('#camera' + id + ' img').css('border', '2px solid #D80000');
}

// Activar los puntos de control correspondientes a la camara cargada
function updateCamera() {
    $('.camera').each(function (i, obj) {
        var aux = obj.getAttributeNS(null, 'nombre').substr(6, 1); //Indice de la camara a la que pertenece

        if (selectedCamera == aux){ // Traer al frente
            document.getElementById('camera_level').appendChild(obj);
        }
        else{ //Llevar al fondo
            document.getElementById('hidden_level').appendChild(obj);
        }
    });
}

// Activar los puntos de control correspondientes a la camara cargada
function updatePoints() {
    $('.point').each(function (i, obj) {
        var aux = obj.getAttributeNS(null, 'nombre').substr(5, 1); //Indice de la camara a la que pertenece

        if (selectedCamera == aux){ // Traer al frente
            document.getElementById('point_level').appendChild(obj);
        }
        else{ //Llevar al fondo
            document.getElementById('hidden_level').appendChild(obj);
        }
    });
}

// Activar los puntos de control correspondientes a la camara cargada
function updateLines() {
    $('.line').each(function (i, obj) {
        var aux = obj.getAttributeNS(null, 'name').substr(5, 1); //Indice de la linea a la que pertenece

        if (selectedCamera == aux){ // Traer al frente
            document.getElementById('line_level').appendChild(obj);
        }
        else{ //Llevar al fondo
            document.getElementById('hidden_level').appendChild(obj);
        }
    });
}

//Cambia los nombres de las etiquetas correspondientes al índice anterior
//Por ejemplo: camara2 -> camara1
function updateCameraIndex( deletedIndex ) {
    for (i = deletedIndex; i <= activeCameras; i++) {
        var indice = (i - 1);

        var nuevoNombre = 'loadCamera(' + indice + ')';
        $('#camera' + i + ' img').attr('onclick', nuevoNombre);

        nuevoNombre = 'camera' + indice;
        $('#camera' + i).attr('id', nuevoNombre);
    }
}
<|endoftext|>


<commit_before>/*
// Sets the html document to be opened as a popup when the user clicks on the browser action's icon
*/
window.onload = function() {

// declares first color picker for font
    $('#picker').colpick({
      flat:true,
    	layout:'hex',
    	submit:0,
    	colorScheme:'dark',
    	onChange:function(hsb,hex,rgb,el,bySetColor) {
    		chrome.tabs.executeScript({
          code: 'document.body.style.color = "#' + hex + '"'
        });
    	}
    }).keyup(function(){
    	$(this).colpickSetColor(this.value);
    });

// links font to color graph
    $("#fontForm").submit(function() {
      var font = $("#fontselect").val();

      // document.getElementsByTagName("p");
      /*slect p tag and iterate over it
      element.style.fontFamily = "' + font + '"*/

      chrome.tabs.executeScript({
        code: 'document.body.style.fontFamily = "' + font + '"'
      });

      return false;
    });

// second color slider for background
    $('#pickerback').colpick({
      flat:true,
      layout:'hex',
      submit:0,
      colorScheme:'dark',
      onChange:function(hsb,hex,rgb,el,bySetColor) {
        chrome.tabs.executeScript({
          code: 'document.body.style.color = "#' + hex + '"'
        });
      }
    }).keyup(function(){
      $(this).colpickSetColor(this.value);
    });

// links the background to the color graph- THIS DOESNT WORK_ STILL LINKS TO FONT
    $("#backgroundForm").submit(function() {
      var background = $("#backgroundselect").val();

      // document.getElementsByTagName("p");
      /*slect p tag and iterate over it
      element.style.backgroundFamily = "' + background + '"*/

      chrome.tabs.executeScript({
        code: 'document.body.style.backgroundFamily = "' + background + '"'
      });

      return false;
    });

};
<commit_msg>backgroundtry1<commit_after>/*
// Sets the html document to be opened as a popup when the user clicks on the browser action's icon
*/
window.onload = function() {

// declares first color picker for font
    $('#picker').colpick({
      flat:true,
    	layout:'hex',
    	submit:0,
    	colorScheme:'dark',
    	onChange:function(hsb,hex,rgb,el,bySetColor) {
    		chrome.tabs.executeScript({
          code: 'document.body.style.color = "#' + hex + '"'
        });
    	}
    }).keyup(function(){
    	$(this).colpickSetColor(this.value);
    });

// links font to color graph
    $("#fontForm").submit(function() {
      var font = $("#fontselect").val();

      // document.getElementsByTagName("p");
      /*slect p tag and iterate over it
      element.style.fontFamily = "' + font + '"*/

      chrome.tabs.executeScript({
        code: 'document.body.style.fontFamily = "' + font + '"'
      });

      return false;
    });

// second color slider for background
    $('#pickerback').colpick({
      flat:true,
      layout:'hex',
      submit:0,
      colorScheme:'dark',
      onChange:function(hsb,hex,rgb,el,bySetColor) {
        chrome.tabs.executeScript({
          code: 'document.body.style.color = "#' + hex + '"'
        });
      }
    }).keyup(function(){
      $(this).colpickSetColor(this.value);
    });

// links the background to the color graph- THIS DOESNT WORK_ STILL LINKS TO FONT
    $("#backgroundForm").submit(function() {
      var background = $("#backgroundselect").val();

      // document.getElementsByTagName("p");
      /*slect p tag and iterate over it
      element.style.backgroundFamily = "' + background + '"*/

      chrome.tabs.executeScript({
        code: 'document.body.style.backgroundFamily = "' + background-color + '"'
      });

      return false;
    });

};
<|endoftext|>


<commit_before>// jQuery selectors
var options = $('.options');
var paperSize = $('[name="paper-size"]', options);
var orientation = $('[name="paper-orientation"]', options);
var imageCount = $('[name="image-count"]', options);
var imageSize = $('[name="image-size"]', options);
var imagePadding = $('[name="image-padding"]', options);
var customImageSize = $('.custom-image-size', options);

var preview = $('.preview');
var page = $('.print-page');

var images = [];

applySettings();
ga('send', 'pageview', 'print-preview.html');

// Reapply settings
$('[name="apply"]', options).on("click", function () {
  setupCanvas();
});

$('[name="print"]', options).on("click", function () {
  ga('send', 'event', "Settings", "print");
  convertStylingToMm();
  $('#print-media').html(`
      size: ${ paperSize.val() } ${ orientation.val() };
  `);
  window.print();
});

$('[name="help"]', options).on("click", function () {
   chrome.extension.sendRequest({action:"help"});
});

// Custom Image Sizes
customImageSize.hide();
imageSize.on("change", function () {
  var self = $(this);
  if (self.val() == "custom_in" || self.val() == "custom_cm") {
    customImageSize.show();
  } else {
    customImageSize.hide();
  }
});

// Build Preview
function setupCanvas () {

  var pageWidth;
  var pageHeight;

  // Page Orientation and height
  if (isLandscape()) {
    pageWidth = preview.width > 1300 ? preview.width() * 0.9 : preview.width() * 0.6;
    pageHeight = pageWidth * getPaperRatio(paperSize.val(), "landscape");
    setImageCount(imageCount.val());
    setImageSize(getPixelSizeInMm(pageHeight));
  } else {
    pageHeight = preview.height() * 0.9;
    pageWidth = pageHeight * getPaperRatio(paperSize.val(), "portrait");
    setImageCount(imageCount.val());
    setImageSize(getPixelSizeInMm(pageWidth));
  }

  page.css("height", pageHeight);
  page.css("width", pageWidth);

  applyImages();
  saveSettings();

}

function isLandscape () {
  if (orientation.val() == "landscape") {
    return true;
  } else {
    return false;
  }
}

function setImageSize (mm) {

  var imageHeight;
  var imageWidth;

  switch (imageSize.val()) {
    case "6x4":
    imageWidth = 6 * 25.4;
    imageHeight =  4 * 25.4;
    break;

    case "6x4.5":
    imageWidth = 6 * 25.4;
    imageHeight = 4.5 * 25.4;
    break;

    case "5x3.75":
    imageWidth = 5 * 25.4;
    imageHeight = 3.75 * 25.4;
    break;

    case "3x2":
    imageWidth = 3 * 25.4;
    imageHeight = 2  * 25.4;
    break;

    case "custom_in":
    imageWidth = $('.custom-image-size [name="width"]').val() * 25.4;
    imageHeight = $('.custom-image-size [name="height"]').val()  * 25.4;
    break;

    case "custom_cm":
    imageWidth = $('.custom-image-size [name="width"]').val() * 10;
    imageHeight = $('.custom-image-size [name="height"]').val() * 10;
    break;
  }

  $('.print-image', page).css("width", imageWidth * mm)
  .css("min-width", imageWidth * mm)
  .css("max-width", imageWidth * mm)
  .css("height", imageHeight * mm)
  .css("max-height", imageHeight * mm)
  .css("min-height", imageHeight * mm)
  .css("margin", imagePadding.val() * mm);

}

function setImageCount (amount) {

  page.empty();
  for (var i = 0; i < amount; i++) {
     var imageElement = `

     <input id="fileUploadInput${i}" class="fileUpload" type="file" accept="image/*" />

     `;
    page.append(imageElement);
  }

  $('.print-image', page).each(function () {
    // Update the drop zone class on drag enter/leave
    $(this).bind('dragenter', function(ev) {
        var placeholder = $(ev.target);
        if (placeholder.hasClass("placeholder")) placeholder.addClass('dragover');
        return false;
    })
    .bind('dragleave', function(ev) {
        $(ev.target).removeClass('dragover');
        return false;
    })

    // Allow drops of any kind into the zone.
    .bind('dragover', function(ev) {
      return false;
    })

    // Handle the final drop...
    .bind('drop', function(ev) {
      var e = ev.originalEvent;
      var imageUrl = false;

      // If placeholder
      if ($(ev.target).hasClass("placeholder")) {

        if (e.preventDefault) e.preventDefault(); // stops the browser from redirecting off to the text.

        if (e.dataTransfer.types) {
          // For each data type
          [].forEach.call(e.dataTransfer.types, function (type) {
            if (type == "text/plain") {
              var url = e.dataTransfer.getData(type);
              if (checkURL(url)) {
                 ga('send', 'event', "Image", "added", "dragged");
                 images.push(url);
                 saveImages();
                 setImageFromUrl(ev.target, url);
                 imageUrl = true;
                 return;
              }
           }
          });
          if (!imageUrl) {
             alert("You must drag images directly.");
             ga('send', 'event', "Image", "failed", "dragged");
             $(ev.target).removeClass('dragover');
          }
        }

      }
      return false;
    });

   $(".fileUpload", $(this)).on("change", function (e) {
      var fileInput = $(this)[0];
      var file = fileInput.files[0];
      var url;

      if (file) {
         url = URL.createObjectURL(e.target.files[0]);
         images.push(url);
         saveImages();
         setImageFromUrl($(this)[0].parentElement, url);
         ga('send', 'event', "Image", "added", "uploaded");
     }

   });

  });
}

function checkURL(url) {
  let valid = false;
  valid = (url.match(/\.(jpeg|jpg|gif|png)$/) != null);
  if (!valid) valid = (url.match(/googleusercontent/) != null);
  return valid;

function rotateImage (image) {
  var orgHeight = image.parent().height();
  var orgWidth = image.parent().width();

  image.removeAttr("style");

    // Portrait to Landscape
    if (image.height < orgWidth) {
      image.css("width", orgHeight + "px");
    } else {
      image.css("height", orgWidth + "px");
    }
    image.css("position", "relative");
    image.css("bottom", "0px");
    image.addClass("print-image-source-portrait");
}

function rotatePlaceholder (image) {
  var orgHeight = image.parent().height();
  var orgWidth = image.parent().width();

  // Landscape to portrait
  image.parent().animate({
    'height': orgWidth,
    'min-height': orgWidth,
    'max-height': orgWidth,
    'width': orgHeight,
    'min-width': orgHeight,
    'max-width': orgHeight
  }, 500, function () {
    image.addClass("print-image-source-landscape");
  });
}

function setImageFromUrl (place, url) {

  place = $(place);
  place.removeClass("dragover placeholder");
  var image = $('.print-image-source', place);
  // rotate image
  getImageMeta(url, function (width, height) {

    if (width < height) {
      var orgHeight = image.parent().height();
      var orgWidth = image.parent().width();
      if ($('[name=rotate-image]:checked', options).val() == "rotate-placeholder") {
        rotatePlaceholder(image);
      } else {
        rotateImage(image);
      }
    } else {
      image.addClass("print-image-source-landscape");
    }
    image.attr("src", url);

  });

  place.on("click", function () {
    if (!place.hasClass("placeholder")) {
      ga('send', 'event', "Image", "removed");
      place.addClass("placeholder");
      $('.print-image-source', place).removeClass("print-image-source-landscape print-image-source-portrait");
      var removeIndex = images.indexOf(image.attr("src"));
      images.splice(removeIndex, 1);
      image.attr("src", url);
      saveImages();
    }
  });
}

function getImageMeta(url, callback) {
    var img = new Image();
    img.src = url;
    img.onload = function() { callback(this.width, this.height); }
}

function getPixelSizeInMm (pixelHeight) {
  var paperFormat = paperSize.val();
  var paperHeight;
  switch (paperFormat) {
    case "A4":
    paperHeight = 210;
    break;

    case "A5":
    paperHeight = 148;
    break;
  }

  return pixelHeight / paperHeight;
}

function getPaperRatio (size, orientation, paperWidth = 0, paperHeight = 0) {

  // Sizes are in mm
  switch (size) {
    case "A4":
    paperHeight = 210;
    paperWidth = 297;
    break;

    case "A5":
    paperHeight = 148;
    paperWidth = 210;
    break;
  }

  return paperHeight / paperWidth;

}

function allowDrop(ev) {
  ev.preventDefault();
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.originalEvent.dataTransfer;
  //ev.target.appendChild(document.getElementById(data));
}

function saveImages () {
  chrome.extension.sendRequest(
    {action:"save", saveName:"images", saveContent: images},
    function(response){
    });

}

function loadImages () {
  chrome.extension.sendRequest({action: "load", load:"images"}, function (response) {
    if (response.loaded && response.loaded.images) {
      images = response.loaded.images;
      applyImages();
   }
  });
}

function applyImages () {
  $('.print-image-source').each(function (index) {
      var image = images[index];
      if (image) {
        setImageFromUrl($(this).parent(), image);
      }
  });

  $('.print-image-source-portrait').each(function () {
    rotateImage($(this));
  });
}

function saveSettings () {

  var printSettings = {
      'paperSize': paperSize.val(),
      'paperOrientation': orientation.val(),
      'imageCount': imageCount.val(),
      'imageSize': imageSize.val(),
      'imagePadding': imagePadding.val()
    }

  chrome.extension.sendRequest({action:"save", saveName: "printSettings", saveContent: printSettings}, function(response){});

}

function applySettings () {
  ga('send', 'event', "Settings", "updated");
  chrome.extension.sendRequest({action: "load", load:"printSettings"}, function (response) {

        if (response.loaded && Object.keys(response.loaded).length !== 0) {
          var result = response.loaded.printSettings;
          result.paperSize ? $('option[value="' + result.paperSize + '"]', paperSize).attr("selected",true) : "";
          result.paperOrientation ? $('option[value="' + result.paperOrientation + '"]', orientation).attr("selected",true) : "";
          result.imageCount ? imageCount.val(result.imageCount) : "";
          result.imageSize ? $('option[value="' + result.imageSize + '"]', imageSize).attr("selected",true) : "";
          result.imagePadding ? imagePadding.val(result.imagePadding) : "";
        } else {
          console.log("No settings saved");
        }

        setupCanvas();
        loadImages();
  });

}

/// Printing
function convertStylingToMm () {
  setPageToMm();
  setImagesToMm();
}

function setImagesToMm () {
  switch (imageSize.val()) {
    case "6x4":
    imageWidth = 6 * 25.4;
    imageHeight =  4 * 25.4;
    break;

    case "6x4.5":
    imageWidth = 6 * 25.4;
    imageHeight = 4.5 * 25.4;
    break;

    case "5x3.75":
    imageWidth = 5 * 25.4;
    imageHeight = 3.75 * 25.4;
    break;

    case "3x2":
    imageWidth = 3 * 25.4;
    imageHeight = 2  * 25.4;
    break;

    case "custom_in":
    imageWidth = $('.custom-image-size [name="width"]').val() * 25.4;
    imageHeight = $('.custom-image-size [name="height"]').val()  * 25.4;
    break;

    case "custom_cm":
    imageWidth = $('.custom-image-size [name="width"]').val() * 10;
    imageHeight = $('.custom-image-size [name="height"]').val() * 10;
    break;
  }

  $('.print-image', page).css("width", imageWidth  + "mm")
  .css("min-width", imageWidth  + "mm")
  .css("max-width", imageWidth  + "mm")
  .css("height", imageHeight  + "mm")
  .css("min-height", imageHeight  + "mm")
  .css("max-height", imageHeight  + "mm")
  .css("margin", imagePadding.val());

  // Portrait images
   $('.print-image-source-portrait', page).each(function () {
     var imageElement = $(this);
     if (imageElement.height < imageElement.width) {
       imageElement.css("width", imageHeight + "mm");
     } else {
       imageElement.css("height", imageWidth + "mm");
     }
   });
}

function setPageToMm () {
  var paperWidth;
  var paperHeight;

  switch (paperSize.val()) {
    case "A4":
    paperHeight = 210;
    paperWidth = 297;
    break;

    case "A5":
    paperHeight = 148;
    paperWidth = 210;
    break;
  }

  if (!isLandscape()) {
    page.css("height", paperWidth  + "mm");
    page.css("width", paperHeight  + "mm");
  } else {
    page.css("height", paperHeight  + "mm");
    page.css("width", paperWidth + "mm");
  }
}
<commit_msg>Remove any additional styling when rotating<commit_after>// jQuery selectors
var options = $('.options');
var paperSize = $('[name="paper-size"]', options);
var orientation = $('[name="paper-orientation"]', options);
var imageCount = $('[name="image-count"]', options);
var imageSize = $('[name="image-size"]', options);
var imagePadding = $('[name="image-padding"]', options);
var customImageSize = $('.custom-image-size', options);

var preview = $('.preview');
var page = $('.print-page');

var images = [];

applySettings();
ga('send', 'pageview', 'print-preview.html');

// Reapply settings
$('[name="apply"]', options).on("click", function () {
  setupCanvas();
});

$('[name="print"]', options).on("click", function () {
  ga('send', 'event', "Settings", "print");
  convertStylingToMm();
  $('#print-media').html(`
      size: ${ paperSize.val() } ${ orientation.val() };
  `);
  window.print();
});

$('[name="help"]', options).on("click", function () {
   chrome.extension.sendRequest({action:"help"});
});

// Custom Image Sizes
customImageSize.hide();
imageSize.on("change", function () {
  var self = $(this);
  if (self.val() == "custom_in" || self.val() == "custom_cm") {
    customImageSize.show();
  } else {
    customImageSize.hide();
  }
});

// Build Preview
function setupCanvas () {

  var pageWidth;
  var pageHeight;

  // Page Orientation and height
  if (isLandscape()) {
    pageWidth = preview.width > 1300 ? preview.width() * 0.9 : preview.width() * 0.6;
    pageHeight = pageWidth * getPaperRatio(paperSize.val(), "landscape");
    setImageCount(imageCount.val());
    setImageSize(getPixelSizeInMm(pageHeight));
  } else {
    pageHeight = preview.height() * 0.9;
    pageWidth = pageHeight * getPaperRatio(paperSize.val(), "portrait");
    setImageCount(imageCount.val());
    setImageSize(getPixelSizeInMm(pageWidth));
  }

  page.css("height", pageHeight);
  page.css("width", pageWidth);

  applyImages();
  saveSettings();

}

function isLandscape () {
  if (orientation.val() == "landscape") {
    return true;
  } else {
    return false;
  }
}

function setImageSize (mm) {

  var imageHeight;
  var imageWidth;

  switch (imageSize.val()) {
    case "6x4":
    imageWidth = 6 * 25.4;
    imageHeight =  4 * 25.4;
    break;

    case "6x4.5":
    imageWidth = 6 * 25.4;
    imageHeight = 4.5 * 25.4;
    break;

    case "5x3.75":
    imageWidth = 5 * 25.4;
    imageHeight = 3.75 * 25.4;
    break;

    case "3x2":
    imageWidth = 3 * 25.4;
    imageHeight = 2  * 25.4;
    break;

    case "custom_in":
    imageWidth = $('.custom-image-size [name="width"]').val() * 25.4;
    imageHeight = $('.custom-image-size [name="height"]').val()  * 25.4;
    break;

    case "custom_cm":
    imageWidth = $('.custom-image-size [name="width"]').val() * 10;
    imageHeight = $('.custom-image-size [name="height"]').val() * 10;
    break;
  }

  $('.print-image', page).css("width", imageWidth * mm)
  .css("min-width", imageWidth * mm)
  .css("max-width", imageWidth * mm)
  .css("height", imageHeight * mm)
  .css("max-height", imageHeight * mm)
  .css("min-height", imageHeight * mm)
  .css("margin", imagePadding.val() * mm);

}

function setImageCount (amount) {

  page.empty();
  for (var i = 0; i < amount; i++) {
     var imageElement = `

     <input id="fileUploadInput${i}" class="fileUpload" type="file" accept="image/*" />

     `;
    page.append(imageElement);
  }

  $('.print-image', page).each(function () {
    // Update the drop zone class on drag enter/leave
    $(this).bind('dragenter', function(ev) {
        var placeholder = $(ev.target);
        if (placeholder.hasClass("placeholder")) placeholder.addClass('dragover');
        return false;
    })
    .bind('dragleave', function(ev) {
        $(ev.target).removeClass('dragover');
        return false;
    })

    // Allow drops of any kind into the zone.
    .bind('dragover', function(ev) {
      return false;
    })

    // Handle the final drop...
    .bind('drop', function(ev) {
      var e = ev.originalEvent;
      var imageUrl = false;

      // If placeholder
      if ($(ev.target).hasClass("placeholder")) {

        if (e.preventDefault) e.preventDefault(); // stops the browser from redirecting off to the text.

        if (e.dataTransfer.types) {
          // For each data type
          [].forEach.call(e.dataTransfer.types, function (type) {
            if (type == "text/plain") {
              var url = e.dataTransfer.getData(type);
              if (checkURL(url)) {
                 ga('send', 'event', "Image", "added", "dragged");
                 images.push(url);
                 saveImages();
                 setImageFromUrl(ev.target, url);
                 imageUrl = true;
                 return;
              }
           }
          });
          if (!imageUrl) {
             alert("You must drag images directly.");
             ga('send', 'event', "Image", "failed", "dragged");
             $(ev.target).removeClass('dragover');
          }
        }

      }
      return false;
    });

   $(".fileUpload", $(this)).on("change", function (e) {
      var fileInput = $(this)[0];
      var file = fileInput.files[0];
      var url;

      if (file) {
         url = URL.createObjectURL(e.target.files[0]);
         images.push(url);
         saveImages();
         setImageFromUrl($(this)[0].parentElement, url);
         ga('send', 'event', "Image", "added", "uploaded");
     }

   });

  });
}

function checkURL(url) {
  let valid = false;
  valid = (url.match(/\.(jpeg|jpg|gif|png)$/) != null);
  if (!valid) valid = (url.match(/googleusercontent/) != null);
  return valid;

function rotateImage (image) {
  var orgHeight = image.parent().height();
  var orgWidth = image.parent().width();

  image.removeAttr("style");

    // Portrait to Landscape
    if (image.height < orgWidth) {
      image.css("width", orgHeight + "px");
    } else {
      image.css("height", orgWidth + "px");
    }
    image.css("position", "relative");
    image.css("bottom", "0px");
    image.addClass("print-image-source-portrait");
}

function rotatePlaceholder (image) {
  var orgHeight = image.parent().height();
  var orgWidth = image.parent().width();

  // Landscape to portrait
  image.parent().animate({
    'height': orgWidth,
    'min-height': orgWidth,
    'max-height': orgWidth,
    'width': orgHeight,
    'min-width': orgHeight,
    'max-width': orgHeight
  }, 500, function () {
    image.addClass("print-image-source-landscape");
  });
}

function setImageFromUrl (place, url) {

  place = $(place);
  place.removeClass("dragover placeholder");
  var image = $('.print-image-source', place);
  // rotate image
  getImageMeta(url, function (width, height) {

    if (width < height) {
      var orgHeight = image.parent().height();
      var orgWidth = image.parent().width();
      if ($('[name=rotate-image]:checked', options).val() == "rotate-placeholder") {
        rotatePlaceholder(image);
      } else {
        rotateImage(image);
      }
    } else {
      image.addClass("print-image-source-landscape");
    }
    image.attr("src", url);

  });

  place.on("click", function () {
    if (!place.hasClass("placeholder")) {
      ga('send', 'event', "Image", "removed");
      place.addClass("placeholder");
      $('.print-image-source', place).removeClass("print-image-source-landscape print-image-source-portrait").removeAttr("style");
      var removeIndex = images.indexOf(image.attr("src"));
      images.splice(removeIndex, 1);
      image.attr("src", url);
      saveImages();
    }
  });
}

function getImageMeta(url, callback) {
    var img = new Image();
    img.src = url;
    img.onload = function() { callback(this.width, this.height); }
}

function getPixelSizeInMm (pixelHeight) {
  var paperFormat = paperSize.val();
  var paperHeight;
  switch (paperFormat) {
    case "A4":
    paperHeight = 210;
    break;

    case "A5":
    paperHeight = 148;
    break;
  }

  return pixelHeight / paperHeight;
}

function getPaperRatio (size, orientation, paperWidth = 0, paperHeight = 0) {

  // Sizes are in mm
  switch (size) {
    case "A4":
    paperHeight = 210;
    paperWidth = 297;
    break;

    case "A5":
    paperHeight = 148;
    paperWidth = 210;
    break;
  }

  return paperHeight / paperWidth;

}

function allowDrop(ev) {
  ev.preventDefault();
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.originalEvent.dataTransfer;
  //ev.target.appendChild(document.getElementById(data));
}

function saveImages () {
  chrome.extension.sendRequest(
    {action:"save", saveName:"images", saveContent: images},
    function(response){
    });

}

function loadImages () {
  chrome.extension.sendRequest({action: "load", load:"images"}, function (response) {
    if (response.loaded && response.loaded.images) {
      images = response.loaded.images;
      applyImages();
   }
  });
}

function applyImages () {
  $('.print-image-source').each(function (index) {
      var image = images[index];
      if (image) {
        setImageFromUrl($(this).parent(), image);
      }
  });

  $('.print-image-source-portrait').each(function () {
    rotateImage($(this));
  });
}

function saveSettings () {

  var printSettings = {
      'paperSize': paperSize.val(),
      'paperOrientation': orientation.val(),
      'imageCount': imageCount.val(),
      'imageSize': imageSize.val(),
      'imagePadding': imagePadding.val()
    }

  chrome.extension.sendRequest({action:"save", saveName: "printSettings", saveContent: printSettings}, function(response){});

}

function applySettings () {
  ga('send', 'event', "Settings", "updated");
  chrome.extension.sendRequest({action: "load", load:"printSettings"}, function (response) {

        if (response.loaded && Object.keys(response.loaded).length !== 0) {
          var result = response.loaded.printSettings;
          result.paperSize ? $('option[value="' + result.paperSize + '"]', paperSize).attr("selected",true) : "";
          result.paperOrientation ? $('option[value="' + result.paperOrientation + '"]', orientation).attr("selected",true) : "";
          result.imageCount ? imageCount.val(result.imageCount) : "";
          result.imageSize ? $('option[value="' + result.imageSize + '"]', imageSize).attr("selected",true) : "";
          result.imagePadding ? imagePadding.val(result.imagePadding) : "";
        } else {
          console.log("No settings saved");
        }

        setupCanvas();
        loadImages();
  });

}

/// Printing
function convertStylingToMm () {
  setPageToMm();
  setImagesToMm();
}

function setImagesToMm () {
  switch (imageSize.val()) {
    case "6x4":
    imageWidth = 6 * 25.4;
    imageHeight =  4 * 25.4;
    break;

    case "6x4.5":
    imageWidth = 6 * 25.4;
    imageHeight = 4.5 * 25.4;
    break;

    case "5x3.75":
    imageWidth = 5 * 25.4;
    imageHeight = 3.75 * 25.4;
    break;

    case "3x2":
    imageWidth = 3 * 25.4;
    imageHeight = 2  * 25.4;
    break;

    case "custom_in":
    imageWidth = $('.custom-image-size [name="width"]').val() * 25.4;
    imageHeight = $('.custom-image-size [name="height"]').val()  * 25.4;
    break;

    case "custom_cm":
    imageWidth = $('.custom-image-size [name="width"]').val() * 10;
    imageHeight = $('.custom-image-size [name="height"]').val() * 10;
    break;
  }

  $('.print-image', page).css("width", imageWidth  + "mm")
  .css("min-width", imageWidth  + "mm")
  .css("max-width", imageWidth  + "mm")
  .css("height", imageHeight  + "mm")
  .css("min-height", imageHeight  + "mm")
  .css("max-height", imageHeight  + "mm")
  .css("margin", imagePadding.val());

  // Portrait images
   $('.print-image-source-portrait', page).each(function () {
     var imageElement = $(this);
     if (imageElement.height < imageElement.width) {
       imageElement.css("width", imageHeight + "mm");
     } else {
       imageElement.css("height", imageWidth + "mm");
     }
   });
}

function setPageToMm () {
  var paperWidth;
  var paperHeight;

  switch (paperSize.val()) {
    case "A4":
    paperHeight = 210;
    paperWidth = 297;
    break;

    case "A5":
    paperHeight = 148;
    paperWidth = 210;
    break;
  }

  if (!isLandscape()) {
    page.css("height", paperWidth  + "mm");
    page.css("width", paperHeight  + "mm");
  } else {
    page.css("height", paperHeight  + "mm");
    page.css("width", paperWidth + "mm");
  }
}
<|endoftext|>


<commit_before>// jQuery selectors
var options = $('.options');
var paperSize = $('[name="paper-size"]', options);
var orientation = $('[name="paper-orientation"]', options);
var imageCount = $('[name="image-count"]', options);
var imageSize = $('[name="image-size"]', options);
var imagePadding = $('[name="image-padding"]', options);
var customImageSize = $('.custom-image-size', options);

var preview = $('.preview');
var page = $('.print-page');

var images = [];

applySettings();
ga('send', 'pageview', 'print-preview.html');

// Reapply settings
$('[name="apply"]', options).on("click", function () {
  setupCanvas();
});

$('[name="print"]', options).on("click", function () {
  ga('send', 'event', "Settings", "print");
  convertStylingToMm();
  $('#print-media').html(`
      size: ${ paperSize.val() } ${ orientation.val() };
  `);
  window.print();
});

$('[name="help"]', options).on("click", function () {
   chrome.extension.sendRequest({action:"help"});
});

// Custom Image Sizes
customImageSize.hide();
imageSize.on("change", function () {
  var self = $(this);
  if (self.val() == "custom_in" || self.val() == "custom_cm") {
    customImageSize.show();
  } else {
    customImageSize.hide();
  }
});

// Build Preview
function setupCanvas () {

  var pageWidth;
  var pageHeight;

  // Page Orientation and height
  if (isLandscape()) {
    pageWidth = preview.width() * 0.9;
    pageHeight = pageWidth * getPaperRatio(paperSize.val(), "landscape");
    setImageCount(imageCount.val());
    setImageSize(getPixelSizeInMm(pageHeight));
  } else {
    pageHeight = preview.height() * 0.9;
    pageWidth = pageHeight * getPaperRatio(paperSize.val(), "portrait");
    setImageCount(imageCount.val());
    setImageSize(getPixelSizeInMm(pageWidth));
  }

  page.css("height", pageHeight);
  page.css("width", pageWidth);

  applyImages();
  saveSettings();

}

function isLandscape () {
  if (orientation.val() == "landscape") {
    return true;
  } else {
    return false;
  }
}

function setImageSize (mm) {

  var imageHeight;
  var imageWidth;

  switch (imageSize.val()) {
    case "6x4":
    imageWidth = 6 * 25.4;
    imageHeight =  4 * 25.4;
    break;

    case "6x4.5":
    imageWidth = 6 * 25.4;
    imageHeight = 4.5 * 25.4;
    break;

    case "5x3.75":
    imageWidth = 5 * 25.4;
    imageHeight = 3.75 * 25.4;
    break;

    case "3x2":
    imageWidth = 3 * 25.4;
    imageHeight = 2  * 25.4;
    break;

    case "custom_in":
    imageWidth = $('.custom-image-size [name="width"]').val() * 25.4;
    imageHeight = $('.custom-image-size [name="height"]').val()  * 25.4;
    break;

    case "custom_cm":
    imageWidth = $('.custom-image-size [name="width"]').val() * 10;
    imageHeight = $('.custom-image-size [name="height"]').val() * 10;
    break;
  }

  $('.print-image', page).css("width", imageWidth * mm)
  .css("min-width", imageWidth * mm)
  .css("max-width", imageWidth * mm)
  .css("height", imageHeight * mm)
  .css("max-height", imageHeight * mm)
  .css("min-height", imageHeight * mm)
  .css("margin", imagePadding.val() * mm);

}

function setImageCount (amount) {

  page.empty();
  for (var i = 0; i < amount; i++) {
     var imageElement = `

     <input id="fileUploadInput${i}" class="fileUpload" type="file" accept="image/*" />

     `;
    page.append(imageElement);
  }

  $('.print-image', page).each(function () {
    // Update the drop zone class on drag enter/leave
    $(this).bind('dragenter', function(ev) {
        var placeholder = $(ev.target);
        if (placeholder.hasClass("placeholder")) placeholder.addClass('dragover');
        return false;
    })
    .bind('dragleave', function(ev) {
        $(ev.target).removeClass('dragover');
        return false;
    })

    // Allow drops of any kind into the zone.
    .bind('dragover', function(ev) {
      return false;
    })

    // Handle the final drop...
    .bind('drop', function(ev) {
      var e = ev.originalEvent;
      var imageUrl = false;

      // If placeholder
      if ($(ev.target).hasClass("placeholder")) {

        if (e.preventDefault) e.preventDefault(); // stops the browser from redirecting off to the text.

        if (e.dataTransfer.types) {
          // For each data type
          [].forEach.call(e.dataTransfer.types, function (type) {
            if (type == "text/plain") {
              var url = e.dataTransfer.getData(type);
              if (checkURL(url)) {
                 ga('send', 'event', "Image", "added", "dragged");
                 images.push(url);
                 saveImages();
                 setImageFromUrl(ev.target, url);
                 imageUrl = true;
                 return;
              }
           }
          });
          if (!imageUrl) {
             alert("You must drag images directly.");
             ga('send', 'event', "Image", "failed", "dragged");
             $(ev.target).removeClass('dragover');
          }
        }

      }
      return false;
    });

   $(".fileUpload", $(this)).on("change", function (e) {
      var fileInput = $(this)[0];
      var file = fileInput.files[0];
      var url;

      if (file) {
         url = URL.createObjectURL(e.target.files[0]);
         images.push(url);
         saveImages();
         setImageFromUrl($(this)[0].parentElement, url);
     }

   });

  });
}

function checkURL(url) {
  let valid = false;
  valid = (url.match(/\.(jpeg|jpg|gif|png)$/) != null);
  if (!valid) valid = (url.match(/googleusercontent/) != null);
  return valid;
}

function setImageFromUrl (place, url) {

  place = $(place);
  place.removeClass("dragover placeholder");
  var image = $('.print-image-source', place);
  // rotate image
  getImageMeta(url, function (width, height) {

    if (width < height) {
      var orgHeight = image.parent().height();
      var orgWidth = image.parent().width();
      if ($('[name=rotate-image]:checked', options).val() == "rotate-placeholder") {
        // Landscape to portrait
        image.parent().animate({
          'height': orgWidth,
          'min-height': orgWidth,
          'max-height': orgWidth,
          'width': orgHeight,
          'min-width': orgHeight,
          'max-width': orgHeight
        }, 500, function () {
          image.addClass("print-image-source-landscape");
          image.attr("src", url);
        });
      } else {
        // Portrait to Landscape
        if (image.height < orgWidth) {
          image.css("width", orgHeight + "px");
        } else {
          image.css("height", orgWidth + "px");
        }
        image.attr("src", url);
        image.css("position", "relative");
        image.css("bottom", "0px");
        image.addClass("print-image-source-portrait");
      }
    } else {
      image.attr("src", url);
      image.addClass("print-image-source-landscape");
    }

  });

  place.on("click", function () {
    if (!place.hasClass("placeholder")) {
      ga('send', 'event', "Image", "removed");
      place.addClass("placeholder");
      $('.print-image-source', place).removeClass("print-image-source-landscape print-image-source-portrait");
      var removeIndex = images.indexOf(image.attr("src"));
      images.splice(removeIndex, 1);
      image.attr("src", url);
      saveImages();
    }
  });
}

function getImageMeta(url, callback) {
    var img = new Image();
    img.src = url;
    img.onload = function() { callback(this.width, this.height); }
}

function getPixelSizeInMm (pixelHeight) {
  var paperFormat = paperSize.val();
  var paperHeight;
  switch (paperFormat) {
    case "A4":
    paperHeight = 210;
    break;

    case "A5":
    paperHeight = 148;
    break;
  }

  return pixelHeight / paperHeight;
}

function getPaperRatio (size, orientation, paperWidth = 0, paperHeight = 0) {

  // Sizes are in mm
  switch (size) {
    case "A4":
    paperHeight = 210;
    paperWidth = 297;
    break;

    case "A5":
    paperHeight = 148;
    paperWidth = 210;
    break;
  }

  return paperHeight / paperWidth;

}

function allowDrop(ev) {
  ev.preventDefault();
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.originalEvent.dataTransfer;
  //ev.target.appendChild(document.getElementById(data));
}

function saveImages () {
  chrome.extension.sendRequest(
    {action:"save", saveName:"images", saveContent: images},
    function(response){
    });

}

function loadImages () {
  chrome.extension.sendRequest({action: "load", load:"images"}, function (response) {
    if (response.loaded && response.loaded.images) {
      images = response.loaded.images;
      applyImages();
   }
  });

}

function applyImages () {
  $('.print-image-source').each(function (index) {
      var image = images[index];
      if (image) {
        setImageFromUrl($(this).parent(), image);
      }
  });
}

function saveSettings () {

  var printSettings = {
      'paperSize': paperSize.val(),
      'paperOrientation': orientation.val(),
      'imageCount': imageCount.val(),
      'imageSize': imageSize.val(),
      'imagePadding': imagePadding.val()
    }

  chrome.extension.sendRequest({action:"save", saveName: "printSettings", saveContent: printSettings}, function(response){});

}

function applySettings () {
  ga('send', 'event', "Settings", "updated");
  chrome.extension.sendRequest({action: "load", load:"printSettings"}, function (response) {

        if (response.loaded && Object.keys(response.loaded).length !== 0) {
          var result = response.loaded.printSettings;
          result.paperSize ? $('option[value="' + result.paperSize + '"]', paperSize).attr("selected",true) : "";
          result.paperOrientation ? $('option[value="' + result.paperOrientation + '"]', orientation).attr("selected",true) : "";
          result.imageCount ? imageCount.val(result.imageCount) : "";
          result.imageSize ? $('option[value="' + result.imageSize + '"]', imageSize).attr("selected",true) : "";
          result.imagePadding ? imagePadding.val(result.imagePadding) : "";
        } else {
          console.log("No settings saved");
        }

        setupCanvas();
        loadImages();
  });

}

/// Printing
function convertStylingToMm () {
  setPageToMm();
  setImagesToMm();
}

function setImagesToMm () {
  switch (imageSize.val()) {
    case "6x4":
    imageWidth = 6 * 25.4;
    imageHeight =  4 * 25.4;
    break;

    case "6x4.5":
    imageWidth = 6 * 25.4;
    imageHeight = 4.5 * 25.4;
    break;

    case "5x3.75":
    imageWidth = 5 * 25.4;
    imageHeight = 3.75 * 25.4;
    break;

    case "3x2":
    imageWidth = 3 * 25.4;
    imageHeight = 2  * 25.4;
    break;

    case "custom_in":
    imageWidth = $('.custom-image-size [name="width"]').val() * 25.4;
    imageHeight = $('.custom-image-size [name="height"]').val()  * 25.4;
    break;

    case "custom_cm":
    imageWidth = $('.custom-image-size [name="width"]').val() * 10;
    imageHeight = $('.custom-image-size [name="height"]').val() * 10;
    break;
  }

  $('.print-image', page).css("width", imageWidth  + "mm")
  .css("min-width", imageWidth  + "mm")
  .css("max-width", imageWidth  + "mm")
  .css("height", imageHeight  + "mm")
  .css("min-height", imageHeight  + "mm")
  .css("max-height", imageHeight  + "mm")
  .css("margin", imagePadding.val());

  // Portrait images
   $('.print-image-source-portrait', page).each(function () {
     var imageElement = $(this);
     if (imageElement.height < imageElement.width) {
       imageElement.css("width", imageHeight + "mm");
     } else {
       imageElement.css("height", imageWidth + "mm");
     }
   });
}

function setPageToMm () {
  var paperWidth;
  var paperHeight;

  switch (paperSize.val()) {
    case "A4":
    paperHeight = 210;
    paperWidth = 297;
    break;

    case "A5":
    paperHeight = 148;
    paperWidth = 210;
    break;
  }

  if (!isLandscape()) {
    page.css("height", paperWidth  + "mm");
    page.css("width", paperHeight  + "mm");
  } else {
    page.css("height", paperHeight  + "mm");
    page.css("width", paperWidth + "mm");
  }
}
<commit_msg>Reduce paper ratio when on a larger screen<commit_after>// jQuery selectors
var options = $('.options');
var paperSize = $('[name="paper-size"]', options);
var orientation = $('[name="paper-orientation"]', options);
var imageCount = $('[name="image-count"]', options);
var imageSize = $('[name="image-size"]', options);
var imagePadding = $('[name="image-padding"]', options);
var customImageSize = $('.custom-image-size', options);

var preview = $('.preview');
var page = $('.print-page');

var images = [];

applySettings();
ga('send', 'pageview', 'print-preview.html');

// Reapply settings
$('[name="apply"]', options).on("click", function () {
  setupCanvas();
});

$('[name="print"]', options).on("click", function () {
  ga('send', 'event', "Settings", "print");
  convertStylingToMm();
  $('#print-media').html(`
      size: ${ paperSize.val() } ${ orientation.val() };
  `);
  window.print();
});

$('[name="help"]', options).on("click", function () {
   chrome.extension.sendRequest({action:"help"});
});

// Custom Image Sizes
customImageSize.hide();
imageSize.on("change", function () {
  var self = $(this);
  if (self.val() == "custom_in" || self.val() == "custom_cm") {
    customImageSize.show();
  } else {
    customImageSize.hide();
  }
});

// Build Preview
function setupCanvas () {

  var pageWidth;
  var pageHeight;

  // Page Orientation and height
  if (isLandscape()) {
    pageWidth = preview.width > 1300 ? preview.width() * 0.9 : preview.width() * 0.6;
    pageHeight = pageWidth * getPaperRatio(paperSize.val(), "landscape");
    setImageCount(imageCount.val());
    setImageSize(getPixelSizeInMm(pageHeight));
  } else {
    pageHeight = preview.height() * 0.9;
    pageWidth = pageHeight * getPaperRatio(paperSize.val(), "portrait");
    setImageCount(imageCount.val());
    setImageSize(getPixelSizeInMm(pageWidth));
  }

  page.css("height", pageHeight);
  page.css("width", pageWidth);

  applyImages();
  saveSettings();

}

function isLandscape () {
  if (orientation.val() == "landscape") {
    return true;
  } else {
    return false;
  }
}

function setImageSize (mm) {

  var imageHeight;
  var imageWidth;

  switch (imageSize.val()) {
    case "6x4":
    imageWidth = 6 * 25.4;
    imageHeight =  4 * 25.4;
    break;

    case "6x4.5":
    imageWidth = 6 * 25.4;
    imageHeight = 4.5 * 25.4;
    break;

    case "5x3.75":
    imageWidth = 5 * 25.4;
    imageHeight = 3.75 * 25.4;
    break;

    case "3x2":
    imageWidth = 3 * 25.4;
    imageHeight = 2  * 25.4;
    break;

    case "custom_in":
    imageWidth = $('.custom-image-size [name="width"]').val() * 25.4;
    imageHeight = $('.custom-image-size [name="height"]').val()  * 25.4;
    break;

    case "custom_cm":
    imageWidth = $('.custom-image-size [name="width"]').val() * 10;
    imageHeight = $('.custom-image-size [name="height"]').val() * 10;
    break;
  }

  $('.print-image', page).css("width", imageWidth * mm)
  .css("min-width", imageWidth * mm)
  .css("max-width", imageWidth * mm)
  .css("height", imageHeight * mm)
  .css("max-height", imageHeight * mm)
  .css("min-height", imageHeight * mm)
  .css("margin", imagePadding.val() * mm);

}

function setImageCount (amount) {

  page.empty();
  for (var i = 0; i < amount; i++) {
     var imageElement = `

     <input id="fileUploadInput${i}" class="fileUpload" type="file" accept="image/*" />

     `;
    page.append(imageElement);
  }

  $('.print-image', page).each(function () {
    // Update the drop zone class on drag enter/leave
    $(this).bind('dragenter', function(ev) {
        var placeholder = $(ev.target);
        if (placeholder.hasClass("placeholder")) placeholder.addClass('dragover');
        return false;
    })
    .bind('dragleave', function(ev) {
        $(ev.target).removeClass('dragover');
        return false;
    })

    // Allow drops of any kind into the zone.
    .bind('dragover', function(ev) {
      return false;
    })

    // Handle the final drop...
    .bind('drop', function(ev) {
      var e = ev.originalEvent;
      var imageUrl = false;

      // If placeholder
      if ($(ev.target).hasClass("placeholder")) {

        if (e.preventDefault) e.preventDefault(); // stops the browser from redirecting off to the text.

        if (e.dataTransfer.types) {
          // For each data type
          [].forEach.call(e.dataTransfer.types, function (type) {
            if (type == "text/plain") {
              var url = e.dataTransfer.getData(type);
              if (checkURL(url)) {
                 ga('send', 'event', "Image", "added", "dragged");
                 images.push(url);
                 saveImages();
                 setImageFromUrl(ev.target, url);
                 imageUrl = true;
                 return;
              }
           }
          });
          if (!imageUrl) {
             alert("You must drag images directly.");
             ga('send', 'event', "Image", "failed", "dragged");
             $(ev.target).removeClass('dragover');
          }
        }

      }
      return false;
    });

   $(".fileUpload", $(this)).on("change", function (e) {
      var fileInput = $(this)[0];
      var file = fileInput.files[0];
      var url;

      if (file) {
         url = URL.createObjectURL(e.target.files[0]);
         images.push(url);
         saveImages();
         setImageFromUrl($(this)[0].parentElement, url);
         ga('send', 'event', "Image", "added", "uploaded");
     }

   });

  });
}

function checkURL(url) {
  let valid = false;
  valid = (url.match(/\.(jpeg|jpg|gif|png)$/) != null);
  if (!valid) valid = (url.match(/googleusercontent/) != null);
  return valid;
}

function setImageFromUrl (place, url) {

  place = $(place);
  place.removeClass("dragover placeholder");
  var image = $('.print-image-source', place);
  // rotate image
  getImageMeta(url, function (width, height) {

    if (width < height) {
      var orgHeight = image.parent().height();
      var orgWidth = image.parent().width();
      if ($('[name=rotate-image]:checked', options).val() == "rotate-placeholder") {
        // Landscape to portrait
        image.parent().animate({
          'height': orgWidth,
          'min-height': orgWidth,
          'max-height': orgWidth,
          'width': orgHeight,
          'min-width': orgHeight,
          'max-width': orgHeight
        }, 500, function () {
          image.addClass("print-image-source-landscape");
          image.attr("src", url);
        });
      } else {
        // Portrait to Landscape
        if (image.height < orgWidth) {
          image.css("width", orgHeight + "px");
        } else {
          image.css("height", orgWidth + "px");
        }
        image.attr("src", url);
        image.css("position", "relative");
        image.css("bottom", "0px");
        image.addClass("print-image-source-portrait");
      }
    } else {
      image.attr("src", url);
      image.addClass("print-image-source-landscape");
    }

  });

  place.on("click", function () {
    if (!place.hasClass("placeholder")) {
      ga('send', 'event', "Image", "removed");
      place.addClass("placeholder");
      $('.print-image-source', place).removeClass("print-image-source-landscape print-image-source-portrait");
      var removeIndex = images.indexOf(image.attr("src"));
      images.splice(removeIndex, 1);
      image.attr("src", url);
      saveImages();
    }
  });
}

function getImageMeta(url, callback) {
    var img = new Image();
    img.src = url;
    img.onload = function() { callback(this.width, this.height); }
}

function getPixelSizeInMm (pixelHeight) {
  var paperFormat = paperSize.val();
  var paperHeight;
  switch (paperFormat) {
    case "A4":
    paperHeight = 210;
    break;

    case "A5":
    paperHeight = 148;
    break;
  }

  return pixelHeight / paperHeight;
}

function getPaperRatio (size, orientation, paperWidth = 0, paperHeight = 0) {

  // Sizes are in mm
  switch (size) {
    case "A4":
    paperHeight = 210;
    paperWidth = 297;
    break;

    case "A5":
    paperHeight = 148;
    paperWidth = 210;
    break;
  }

  return paperHeight / paperWidth;

}

function allowDrop(ev) {
  ev.preventDefault();
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.originalEvent.dataTransfer;
  //ev.target.appendChild(document.getElementById(data));
}

function saveImages () {
  chrome.extension.sendRequest(
    {action:"save", saveName:"images", saveContent: images},
    function(response){
    });

}

function loadImages () {
  chrome.extension.sendRequest({action: "load", load:"images"}, function (response) {
    if (response.loaded && response.loaded.images) {
      images = response.loaded.images;
      applyImages();
   }
  });

}

function applyImages () {
  $('.print-image-source').each(function (index) {
      var image = images[index];
      if (image) {
        setImageFromUrl($(this).parent(), image);
      }
  });
}

function saveSettings () {

  var printSettings = {
      'paperSize': paperSize.val(),
      'paperOrientation': orientation.val(),
      'imageCount': imageCount.val(),
      'imageSize': imageSize.val(),
      'imagePadding': imagePadding.val()
    }

  chrome.extension.sendRequest({action:"save", saveName: "printSettings", saveContent: printSettings}, function(response){});

}

function applySettings () {
  ga('send', 'event', "Settings", "updated");
  chrome.extension.sendRequest({action: "load", load:"printSettings"}, function (response) {

        if (response.loaded && Object.keys(response.loaded).length !== 0) {
          var result = response.loaded.printSettings;
          result.paperSize ? $('option[value="' + result.paperSize + '"]', paperSize).attr("selected",true) : "";
          result.paperOrientation ? $('option[value="' + result.paperOrientation + '"]', orientation).attr("selected",true) : "";
          result.imageCount ? imageCount.val(result.imageCount) : "";
          result.imageSize ? $('option[value="' + result.imageSize + '"]', imageSize).attr("selected",true) : "";
          result.imagePadding ? imagePadding.val(result.imagePadding) : "";
        } else {
          console.log("No settings saved");
        }

        setupCanvas();
        loadImages();
  });

}

/// Printing
function convertStylingToMm () {
  setPageToMm();
  setImagesToMm();
}

function setImagesToMm () {
  switch (imageSize.val()) {
    case "6x4":
    imageWidth = 6 * 25.4;
    imageHeight =  4 * 25.4;
    break;

    case "6x4.5":
    imageWidth = 6 * 25.4;
    imageHeight = 4.5 * 25.4;
    break;

    case "5x3.75":
    imageWidth = 5 * 25.4;
    imageHeight = 3.75 * 25.4;
    break;

    case "3x2":
    imageWidth = 3 * 25.4;
    imageHeight = 2  * 25.4;
    break;

    case "custom_in":
    imageWidth = $('.custom-image-size [name="width"]').val() * 25.4;
    imageHeight = $('.custom-image-size [name="height"]').val()  * 25.4;
    break;

    case "custom_cm":
    imageWidth = $('.custom-image-size [name="width"]').val() * 10;
    imageHeight = $('.custom-image-size [name="height"]').val() * 10;
    break;
  }

  $('.print-image', page).css("width", imageWidth  + "mm")
  .css("min-width", imageWidth  + "mm")
  .css("max-width", imageWidth  + "mm")
  .css("height", imageHeight  + "mm")
  .css("min-height", imageHeight  + "mm")
  .css("max-height", imageHeight  + "mm")
  .css("margin", imagePadding.val());

  // Portrait images
   $('.print-image-source-portrait', page).each(function () {
     var imageElement = $(this);
     if (imageElement.height < imageElement.width) {
       imageElement.css("width", imageHeight + "mm");
     } else {
       imageElement.css("height", imageWidth + "mm");
     }
   });
}

function setPageToMm () {
  var paperWidth;
  var paperHeight;

  switch (paperSize.val()) {
    case "A4":
    paperHeight = 210;
    paperWidth = 297;
    break;

    case "A5":
    paperHeight = 148;
    paperWidth = 210;
    break;
  }

  if (!isLandscape()) {
    page.css("height", paperWidth  + "mm");
    page.css("width", paperHeight  + "mm");
  } else {
    page.css("height", paperHeight  + "mm");
    page.css("width", paperWidth + "mm");
  }
}
<|endoftext|>


<commit_before>/* Author: Daniel Katzberg */
'use strict';

angular.module('metadatamanagementApp')
  .controller('DataAcquisitionProjectNavbarController', [
    'CurrentProjectService', 'DataAcquisitionProjectPostValidationService',
    'DataAcquisitionProjectSearchResource', 'DataAcquisitionProjectResource',
    '$mdDialog', 'SimpleMessageToastService', '$translate',
    'ElasticSearchAdminService',
    function(CurrentProjectService,
      DataAcquisitionProjectPostValidationService,
      DataAcquisitionProjectSearchResource, DataAcquisitionProjectResource,
      $mdDialog, SimpleMessageToastService, $translate,
      ElasticSearchAdminService) {
      var ctrl = this;
      //For Project Handling
      ctrl.dataAcquisitionProjects = null;
      ctrl.searchText = '';
      //Load the projects for the drop menu
      function loadProjects() {
        DataAcquisitionProjectSearchResource.findAll(
          function(result) {
            ctrl.dataAcquisitionProjects =
              result._embedded.dataAcquisitionProjects;
            var projects = ctrl.searchProjects(ctrl.searchText);
            if (projects.length === 1) {
              ctrl.selectedProject = projects[0];
              ctrl.searchText = projects[0].id;
            } else {
              ctrl.selectedProject = null;
              ctrl.searchText = '';
            }
          });
      }
      //Helper method for query the project list
      function createFilterFor(query) {
        var lowercaseQuery = angular.lowercase(query);
        return function filterFn(project) {
          return (project.id.indexOf(lowercaseQuery) === 0);
        };
      }

      //Query for searching in project list
      ctrl.searchProjects = function(query) {
        var results = query ? ctrl.dataAcquisitionProjects.filter(
          createFilterFor(query)) : ctrl.dataAcquisitionProjects;
        return results;
      };

      //Update the state for the current project
      ctrl.onSelectedProjectChanged = function(project) {
        CurrentProjectService.setCurrentProject(project);
      };

      /* Function for opening a dialog for creating a new project */
      ctrl.createProject = function() {
        $mdDialog.show({
            controller: 'CreateProjectDialogController',
            templateUrl: 'scripts/dataacquisitionprojectmanagement/' +
              'views/create-project-dialog.html.tmpl',
            clickOutsideToClose: false
          })
          .then(function(project) {
            DataAcquisitionProjectResource.save(project,
              //Success
              function() {
                SimpleMessageToastService
                  .openSimpleMessageToast(
                    'data-acquisition-project-management.log-messages.' +
                    'data-acquisition-project.saved', {
                      id: project.id
                    });
                ctrl.selectedProject = project;
                CurrentProjectService.setCurrentProject(project);
                loadProjects();
              },
              //Server Error
              function(errorMsg) {
                SimpleMessageToastService
                  .openSimpleMessageToast(
                    'data-acquisition-project-management.log-messages.' +
                    'data-acquisition-project.server-error' + errorMsg);
                loadProjects();
              }
            );
          });
      };

      //Conformation Dialog for the deletion of a project
      ctrl.deleteProject = function() {
        var confirm = $mdDialog.confirm()
          .title($translate.instant(
            'data-acquisition-project-management.log-messages.' +
            'data-acquisition-project.delete-title', {
              id: ctrl.selectedProject.id
            }))
          .textContent($translate.instant(
            'data-acquisition-project-management.log-messages.' +
            'data-acquisition-project.delete', {
              id: ctrl.selectedProject.id
            }))
          .ariaLabel($translate.instant(
            'data-acquisition-project-management.log-messages.' +
            'data-acquisition-project.delete', {
              id: ctrl.selectedProject.id
            }))
          .ok($translate.instant('global.buttons.ok'))
          .cancel($translate.instant('global.buttons.cancel'));

        $mdDialog.show(confirm).then(function() {
          //User clicked okay -> Delete Project, hide dialog, show feedback
          $mdDialog.hide(ctrl.selectedProject.id);
          DataAcquisitionProjectResource.delete({
              id: ctrl.selectedProject.id
            },
            function() {
              ElasticSearchAdminService.processUpdateQueue().then(
                function() {
                  SimpleMessageToastService.openSimpleMessageToast(
                    'data-acquisition-project-management.log-messages.' +
                    'data-acquisition-project.deleted-successfully-project', {
                      id: ctrl.selectedProject.id
                    });
                  loadProjects();
                });
            },
            function() {
              SimpleMessageToastService.openSimpleMessageToast(

                'data-acquisition-project-management.log-messages.' +
                'data-acquisition-project.deleted-not-successfully-project', {
                  id: ctrl.selectedProject.id
                });
            });

        }, function() {
          //User clicked cancel
          $mdDialog.cancel();
        });
      };

      ctrl.postValidateProject = function() {
        DataAcquisitionProjectPostValidationService
          .postValidate(ctrl.selectedProject.id);
      };
      loadProjects();
    }
  ]);
<commit_msg>#919 added initialization with current project to fix the bug<commit_after>/* Author: Daniel Katzberg */
'use strict';

angular.module('metadatamanagementApp')
  .controller('DataAcquisitionProjectNavbarController', [
    'CurrentProjectService', 'DataAcquisitionProjectPostValidationService',
    'DataAcquisitionProjectSearchResource', 'DataAcquisitionProjectResource',
    '$mdDialog', 'SimpleMessageToastService', '$translate',
    'ElasticSearchAdminService',
    function(CurrentProjectService,
      DataAcquisitionProjectPostValidationService,
      DataAcquisitionProjectSearchResource, DataAcquisitionProjectResource,
      $mdDialog, SimpleMessageToastService, $translate,
      ElasticSearchAdminService) {
      var ctrl = this;
      //For Project Handling
      ctrl.dataAcquisitionProjects = null;
      ctrl.searchText = '';

      // init the input controle with the current project
      if (CurrentProjectService.getCurrentProject()) {
        ctrl.searchText = CurrentProjectService.getCurrentProject().id;
      }
      //Load the projects for the drop menu
      function loadProjects() {
        DataAcquisitionProjectSearchResource.findAll(
          function(result) {
            ctrl.dataAcquisitionProjects =
              result._embedded.dataAcquisitionProjects;
            var projects = ctrl.searchProjects(ctrl.searchText);
            if (projects.length === 1) {
              ctrl.selectedProject = projects[0];
              ctrl.searchText = projects[0].id;
            } else {
              ctrl.selectedProject = null;
              ctrl.searchText = '';
            }
          });
      }
      //Helper method for query the project list
      function createFilterFor(query) {
        var lowercaseQuery = angular.lowercase(query);
        return function filterFn(project) {
          return (project.id.indexOf(lowercaseQuery) === 0);
        };
      }

      //Query for searching in project list
      ctrl.searchProjects = function(query) {
        var results = query ? ctrl.dataAcquisitionProjects.filter(
          createFilterFor(query)) : ctrl.dataAcquisitionProjects;
        return results;
      };

      //Update the state for the current project
      ctrl.onSelectedProjectChanged = function(project) {
        CurrentProjectService.setCurrentProject(project);
      };

      /* Function for opening a dialog for creating a new project */
      ctrl.createProject = function() {
        $mdDialog.show({
            controller: 'CreateProjectDialogController',
            templateUrl: 'scripts/dataacquisitionprojectmanagement/' +
              'views/create-project-dialog.html.tmpl',
            clickOutsideToClose: false
          })
          .then(function(project) {
            DataAcquisitionProjectResource.save(project,
              //Success
              function() {
                SimpleMessageToastService
                  .openSimpleMessageToast(
                    'data-acquisition-project-management.log-messages.' +
                    'data-acquisition-project.saved', {
                      id: project.id
                    });
                ctrl.selectedProject = project;
                CurrentProjectService.setCurrentProject(project);
                loadProjects();
              },
              //Server Error
              function(errorMsg) {
                SimpleMessageToastService
                  .openSimpleMessageToast(
                    'data-acquisition-project-management.log-messages.' +
                    'data-acquisition-project.server-error' + errorMsg);
                loadProjects();
              }
            );
          });
      };

      //Conformation Dialog for the deletion of a project
      ctrl.deleteProject = function() {
        var confirm = $mdDialog.confirm()
          .title($translate.instant(
            'data-acquisition-project-management.log-messages.' +
            'data-acquisition-project.delete-title', {
              id: ctrl.selectedProject.id
            }))
          .textContent($translate.instant(
            'data-acquisition-project-management.log-messages.' +
            'data-acquisition-project.delete', {
              id: ctrl.selectedProject.id
            }))
          .ariaLabel($translate.instant(
            'data-acquisition-project-management.log-messages.' +
            'data-acquisition-project.delete', {
              id: ctrl.selectedProject.id
            }))
          .ok($translate.instant('global.buttons.ok'))
          .cancel($translate.instant('global.buttons.cancel'));

        $mdDialog.show(confirm).then(function() {
          //User clicked okay -> Delete Project, hide dialog, show feedback
          $mdDialog.hide(ctrl.selectedProject.id);
          DataAcquisitionProjectResource.delete({
              id: ctrl.selectedProject.id
            },
            function() {
              ElasticSearchAdminService.processUpdateQueue().then(
                function() {
                  SimpleMessageToastService.openSimpleMessageToast(
                    'data-acquisition-project-management.log-messages.' +
                    'data-acquisition-project.deleted-successfully-project', {
                      id: ctrl.selectedProject.id
                    });
                  loadProjects();
                });
            },
            function() {
              SimpleMessageToastService.openSimpleMessageToast(

                'data-acquisition-project-management.log-messages.' +
                'data-acquisition-project.deleted-not-successfully-project', {
                  id: ctrl.selectedProject.id
                });
            });

        }, function() {
          //User clicked cancel
          $mdDialog.cancel();
        });
      };

      ctrl.postValidateProject = function() {
        DataAcquisitionProjectPostValidationService
          .postValidate(ctrl.selectedProject.id);
      };
      loadProjects();
    }
  ]);
<|endoftext|>