<commit_before>
$(document).ready(function() {
    // Globals
    States = {pageIsActive: true, tappedInfoButton: false };
    InteractionIndex = {datetime: 0, user_id: 1, color: 2};
    ClockElements = { year: $('#year'), month: $('#month'), day: $('#day'), hour: $('#hour'), minute: $('#minute')};
    Variables = { interactionFrequency: 15, minInteractionSize: 10, maxInteractionSize: 30 }
    Interactions = new Queue();

    // Events
    $('.info').on('tap', function(){
        // console.log(States.tappedInfoButton);
        if (States.tappedInfoButton)
        {
            $('#more-info').stop( true, true ).fadeOut( 400 );
            $('.info').removeClass('show');
            // console.log($('.info').attr("class").split(' '));
            States.tappedInfoButton  = false;
        }
        else{
            $('#more-info').stop( true, true ).fadeIn( "slow" );
            $('.info').addClass('show');
            // console.log($('.info').attr("class").split(' '));
            States.tappedInfoButton  = true;
        }
    });

    injectInteractionAnimationRule();
    Initialise();

    function Initialise()
    {
        // Pause state event listeners
        $(window).blur(function(){
            States.pageIsActive = false;
        });

        $(window).focus(function(event) {
           States.pageIsActive = true;
        });

        // Parse the data.
        Papa.parse("data/message_data.csv", {
            download: true,
            complete: function(results) {
                // Add every interaction to a Queue
                for (var i= 1; i < results.data.length - 1; i++)
                {
                        QueueInteraction((results.data[i]));
                }
                // Start the main logic.
                $('#loader-container').fadeOut( "slow" );
                $('#clock').fadeIn( "slow" );
                $('.info').fadeIn( "slow" );

                StartMusic();

                Main();
            }
        });
    }

    function Main()
    {
        // Infinite loop
        window.setInterval(function () {
            if (States.pageIsActive && !Interactions.isEmpty())
            {
                // Dequeue an interaction and activate it
                var interaction = Interactions.dequeue();
                ActivateInteraction(interaction);
            }
            else
            {
                // console.log('Paused');
            }
        }, Variables.interactionFrequency); // repeat forever, polling every 0.1 seconds
    }

    function ActivateInteraction(interaction)
    {
        // Update the time
        datetime = interaction.datetime;
        UpdateTimer(datetime);

        // Get animation properties
        var color = "background:" + interaction.color + ";";
        var sizeInt = getRandomInt(Variables.minInteractionSize, Variables.maxInteractionSize);
        var size = "height: " + sizeInt + "px; width: " + sizeInt + "px;";
        var topOffset = "top: " + getRandomInt(0,100) + "%;";
        var style = topOffset+color+size;

        // Create the animation with a self destruct
        $("

").appendTo('#interaction-container').one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function(){$(this).remove();});
    }

    function UpdateTimer(datetime)
    {
        ClockElements.year.text(datetime.substr(0, 4));
        ClockElements.month.text(datetime.substr(5, 2));
        ClockElements.day.text(datetime.substr(8, 2));
        ClockElements.hour.text(datetime.substr(11, 2));
        ClockElements.minute.text(datetime.substr(14, 2));
    }

    function Interaction(radius, speed, width, xPos, yPos, datetime, user_id, color) {
        this.radius = radius;
        this.speed = speed;
        this.width = width;
        this.xPos = xPos;
        this.yPos = yPos;
        this.datetime = datetime;
        this.user_id = user_id;
        this.color = color;
        this.opacity = .05 + Math.random() * .5;
    }

    function QueueInteraction(interaction_data) {

        var randomX = 0;
        var randomY = 0;
        var speed = 7;
        var size = 5 + Math.random() * 100;

        var interaction = new Interaction(
            10,
            speed,
            size,
            randomX,
            randomY,
            interaction_data[InteractionIndex.datetime],
            interaction_data[InteractionIndex.user_id],
            interaction_data[InteractionIndex.color]
        );

        Interactions.enqueue(interaction);
    }

    function getRandomInt(min, max) {
     return Math.round(Math.random() * (max - min + 1)) + min;
    }

    // I cant figure out how to dynamically set my transitions so this exists
    function injectInteractionAnimationRule() {
        var prefix = getVendorPrefix();
        var screenWidth = $( window ).width() * window.devicePixelRatio;
        var styleSheet = document.styleSheets[0];
        var name = 'implode'; // An animation has no selector but it does have a name...

        var ruleOutterTop = '@' + prefix + '-keyframes implode {'
        var ruleBody = '100% { ' + prefix + '-transform: translateX(' + screenWidth + 'px); transform: translateX(' + screenWidth +  'px); }'
        var ruleOutterBot = '}'

        var rule = ruleOutterTop + ruleBody + ruleOutterBot;

        var index = 0;
        if (styleSheet.rules) // chrome and safari
        {
            index = styleSheet.rules.length;
            styleSheet.insertRule(rule , index);
        }
        else if (styleSheet.cssRules) // firefox and IE
        {
            index = styleSheet.cssRules.length;
            styleSheet.insertRule(rule , index);
        }
        else
            alert('Something has gone wrong. \n\nI would really appreciate it if you emailed at ross.kinsella.ie@gmail.com \n\nWith your:\n - Browser and its version \n - The app you were looking at');
    }

    function getVendorPrefix () {
        var ua = navigator.userAgent.toLowerCase(),
            match = /opera/.exec(ua) || /msie/.exec(ua) || /firefox/.exec(ua) || /(chrome|safari)/.exec(ua),
            vendors = {
                opera: '-O',
                chrome: '-webkit',
                safari: '-webkit',
                firefox: '-Moz',
                msie: '-ms'
            };

        return vendors[match[0]];
    }

    // You cannot autoplay media for IOS.
    function StartMusic()
    {
        var iOS = ( navigator.userAgent.match(/(iPad|iPhone|iPod|Android)/g) ? true : false );
        if (iOS)
            $('#jack-credit').html('Visit here on a desktop device for a sweet song.');
        else
            $('#loader-container').append("");
    }

});<commit_msg>resizing remakes animation<commit_after>$(document).ready(function() {
    // Globals
    States = {pageIsActive: true, tappedInfoButton: false };
    InteractionIndex = {datetime: 0, user_id: 1, color: 2};
    ClockElements = { year: $('#year'), month: $('#month'), day: $('#day'), hour: $('#hour'), minute: $('#minute')};
    Variables = { interactionFrequency: 15, minInteractionSize: 10, maxInteractionSize: 30 }
    Interactions = new Queue();

    // Events
    $('.info').on('tap', function(){
        // console.log(States.tappedInfoButton);
        if (States.tappedInfoButton)
        {
            $('#more-info').stop( true, true ).fadeOut( 400 );
            $('.info').removeClass('show');
            // console.log($('.info').attr("class").split(' '));
            States.tappedInfoButton  = false;
        }
        else{
            $('#more-info').stop( true, true ).fadeIn( "slow" );
            $('.info').addClass('show');
            // console.log($('.info').attr("class").split(' '));
            States.tappedInfoButton  = true;
        }
    });

    $( window ).resize(function() {
        injectInteractionAnimationRule();
    });

    injectInteractionAnimationRule();
    Initialise();

    function Initialise()
    {
        // Pause state event listeners
        $(window).blur(function(){
            States.pageIsActive = false;
        });

        $(window).focus(function(event) {
           States.pageIsActive = true;
        });

        // Parse the data.
        Papa.parse("data/message_data.csv", {
            download: true,
            complete: function(results) {
                // Add every interaction to a Queue
                for (var i= 1; i < results.data.length - 1; i++)
                {
                        QueueInteraction((results.data[i]));
                }
                // Start the main logic.
                $('#loader-container').fadeOut( "slow" );
                $('#clock').fadeIn( "slow" );
                $('.info').fadeIn( "slow" );

                StartMusic();

                Main();
            }
        });
    }

    function Main()
    {
        // Infinite loop
        window.setInterval(function () {
            if (States.pageIsActive && !Interactions.isEmpty())
            {
                // Dequeue an interaction and activate it
                var interaction = Interactions.dequeue();
                ActivateInteraction(interaction);
            }
            else
            {
                // console.log('Paused');
            }
        }, Variables.interactionFrequency); // repeat forever, polling every 0.1 seconds
    }

    function ActivateInteraction(interaction)
    {
        // Update the time
        datetime = interaction.datetime;
        UpdateTimer(datetime);

        // Get animation properties
        var color = "background:" + interaction.color + ";";
        var sizeInt = getRandomInt(Variables.minInteractionSize, Variables.maxInteractionSize);
        var size = "height: " + sizeInt + "px; width: " + sizeInt + "px;";
        var topOffset = "top: " + getRandomInt(0,100) + "%;";
        var style = topOffset+color+size;

        // Create the animation with a self destruct
        $("

").appendTo('#interaction-container').one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function(){$(this).remove();});
    }

    function UpdateTimer(datetime)
    {
        ClockElements.year.text(datetime.substr(0, 4));
        ClockElements.month.text(datetime.substr(5, 2));
        ClockElements.day.text(datetime.substr(8, 2));
        ClockElements.hour.text(datetime.substr(11, 2));
        ClockElements.minute.text(datetime.substr(14, 2));
    }

    function Interaction(radius, speed, width, xPos, yPos, datetime, user_id, color) {
        this.radius = radius;
        this.speed = speed;
        this.width = width;
        this.xPos = xPos;
        this.yPos = yPos;
        this.datetime = datetime;
        this.user_id = user_id;
        this.color = color;
        this.opacity = .05 + Math.random() * .5;
    }

    function QueueInteraction(interaction_data) {

        var randomX = 0;
        var randomY = 0;
        var speed = 7;
        var size = 5 + Math.random() * 100;

        var interaction = new Interaction(
            10,
            speed,
            size,
            randomX,
            randomY,
            interaction_data[InteractionIndex.datetime],
            interaction_data[InteractionIndex.user_id],
            interaction_data[InteractionIndex.color]
        );

        Interactions.enqueue(interaction);
    }

    function getRandomInt(min, max) {
     return Math.round(Math.random() * (max - min + 1)) + min;
    }

    // I cant figure out how to dynamically set my transitions so this exists
    function injectInteractionAnimationRule() {
        var prefix = getVendorPrefix();
        var screenWidth = $( window ).width() * window.devicePixelRatio;
        var styleSheet = document.styleSheets[0];
        var name = 'implode'; // An animation has no selector but it does have a name...

        var ruleOutterTop = '@' + prefix + '-keyframes implode {'
        var ruleBody = '100% { ' + prefix + '-transform: translateX(' + screenWidth + 'px); transform: translateX(' + screenWidth +  'px); }'
        var ruleOutterBot = '}'

        var rule = ruleOutterTop + ruleBody + ruleOutterBot;

        var index = 0;
        if (styleSheet.rules) // chrome and safari
        {
            index = styleSheet.rules.length;
            styleSheet.insertRule(rule , index);
        }
        else if (styleSheet.cssRules) // firefox and IE
        {
            index = styleSheet.cssRules.length;
            styleSheet.insertRule(rule , index);
        }
        else
            alert('Something has gone wrong. \n\nI would really appreciate it if you emailed at ross.kinsella.ie@gmail.com \n\nWith your:\n - Browser and its version \n - The app you were looking at');
    }

    function getVendorPrefix () {
        var ua = navigator.userAgent.toLowerCase(),
            match = /opera/.exec(ua) || /msie/.exec(ua) || /firefox/.exec(ua) || /(chrome|safari)/.exec(ua),
            vendors = {
                opera: '-O',
                chrome: '-webkit',
                safari: '-webkit',
                firefox: '-Moz',
                msie: '-ms'
            };

        return vendors[match[0]];
    }

    // You cannot autoplay media for IOS.
    function StartMusic()
    {
        var iOS = ( navigator.userAgent.match(/(iPad|iPhone|iPod|Android)/g) ? true : false );
        if (iOS)
            $('#jack-credit').html('Visit here on a desktop device for a sweet song.');
        else
            $('#loader-container').append("");
    }

});<|endoftext|>


<commit_before>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });
var imageSrc;
$(document).ready(function(){
    imageSrc = $('#image').attr('src');
    //console.log(imageSrc);

    var doc = new jsPDF();
    var dataURL;
    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }

    };

    $('#pdf').click(function () {
        //image converet to base 64 open
        var imageUrl = $('#image').attr('src');
        var imageUrl1 = $('#image1').attr('src');
        var imageUrl2 = $('#image2').attr('src');
        var imageUrl3 = $('#image3').attr('src');

        var imageArr = [imageUrl,imageUrl1,imageUrl2,imageUrl3];
        var dataURLArr = [];
        var precount = imageArr.length;
        //trim the imageArray to remove undefined if less than 4 images.
        for(var i=0; i< precount; i++) {
            if(imageArr[i] == 'undefined' || imageArr[i] == null) {
                var index = imageArr.indexOf(imageArr[i]);
                if (index > -1) {
                    imageArr.splice(index, 1);
                }
            }
        }
        for (var i=0; i< imageArr.length; i++) {
            convertImgToBase64(imageArr[i], i); // pass index of current element
        }
            //createPdf();
            //console.log(dataURLArr[i] + "" + "" + "num" + i);

        //var data = $('#content-box').html();
        console.log('imageUrl', imageUrl);

        function convertImgToBase64(url, imageCount){
            var canvas = document.createElement('CANVAS');
            var ctx = canvas.getContext('2d');
            var img = new Image;
            img.crossOrigin = 'Anonymous';
            img.src = url;
            img.onload = function(){
                canvas.height = img.height;
                canvas.width = img.width;
                ctx.drawImage(img,0,0);
                dataURL = canvas.toDataURL('image/jpeg');
                dataURLArr.push(dataURL);
                if(imageCount == imageArr.length-1) { // check if it is last index of array
                    createPdf();
                }
                console.log('dataUrl',dataURL);
                //callback.call(this, dataURL);
                // Clean up
                canvas = null;
            };

        }
                // image convert base64 close
        function createPdf() {
            //console.log('dataUrl in createPdf',dataURL);
            if (dataURLArr.length > 0) {
                var doc = new jsPDF('p','pt','a4');
                //doc.setFontSize(14);
               // console.log(imageSrc);
                var imgData;
                for (var i=0; i<dataURLArr.length; i++) {
                    imgData = dataURLArr[i];
                   doc.addImage(imgData, 'JPEG', 25, 50*(i+1), 60, 80);
                }
                doc.fromHTML($('#content-data').html(), 80,30,  {
                    'width': 450,'elementHandlers': specialElementHandlers
                });
                doc.save('sample-file.pdf');
            }
        };
    });
});
<commit_msg>added content data id<commit_after>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });
var imageSrc;
$(document).ready(function(){
    imageSrc = $('#image').attr('src');
    //console.log(imageSrc);

    var doc = new jsPDF();
    var dataURL;
    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }

    };

    $('#pdf').click(function () {
        //image converet to base 64 open
        var imageUrl = $('#image').attr('src');
        var imageUrl1 = $('#image1').attr('src');
        var imageUrl2 = $('#image2').attr('src');
        var imageUrl3 = $('#image3').attr('src');

        var imageArr = [imageUrl,imageUrl1,imageUrl2,imageUrl3];
        var dataURLArr = [];
        var precount = imageArr.length;
        //trim the imageArray to remove undefined if less than 4 images.
        for(var i=0; i< precount; i++) {
            if(imageArr[i] == 'undefined' || imageArr[i] == null) {
                var index = imageArr.indexOf(imageArr[i]);
                if (index > -1) {
                    imageArr.splice(index, 1);
                }
            }
        }
        for (var i=0; i< imageArr.length; i++) {
            convertImgToBase64(imageArr[i], i); // pass index of current element
        }
            //createPdf();
            //console.log(dataURLArr[i] + "" + "" + "num" + i);

        //var data = $('#content-box').html();
        console.log('imageUrl', imageUrl);

        function convertImgToBase64(url, imageCount){
            var canvas = document.createElement('CANVAS');
            var ctx = canvas.getContext('2d');
            var img = new Image;
            img.crossOrigin = 'Anonymous';
            img.src = url;
            img.onload = function(){
                canvas.height = img.height;
                canvas.width = img.width;
                ctx.drawImage(img,0,0);
                dataURL = canvas.toDataURL('image/jpeg');
                dataURLArr.push(dataURL);
                if(imageCount == imageArr.length-1) { // check if it is last index of array
                    createPdf();
                }
                console.log('dataUrl',dataURL);
                //callback.call(this, dataURL);
                // Clean up
                canvas = null;
            };

        }
                // image convert base64 close
        function createPdf() {
            //console.log('dataUrl in createPdf',dataURL);
            if (dataURLArr.length > 0) {
                var doc = new jsPDF('p','pt','a4');
                //doc.setFontSize(14);
               // console.log(imageSrc);
                var imgData;
                for (var i=0; i<dataURLArr.length; i++) {
                    imgData = dataURLArr[i];
                   doc.addImage(imgData, 'JPEG', 25, 40*(i+1), 60, 80);
                }
                doc.fromHTML($('#content-data').html(), 80,30,  {
                    'width': 450,'elementHandlers': specialElementHandlers
                });
                doc.save('sample-file.pdf');
            }
        };
    });
});
<|endoftext|>


<commit_before>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });

    $(document).ready(function(){

        //console.log(imageSrc);

        var doc = new jsPDF();

        doc.setFontSize(40);
        doc.text(35, 25, "Octonyan loves jsPDF");

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#pdf').click(function () {
        var imageSrc = $('#image').attr('src');
        var doc = new jsPDF();

        doc.addImage(imageSrc, 'JPEG', 15, 40, 180, 180);
        doc.fromHTML($('#content-box').html(), 15, 15, {
            'width': 170,'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });
});

      $(function() {
    $("#message").on('click', function() {
        alert("asdfasdf");
       // $.message("#formdata");
    });
     });  <commit_msg>added pages<commit_after>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });

    $(document).ready(function(){

        //console.log(imageSrc);

        var doc = new jsPDF();

        doc.setFontSize(40);
        doc.text(35, 25, "Octonyan loves jsPDF");

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#pdf').click(function () {
        var imageSrc = $('#image').attr('src');
        var doc = new jsPDF();

        doc.setFontSize(40);
        doc.text(35, 25, "Octonyan loves jsPDF");
        doc.addImage(imageSrc, 'PNG', 15, 40, 180, 180);
        // doc.fromHTML($('#content-box').html(), 15, 15, {
        //     'width': 170,'elementHandlers': specialElementHandlers
        // });
        doc.save('sample-file.pdf');
    });
});

      $(function() {
    $("#message").on('click', function() {
        alert("asdfasdf");
       // $.message("#formdata");
    });
     });  <|endoftext|>


<commit_before>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });

    $(document).ready(function(){

        //console.log(imageSrc);

        var doc = new jsPDF();

        doc.setFontSize(40);
        doc.text(35, 25, "Octonyan loves jsPDF");

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#pdf').click(function () {
        var imageSrc = $('#image').attr('src');
        var doc = new jsPDF();

        doc.addImage(imageSrc, 'JPEG', 15, 40, 180, 180);
        doc.fromHTML($('#image').html(), 15, 15, {
            'width': 170,'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });
});

      $(function() {
    $("#message").on('click', function() {
        alert("asdfasdf");
       // $.message("#formdata");
    });
     });  <commit_msg>added files<commit_after>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });

    $(document).ready(function(){

        //console.log(imageSrc);

        var doc = new jsPDF();

        doc.setFontSize(40);
        doc.text(35, 25, "Octonyan loves jsPDF");

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#pdf').click(function () {
        var imageSrc = $('#image').attr('src');
        var doc = new jsPDF();

        doc.addImage(imageSrc, 'JPEG', 15, 40, 180, 180);
        doc.fromHTML($('#content-box').html(), 15, 15, {
            'width': 170,'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });
});

      $(function() {
    $("#message").on('click', function() {
        alert("asdfasdf");
       // $.message("#formdata");
    });
     });  <|endoftext|>


<commit_before>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });
var imageSrc;
$(document).ready(function(){
    imageSrc = $('#image').attr('src');
    //console.log(imageSrc);

    var doc = new jsPDF();
    var dataURL;
    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };

    $('#pdf').click(function () {
        //image converet to base 64 open
        var imageUrl = $('#image').attr('src');
        var imageUrl1 = $('#image1').attr('src');
        var imageUrl2 = $('#image2').attr('src');
        var imageUrl3 = $('#image3').attr('src');
        var imageArr = [imageUrl,imageUrl1,imageUrl2,imageUrl3];
        var dataURLArr = [];
        for(var i=0; i< imageArr.length; i++) {
            convertImgToBase64(imageArr[i]);
            if(i==imageArr.length-1) {
                createPdf();
            }
            //console.log(dataURLArr[i] + "" + "" + "num" + i);
        }

        //var data = $('#content-box').html();
        console.log('imageUrl', imageUrl);

        function convertImgToBase64(url, callback, outputFormat){
            var canvas = document.createElement('CANVAS');
            var ctx = canvas.getContext('2d');
            var img = new Image;
            img.crossOrigin = 'Anonymous';
            img.src = url;
            img.onload = function(){
                canvas.height = img.height;
                canvas.width = img.width;
                ctx.drawImage(img,0,0);
                dataURL = canvas.toDataURL(outputFormat || 'image/jpeg');
                dataURLArr.push(dataURL);
                //createPdf();
                console.log('dataUrl',dataURL);
                //callback.call(this, dataURL);
                // Clean up
                canvas = null;
            };

        }
                // image convert base64 close
        function createPdf() {
            //console.log('dataUrl in createPdf',dataURL);
            if (dataURLArr.length > 0) {
                var doc = new jsPDF();
               // console.log(imageSrc);
                var imgData;
                for (var i=0; i<dataURLArr.length; i++) {
                    imgData = dataURLArr[i];
                    doc.addImage(imgData, 'JPEG', 15*(i+1), 15*(i+1), 40, 40);
                }
                doc.fromHTML($('#content-box').html(), 15, 15, {
                    'width': 170,'elementHandlers': specialElementHandlers
                });
                doc.save('sample-file.pdf');
            }
                           // doc.setFontSize(40);
            //doc.text(10, 20, data);
        };
        ///if (dataURLArr.length > 0) {

        //}
    });
});
<commit_msg>added data<commit_after>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });
var imageSrc;
$(document).ready(function(){
    imageSrc = $('#image').attr('src');
    //console.log(imageSrc);

    var doc = new jsPDF();
    var dataURL;
    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };

    $('#pdf').click(function () {
        //image converet to base 64 open
        var imageUrl = $('#image').attr('src');
        var imageUrl1 = $('#image1').attr('src');
        var imageUrl2 = $('#image2').attr('src');
        var imageUrl3 = $('#image3').attr('src');
        var imageArr = [imageUrl,imageUrl1,imageUrl2,imageUrl3];
        var dataURLArr = [];
        for(var i=0; i< imageArr.length; i++) {
            convertImgToBase64(imageArr[i], i);
            //createPdf();
            //console.log(dataURLArr[i] + "" + "" + "num" + i);
        }

        //var data = $('#content-box').html();
        console.log('imageUrl', imageUrl);

        function convertImgToBase64(url, imageCount){
            var canvas = document.createElement('CANVAS');
            var ctx = canvas.getContext('2d');
            var img = new Image;
            img.crossOrigin = 'Anonymous';
            img.src = url;
            img.onload = function(){
                canvas.height = img.height;
                canvas.width = img.width;
                ctx.drawImage(img,0,0);
                dataURL = canvas.toDataURL(outputFormat || 'image/jpeg');
                dataURLArr.push(dataURL);
                if(imageCount == 3) {
                    createPdf();
                }
                console.log('dataUrl',dataURL);
                //callback.call(this, dataURL);
                // Clean up
                canvas = null;
            };

        }
                // image convert base64 close
        function createPdf() {
            //console.log('dataUrl in createPdf',dataURL);
            if (dataURLArr.length > 0) {
                var doc = new jsPDF();
               // console.log(imageSrc);
                var imgData;
                for (var i=0; i<dataURLArr.length; i++) {
                    imgData = dataURLArr[i];
                    doc.addImage(imgData, 'JPEG', 15*(i+1), 15*(i+1), 40, 40);
                }
                doc.fromHTML($('#content-box').html(), 15, 15, {
                    'width': 170,'elementHandlers': specialElementHandlers
                });
                doc.save('sample-file.pdf');
            }
                           // doc.setFontSize(40);
            //doc.text(10, 20, data);
        };
        ///if (dataURLArr.length > 0) {

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


<commit_before>/*
 * L.Routing main class
 *
 * Main clase for the Leaflet routing module
 *
 * @dependencies L
 *
 * @usage new L.Routing(options);
 *
 * @todo use L.Class.extend instead?
*/

L.Routing = L.Control.extend({

  // INCLUDES
  includes: [L.Mixin.Events]

  // CONSTANTS
  ,statics: {
    VERSION: '0.0.2-dev'
  }

  // OPTIONS
  ,options: {
    position: 'topleft'
    ,icons: {
      start: new L.Icon.Default()
      ,end: new L.Icon.Default()
      ,normal: new L.Icon.Default()
    }
    ,zIndexOffset: 2000
    ,routing: {
      router: null       // function (<L.Latlng> l1, <L.Latlng> l2, <Function> cb)
    }
    ,snapping: {
      layers: []         // layers to snap to
      ,sensitivity: 10   // snapping sensitivity
      ,vertexonly: false // vertex only snapping
    }
  }

  /**
   * Routing Constructor
   *
   * @access public
   *
   * @param <Object> options - non-default options
   *
   * @todo render display of segments and waypoints
  */
  ,initialize: function (options) {
    this._editing = false;
    this._drawing = false;

    L.Util.setOptions(this, options);
  }

  /**
   * Called when controller is added to map
   *
   * @access public
   *
   * @param <L.Map> map - map instance
   *
   * @return <HTMLElement> container
  */
  ,onAdd: function (map) {
    this._map         = map;
    this._container   = this._map._container;
    this._overlayPane = this._map._panes.overlayPane;
    this._popupPane   = this._map._panes.popupPane;

    this._router      = this.options.routing.router;
    this._segments    = new L.FeatureGroup().addTo(map);
    this._waypoints   = new L.FeatureGroup().addTo(map);
    this._waypoints._first = null;
    this._waypoints._last = null;

    //L.DomUtil.disableTextSelection();
    //this._tooltip = new L.Tooltip(this._map);
    //this._tooltip.updateContent({ text: L.drawLocal.draw.marker.tooltip.start });
    L.DomEvent.addListener(this._container, 'keyup', this._keyupListener, this);

    this._draw = new L.Routing.Draw(this, {
      icons: this.options.icons
      ,zIndexOffset: this.options.zIndexOffset
      ,snapping: this.options.snapping
    });

    this._edit = new L.Routing.Edit(this, {
      icons: this.options.icons
      ,zIndexOffset: this.options.zIndexOffset
      ,snapping: this.options.snapping
    });
    this._edit.enable();

    this.on('waypoint:click', this._waypointClickHandler, this)
    this._segments.on('mouseover'    , this._fireSegmentEvent, this);
    this._edit.on('segment:mouseout' , this._fireSegmentEvent, this);
    this._edit.on('segment:dragstart', this._fireSegmentEvent, this);
    this._edit.on('segment:dragend'  , this._fireSegmentEvent, this);

    var container = L.DomUtil.create('div', 'leaflet-routing');

    return container;
  }

  /**
   * Called when controller is removed from map
   *
   * @access public
   *
   * @param <L.Map> map - map instance
  */
  ,onRemove: function(map) {
    //L.DomUtil.create('div', 'leaflet-routing'); <= delete this

    this.off('waypoint:click', this._waypointClickHandler, this)
    this._segments.off('mouseover'    , this._fireSegmentEvent, this);
    this._edit.off('segment:mouseout' , this._fireSegmentEvent, this);
    this._edit.off('segment:dragstart', this._fireSegmentEvent, this);
    this._edit.off('segment:dragend'  , this._fireSegmentEvent, this);

    this._edit.disable();
    this._draw.disable();

    L.DomUtil.enableTextSelection();
    // this._tooltip.dispose();
    // this._tooltip = null;
    L.DomEvent.removeListener(this._container, 'keyup', this._keyupListener);

    delete this._draw;
    delete this._edit;
    delete this._map;
    delete this._router;
    delete this._segments;
    delete this._waypoints;
    delete this.options;
  }

  ,_waypointClickHandler: function(e) {
    this.removeWaypoint(e.marker, function() {
      console.log(arguments);
    });
  }

  /**
   * Add new waypoint to path
   *
   * @access public
   *
   * @param <L.Marker> marker - new waypoint marker (can be ll)
   * @param <L.Marker> prev - previous waypoint marker
   * @param <L.Marker> next - next waypoint marker
   * @param <Function> cb - callback method
   *
   * @return void
  */
  ,addWaypoint: function(marker, prev, next, cb) {
    if (marker instanceof L.LatLng) {
      marker = new L.Marker(marker);
    }

    marker._routing = {
      prevMarker  : prev
      ,nextMarker : next
      ,prevLine   : null
      ,nextLine   : null
      ,timeoutID  : null
    };

    if (this._waypoints._first === null && this._waypoints._last === null) {
      this._waypoints._first = marker;
      this._waypoints._last = marker;
    } else if (next === null) {
      this._waypoints._last = marker;
    } else if (prev === null) {
      this._waypoints._first = marker;
    }

    if (marker._routing.prevMarker !== null) {
      marker._routing.prevMarker._routing.nextMarker = marker;
      marker._routing.prevLine = marker._routing.prevMarker._routing.nextLine;
      if (marker._routing.prevLine !== null) {
        marker._routing.prevLine._routing.nextMarker = marker;
      }
    }

    if (marker._routing.nextMarker !== null) {
      marker._routing.nextMarker._routing.prevMarker = marker;
      marker.nextLine = marker._routing.nextMarker._routing.prevLine;
      if (marker._routing.nextLine !== null) {
        marker._routing.nextLine._routing.prevMarker = marker;
      }
    }

    marker.on('mouseover', this._fireWaypointEvent, this);
    marker.on('mouseout' , this._fireWaypointEvent, this);
    marker.on('dragstart', this._fireWaypointEvent, this);
    marker.on('dragend'  , this._fireWaypointEvent, this);
    marker.on('drag'     , this._fireWaypointEvent, this);
    marker.on('click'    , this._fireWaypointEvent, this);

    this.routeWaypoint(marker, cb);
    this._waypoints.addLayer(marker);
    marker.dragging.enable();
  }

  /**
   * Remove a waypoint from path
   *
   * @access public
   *
   * @param <L.Marker> marker - new waypoint marker (can be ll)
   * @param <Function> cb - callback method
   *
   * @return void
  */
  ,removeWaypoint: function(marker, cb) {
    marker.off('mouseover', this._fireWaypointEvent, this);
    marker.off('mouseout' , this._fireWaypointEvent, this);
    marker.off('dragstart', this._fireWaypointEvent, this);
    marker.off('dragend'  , this._fireWaypointEvent, this);
    marker.off('drag'     , this._fireWaypointEvent, this);
    marker.off('click'    , this._fireWaypointEvent, this);

    var prev = marker._routing.prevMarker;
    var next = marker._routing.nextMarker;

    if (this._waypoints._first && marker._leaflet_id === this._waypoints._first._leaflet_id) {
      this._waypoints._first = next;
    }

    if (this._waypoints._last && marker._leaflet_id === this._waypoints._last._leaflet_id) {
      this._waypoints._last = prev;
    }

    if (prev !== null) {
      prev._routing.nextMarker = next;
      prev._routing.nextLine = null;
    }

    if (next !== null) {
      next._routing.prevMarker = prev;
      next._routing.prevLine = null;
    }

    if (marker._routing.nextLine !== null) {
      this._segments.removeLayer(marker._routing.nextLine);
    }

    if (marker._routing.prevLine !== null) {
      this._segments.removeLayer(marker._routing.prevLine);
    }

    this._waypoints.removeLayer(marker);

    if (prev !== null) {
      this.routeWaypoint(prev, cb);
    } else if (next !== null) {
      this.routeWaypoint(next, cb);
    } else {
      this._draw.enable();
      cb(null, null);
    }

  }

  /**
   * Route with respect to waypoint
   *
   * @access public
   *
   * @param <L.Marker> marker - marker to route on
   * @param <Function> cb - callback function
   *
   * @return void
   *
   * @todo add propper error checking for callback
  */
  ,routeWaypoint: function(marker, cb) {
    var i = 0;
    var callback = function(err, data) {
      i++;
      if (i === 2) {
        cb(err, marker);
      }
    }

    this._routeSegment(marker._routing.prevMarker, marker, callback);
    this._routeSegment(marker, marker._routing.nextMarker, callback);
  }

  /**
   * Route segment between two markers
   *
   * @access private
   *
   * @param <L.Marker> m1 - first waypoint marker
   * @param <L.Marker> m2 - second waypoint marker
   * @param <Function> cb - callback function (<Error> err, <String> data)
   *
   * @return void
   *
   * @todo logic if router fails
  */
  ,_routeSegment: function(m1, m2, cb) {
    var $this = this;

    if (m1 === null || m2 === null) {
      return cb(null, true);
    }

    this._router(m1.getLatLng(), m2.getLatLng(), function(err, layer) {
      if (typeof layer === 'undefined') {
        var layer = new L.Polyline([m1.getLatLng(), m2.getLatLng()]);
      }

      layer._routing = {
        prevMarker: m1
        ,nextMarker: m2
      };

      if (m1._routing.nextLine !== null) {
        $this._segments.removeLayer(m1._routing.nextLine);
      }
      $this._segments.addLayer(layer);

      m1._routing.nextLine = layer;
      m2._routing.prevLine = layer;

      return cb(null, layer);
    });
  }

  /**
   * Fire events
   *
   * @access private
   *
   * @param <L.Event> e - mouse event
   *
   * @return void
  */
  ,_fireWaypointEvent: function(e) {
    this.fire('waypoint:' + e.type, {marker:e.target});
  }

  /**
   *
  */
  ,_fireSegmentEvent: function(e) {
    if (e.type.split(':').length === 2) {
      this.fire(e.type);
    } else {
      this.fire('segment:' + e.type);
    }
  }

  /**
   * Get first waypoint
   *
   * @access public
   *
   * @return L.Marker
  */
  ,getFirst: function() {
    return this._waypoints._first;
  }

  /**
   * Get last waypoint
   *
   * @access public
   *
   * @return L.Marker
  */
  ,getLast: function() {
    return this._waypoints._last;
  }

  /**
   * Export route to GeoJSON
   *
   * @access public
   *
   * @return {@code object} GeoJSON object
   *
  */
  ,toGeoJSON: function() {
    var geojson = {type: "LineString", properties: {waypoints: []}, coordinates: []};
    var current = this._waypoints._first;

    if (current === null) { return geojson; }

    geojson.properties.waypoints.push([current.getLatLng().lng, current.getLatLng().lat]);

    while (current._routing.nextMarker) {
      var next = current._routing.nextMarker
      geojson.properties.waypoints.push([next.getLatLng().lng, next.getLatLng().lat]);

      var tmp = current._routing.nextLine.getLatLngs();
      for (var i = 0; i < tmp.length; i++) {
        if (tmp[i].alt) {
          geojson.coordinates.push(tmp[i].lng, tmp[i].lat, tmp[i].alt);
        } else {
          geojson.coordinates.push(tmp[i].lng, tmp[i].lat);
        }
      }

      current = current._routing.nextMarker;
    }

    return geojson
  }

  /**
   * Start (or continue) drawing
   *
   * Call this method in order to start or continue drawing. The drawing handler
   * will be activate and the user can draw on the map.
   *
   * @access public
   *
   * @return void
   *
   * @todo check enable
  */
  ,draw: function (enable) {
    if (typeof enable === 'undefined') {
      var enable = true;
    }

    if (enable) {
      this._draw.enable();
    } else {
      this._draw.disable();
    }
  }

  /**
   * Enable or disable routing
   *
   * @access public
   *
   * @return void
   *
   * @todo check enable
  */
  ,routing: function (enable) {
    throw new Error('Not implemented');
  }

  /**
   * Enable or disable snapping
   *
   * @access public
   *
   * @return void
   *
   * @todo check enable
  */
  ,snapping: function (enable) {
    throw new Error('Not implemented');
  }

    /**
   * Key up listener
   *
   * * `ESC` to cancel drawing
   * * `M` to enable drawing
   *
   * @access private
   *
   * @return void
  */
  ,_keyupListener: function (e) {
    if (e.keyCode === 27) {
      this._draw.disable();
    } else if (e.keyCode === 77) {
      this._draw.enable();
    }
  }

});
<commit_msg>New L.Routing.js-file - bugfix<commit_after>/*
 * L.Routing main class
 *
 * Main clase for the Leaflet routing module
 *
 * @dependencies L
 *
 * @usage new L.Routing(options);
 *
 * @todo use L.Class.extend instead?
*/

L.Routing = L.Control.extend({

  // INCLUDES
  includes: [L.Mixin.Events]

  // CONSTANTS
  ,statics: {
    VERSION: '0.0.2-dev'
  }

  // OPTIONS
  ,options: {
    position: 'topleft'
    ,icons: {
      start: new L.Icon.Default()
      ,end: new L.Icon.Default()
      ,normal: new L.Icon.Default()
    }
    ,zIndexOffset: 2000
    ,routing: {
      router: null       // function (<L.Latlng> l1, <L.Latlng> l2, <Function> cb)
    }
    ,snapping: {
      layers: []         // layers to snap to
      ,sensitivity: 10   // snapping sensitivity
      ,vertexonly: false // vertex only snapping
    }
  }

  /**
   * Routing Constructor
   *
   * @access public
   *
   * @param <Object> options - non-default options
   *
   * @todo render display of segments and waypoints
  */
  ,initialize: function (options) {
    this._editing = false;
    this._drawing = false;

    L.Util.setOptions(this, options);
  }

  /**
   * Called when controller is added to map
   *
   * @access public
   *
   * @param <L.Map> map - map instance
   *
   * @return <HTMLElement> container
  */
  ,onAdd: function (map) {
    this._map         = map;
    this._container   = this._map._container;
    this._overlayPane = this._map._panes.overlayPane;
    this._popupPane   = this._map._panes.popupPane;

    this._router      = this.options.routing.router;
    this._segments    = new L.FeatureGroup().addTo(map);
    this._waypoints   = new L.FeatureGroup().addTo(map);
    this._waypoints._first = null;
    this._waypoints._last = null;

    //L.DomUtil.disableTextSelection();
    //this._tooltip = new L.Tooltip(this._map);
    //this._tooltip.updateContent({ text: L.drawLocal.draw.marker.tooltip.start });
    L.DomEvent.addListener(this._container, 'keyup', this._keyupListener, this);

    this._draw = new L.Routing.Draw(this, {
      icons: this.options.icons
      ,zIndexOffset: this.options.zIndexOffset
      ,snapping: this.options.snapping
    });

    this._edit = new L.Routing.Edit(this, {
      icons: this.options.icons
      ,zIndexOffset: this.options.zIndexOffset
      ,snapping: this.options.snapping
    });
    this._edit.enable();

    this.on('waypoint:click', this._waypointClickHandler, this)
    this._segments.on('mouseover'    , this._fireSegmentEvent, this);
    this._edit.on('segment:mouseout' , this._fireSegmentEvent, this);
    this._edit.on('segment:dragstart', this._fireSegmentEvent, this);
    this._edit.on('segment:dragend'  , this._fireSegmentEvent, this);

    var container = L.DomUtil.create('div', 'leaflet-routing');

    return container;
  }

  /**
   * Called when controller is removed from map
   *
   * @access public
   *
   * @param <L.Map> map - map instance
  */
  ,onRemove: function(map) {
    //L.DomUtil.create('div', 'leaflet-routing'); <= delete this

    this.off('waypoint:click', this._waypointClickHandler, this)
    this._segments.off('mouseover'    , this._fireSegmentEvent, this);
    this._edit.off('segment:mouseout' , this._fireSegmentEvent, this);
    this._edit.off('segment:dragstart', this._fireSegmentEvent, this);
    this._edit.off('segment:dragend'  , this._fireSegmentEvent, this);

    this._edit.disable();
    this._draw.disable();

    L.DomUtil.enableTextSelection();
    // this._tooltip.dispose();
    // this._tooltip = null;
    L.DomEvent.removeListener(this._container, 'keyup', this._keyupListener);

    delete this._draw;
    delete this._edit;
    delete this._map;
    delete this._router;
    delete this._segments;
    delete this._waypoints;
    delete this.options;
  }

  ,_waypointClickHandler: function(e) {
    this.removeWaypoint(e.marker, function() {
      console.log(arguments);
    });
  }

  /**
   * Add new waypoint to path
   *
   * @access public
   *
   * @param <L.Marker> marker - new waypoint marker (can be ll)
   * @param <L.Marker> prev - previous waypoint marker
   * @param <L.Marker> next - next waypoint marker
   * @param <Function> cb - callback method
   *
   * @return void
  */
  ,addWaypoint: function(marker, prev, next, cb) {
    if (marker instanceof L.LatLng) {
      marker = new L.Marker(marker);
    }

    marker._routing = {
      prevMarker  : prev
      ,nextMarker : next
      ,prevLine   : null
      ,nextLine   : null
      ,timeoutID  : null
    };

    if (this._waypoints._first === null && this._waypoints._last === null) {
      this._waypoints._first = marker;
      this._waypoints._last = marker;
    } else if (next === null) {
      this._waypoints._last = marker;
    } else if (prev === null) {
      this._waypoints._first = marker;
    }

    if (marker._routing.prevMarker !== null) {
      marker._routing.prevMarker._routing.nextMarker = marker;
      marker._routing.prevLine = marker._routing.prevMarker._routing.nextLine;
      if (marker._routing.prevLine !== null) {
        marker._routing.prevLine._routing.nextMarker = marker;
      }
    }

    if (marker._routing.nextMarker !== null) {
      marker._routing.nextMarker._routing.prevMarker = marker;
      marker.nextLine = marker._routing.nextMarker._routing.prevLine;
      if (marker._routing.nextLine !== null) {
        marker._routing.nextLine._routing.prevMarker = marker;
      }
    }

    marker.on('mouseover', this._fireWaypointEvent, this);
    marker.on('mouseout' , this._fireWaypointEvent, this);
    marker.on('dragstart', this._fireWaypointEvent, this);
    marker.on('dragend'  , this._fireWaypointEvent, this);
    marker.on('drag'     , this._fireWaypointEvent, this);
    marker.on('click'    , this._fireWaypointEvent, this);

    this.routeWaypoint(marker, cb);
    this._waypoints.addLayer(marker);
    marker.dragging.enable();
  }

  /**
   * Remove a waypoint from path
   *
   * @access public
   *
   * @param <L.Marker> marker - new waypoint marker (can be ll)
   * @param <Function> cb - callback method
   *
   * @return void
  */
  ,removeWaypoint: function(marker, cb) {
    marker.off('mouseover', this._fireWaypointEvent, this);
    marker.off('mouseout' , this._fireWaypointEvent, this);
    marker.off('dragstart', this._fireWaypointEvent, this);
    marker.off('dragend'  , this._fireWaypointEvent, this);
    marker.off('drag'     , this._fireWaypointEvent, this);
    marker.off('click'    , this._fireWaypointEvent, this);

    var prev = marker._routing.prevMarker;
    var next = marker._routing.nextMarker;

    if (this._waypoints._first && marker._leaflet_id === this._waypoints._first._leaflet_id) {
      this._waypoints._first = next;
    }

    if (this._waypoints._last && marker._leaflet_id === this._waypoints._last._leaflet_id) {
      this._waypoints._last = prev;
    }

    if (prev !== null) {
      prev._routing.nextMarker = next;
      prev._routing.nextLine = null;
    }

    if (next !== null) {
      next._routing.prevMarker = prev;
      next._routing.prevLine = null;
    }

    if (marker._routing.nextLine !== null) {
      this._segments.removeLayer(marker._routing.nextLine);
    }

    if (marker._routing.prevLine !== null) {
      this._segments.removeLayer(marker._routing.prevLine);
    }

    this._waypoints.removeLayer(marker);

    if (prev !== null) {
      this.routeWaypoint(prev, cb);
    } else if (next !== null) {
      this.routeWaypoint(next, cb);
    } else {
      this._draw.enable();
      cb(null, null);
    }

  }

  /**
   * Route with respect to waypoint
   *
   * @access public
   *
   * @param <L.Marker> marker - marker to route on
   * @param <Function> cb - callback function
   *
   * @return void
   *
   * @todo add propper error checking for callback
  */
  ,routeWaypoint: function(marker, cb) {
    var i = 0;
    var callback = function(err, data) {
      i++;
      if (i === 2) {
        cb(err, marker);
      }
    }

    this._routeSegment(marker._routing.prevMarker, marker, callback);
    this._routeSegment(marker, marker._routing.nextMarker, callback);
  }

  /**
   * Route segment between two markers
   *
   * @access private
   *
   * @param <L.Marker> m1 - first waypoint marker
   * @param <L.Marker> m2 - second waypoint marker
   * @param <Function> cb - callback function (<Error> err, <String> data)
   *
   * @return void
   *
   * @todo logic if router fails
  */
  ,_routeSegment: function(m1, m2, cb) {
    var $this = this;

    if (m1 === null || m2 === null) {
      return cb(null, true);
    }

    this._router(m1.getLatLng(), m2.getLatLng(), function(err, layer) {
      if (typeof layer === 'undefined') {
        var layer = new L.Polyline([m1.getLatLng(), m2.getLatLng()]);
      }

      layer._routing = {
        prevMarker: m1
        ,nextMarker: m2
      };

      if (m1._routing.nextLine !== null) {
        $this._segments.removeLayer(m1._routing.nextLine);
      }
      $this._segments.addLayer(layer);

      m1._routing.nextLine = layer;
      m2._routing.prevLine = layer;

      return cb(null, layer);
    });
  }

  /**
   * Fire events
   *
   * @access private
   *
   * @param <L.Event> e - mouse event
   *
   * @return void
  */
  ,_fireWaypointEvent: function(e) {
    this.fire('waypoint:' + e.type, {marker:e.target});
  }

  /**
   *
  */
  ,_fireSegmentEvent: function(e) {
    if (e.type.split(':').length === 2) {
      this.fire(e.type);
    } else {
      this.fire('segment:' + e.type);
    }
  }

  /**
   * Get first waypoint
   *
   * @access public
   *
   * @return L.Marker
  */
  ,getFirst: function() {
    return this._waypoints._first;
  }

  /**
   * Get last waypoint
   *
   * @access public
   *
   * @return L.Marker
  */
  ,getLast: function() {
    return this._waypoints._last;
  }

  /**
   * Export route to GeoJSON
   *
   * @access public
   *
   * @return {@code object} GeoJSON object
   *
  */
  ,toGeoJSON: function() {
    var geojson = {type: "LineString", properties: {waypoints: []}, coordinates: []};
    var current = this._waypoints._first;

    if (current === null) { return geojson; }

    geojson.properties.waypoints.push([current.getLatLng().lng, current.getLatLng().lat]);

    while (current._routing.nextMarker) {
      var next = current._routing.nextMarker
      geojson.properties.waypoints.push([next.getLatLng().lng, next.getLatLng().lat]);

      var tmp = current._routing.nextLine.getLatLngs();
      for (var i = 0; i < tmp.length; i++) {
        if (tmp[i].alt) {
          geojson.coordinates.push([tmp[i].lng, tmp[i].lat, tmp[i].alt]);
        } else {
          geojson.coordinates.push([tmp[i].lng, tmp[i].lat]);
        }
      }

      current = current._routing.nextMarker;
    }

    return geojson
  }

  /**
   * Start (or continue) drawing
   *
   * Call this method in order to start or continue drawing. The drawing handler
   * will be activate and the user can draw on the map.
   *
   * @access public
   *
   * @return void
   *
   * @todo check enable
  */
  ,draw: function (enable) {
    if (typeof enable === 'undefined') {
      var enable = true;
    }

    if (enable) {
      this._draw.enable();
    } else {
      this._draw.disable();
    }
  }

  /**
   * Enable or disable routing
   *
   * @access public
   *
   * @return void
   *
   * @todo check enable
  */
  ,routing: function (enable) {
    throw new Error('Not implemented');
  }

  /**
   * Enable or disable snapping
   *
   * @access public
   *
   * @return void
   *
   * @todo check enable
  */
  ,snapping: function (enable) {
    throw new Error('Not implemented');
  }

    /**
   * Key up listener
   *
   * * `ESC` to cancel drawing
   * * `M` to enable drawing
   *
   * @access private
   *
   * @return void
  */
  ,_keyupListener: function (e) {
    if (e.keyCode === 27) {
      this._draw.disable();
    } else if (e.keyCode === 77) {
      this._draw.enable();
    }
  }

});
<|endoftext|>


<commit_before>'use strict';

//style for the map
var mapOptions = {
  zoom: 12,
  styles: '#',
  center: new google.maps.LatLng(47.618217, -122.351832),
  mapTypeId: google.maps.MapTypeId.STREET,
  zoomControl: true,
  zoomControlOptions: {
    position: google.maps.ControlPosition.RIGHT_CENTER
  }
}

// launches the map
let map = new google.maps.Map(document.getElementById('map'), mapOptions);

var markers = [];

// start of marker clusters
function initMap(concerts) {

  let noteIcon = $('#style-selector').val() === 'dark-mode' || $('#style-selector').val() === 'night-mode' ? '/img/note-icon.png' : '/img/dark-note-icon.png';

  // trying to delete markers
  markers.forEach(function(m) { m.setMap(null); m = null; });
  // starting the spiderfier library to assist with identical location markers.
  let oms = new OverlappingMarkerSpiderfier(map, {
    markersWontMove: true,
    markersWontHide: true,
    basicFormatEvents: true
  });
  // builds the markers based on the user form input.
  markers = concerts.map(function(concert){
    let locations = {lat: parseFloat(concert.venueLat), lng: parseFloat(concert.venueLong)};
    let marker = new google.maps.Marker({
      position: locations,
      icon: noteIcon,
      animation: google.maps.Animation.DROP,
      visible: locations.lat !== 0 && locations.lng !== 0
    });
    //builds the info window when the user clicks on the location marker
    let windowContent = `
Event: ${concert.name}
Date: ${concert.date}
Time: ${concert.time}
Venue: ${concert.venue}
Click to Buy Tickets
`
    let infoWindow = new google.maps.InfoWindow({
      content: windowContent
    });
    google.maps.event.addListener(marker, 'spider_click', function(e){
      infoWindow.open(map, marker);
    });
    oms.addMarker(marker);
    return marker
  });
}
<commit_msg>added in resizing listener for map.<commit_after>'use strict';

//style for the map
var mapOptions = {
  zoom: 12,
  styles: '#',
  center: new google.maps.LatLng(47.618217, -122.351832),
  mapTypeId: google.maps.MapTypeId.STREET,
  zoomControl: true,
  zoomControlOptions: {
    position: google.maps.ControlPosition.RIGHT_CENTER
  }
}

// launches the map
let map = new google.maps.Map(document.getElementById('map'), mapOptions);

google.maps.event.addDomListener(window, 'resize', function() {
  var center = map.getCenter();
  google.maps.event.trigger(map, 'resize');
  map.setCenter(center);
});

var markers = [];

// start of marker clusters
function initMap(concerts) {

  let noteIcon = $('#style-selector').val() === 'dark-mode' || $('#style-selector').val() === 'night-mode' ? '/img/note-icon.png' : '/img/dark-note-icon.png';

  // trying to delete markers
  markers.forEach(function(m) { m.setMap(null); m = null; });
  // starting the spiderfier library to assist with identical location markers.
  let oms = new OverlappingMarkerSpiderfier(map, {
    markersWontMove: true,
    markersWontHide: true,
    basicFormatEvents: true
  });
  // builds the markers based on the user form input.
  markers = concerts.map(function(concert){
    let locations = {lat: parseFloat(concert.venueLat), lng: parseFloat(concert.venueLong)};
    let marker = new google.maps.Marker({
      position: locations,
      icon: noteIcon,
      animation: google.maps.Animation.DROP,
      visible: locations.lat !== 0 && locations.lng !== 0
    });
    //builds the info window when the user clicks on the location marker
    let windowContent = `
Event: ${concert.name}
Date: ${concert.date}
Time: ${concert.time}
Venue: ${concert.venue}
Click to Buy Tickets
`
    let infoWindow = new google.maps.InfoWindow({
      content: windowContent
    });
    google.maps.event.addListener(marker, 'spider_click', function(e){
      infoWindow.open(map, marker);
    });
    oms.addMarker(marker);
    return marker
  });
}
<|endoftext|>


<commit_before>define([
	'jquery',
	'underscore',
	'backbone',
	'config',
	'utils',
	'text!templates/header.html',
], function($, _, Backbone, config, utils, templateHtml) {
    "use strict";

	var HeaderView = Backbone.View.extend({

	    tagName: 'div',
		className: 'header-view',

	    events: {
			'click #aboutMap': 'aboutMapClicked',
			'click #aboutGeoSense' : 'aboutGeoSenseClicked',
			'click #shareLink' : 'shareLinkClicked',
			'click #postFacebook' : 'postFacebookClicked',
			'click #postTwitter' : 'postTwitterClicked',
			'click .map-tool.setup' : 'setupButtonClicked',
			'click .map-tool.add-data' : 'addDataButtonClicked',
			'click .map-tool.upload' : 'uploadButtonClicked',
			'click .map-tool.timeline' : 'timelineButtonClicked',
			'click #mapView a' : 'mapViewToggleClicked',
			'click #viewBase .dropdown-menu a' : 'viewBaseToggleClicked',
			'click #viewStyle .dropdown-menu a' : 'viewStyleToggleClicked',

			'keypress input': 'keyEvent',
	    },

	    initialize: function(options)
	    {
		    this.template = _.template(templateHtml);
			this.vent = options.vent;
			this.listenTo(this.model, 'sync', this.populateFromModel);
	    },

	    render: function()
	    {
			$(this.el).html(this.template());
			this.populateFromModel();

			this.$('.search-query').click(function() {
				$(this).select();
			});

			if (!app.isMapAdmin()) {
				this.$('.admin-tool').remove();
			}

			this.$('.base-options').click(function(event) {
				event.stopPropagation();
			});

			var opts = this.model.attributes.viewOptions || {},
				opacity = opts.baselayerOpacity || 1,
				backgroundColor = opts.backgroundColor,
				slider = this.$('.baselayer-opacity .slider'),
				input = this.$('input[name=baselayerOpacity]');

			slider.slider({
				min: 0,
				max: 1,
				range: "min",
				step: .025,
				value: opacity,
				slide: function( event, ui ) {
					app.setViewOptions({baselayerOpacity: ui.value});
					input.val(ui.value);
				}
		    });
		    input.change(function() {
		    	var val = parseFloat($(this).val());
		    	if (isNaN(val) || val > 1) val = 1;
		    	if (val < 0) val = 0;
		    	$(this).val(val);
		    	slider.slider('value', val);
		    });

			var colorInput = this.$('input[name=backgroundColor]');
	    	if (backgroundColor != undefined) {
				$(colorInput).miniColors('value', backgroundColor);
	    	}
			$(colorInput).miniColors({
			    change: function(hex, rgb) {
					app.setViewOptions({backgroundColor: hex});
				}
			});
			$(colorInput).change(function() {
				// when blank
				app.setViewOptions({backgroundColor: $(this).val()});
			});

	        return this;
	    },

		keyEvent: function(event)
		{
			if (event.keyCode == 13) {
				if (this.$("#search").is(":focus")) {
					var address = $('#search').val();
					if (address != '') {
						app.zoomToAddress(address);
					}
				}
			}
		},

	    populateFromModel: function()
	    {
			var mapInfo = this.model.attributes;
			var title = $('<a>');
			title.text(mapInfo.title);
			title.attr('href', app.genPublicURL());
			title.click(function() {
				console.log(app.getDefaultVisibleMapArea());
				app.mapView.setVisibleMapArea(app.getDefaultVisibleMapArea());
				return false;
			});
			this.$('.brand h1').html(title);

			if (mapInfo.linkURL) {
				this.$('#authorLink').show();
				this.$('#authorLink a').attr('href', mapInfo.linkURL);
				this.$('#authorLink .text').text(mapInfo.linkTitle || mapInfo.title);
			} else {
				this.$('#authorLink').hide();
			}
		},

		mapViewToggleClicked: function(evt)
		{
			var link = evt.currentTarget;
			var mapViewName = link.href.split('#')[1];
			if (mapViewName != app.mapViewName) {
				app.navigate(app.genMapURI(mapViewName), {trigger: true});
			}
			evt.preventDefault();
		},

		viewBaseToggleClicked: function(evt)
		{
			var link = evt.currentTarget;
			var viewBase = link.href.split('#')[1];
			app.setViewBase(viewBase);
			evt.preventDefault();
		},

		viewStyleToggleClicked: function(evt)
		{
			var link = evt.currentTarget;
			var style = link.href.split('#')[1];
			app.setViewStyle(style);
			evt.preventDefault();
		},

		timelineButtonClicked: function(evt)
		{
			evt.preventDefault();
		},

		setupButtonClicked: function(evt)
		{
			app.showSetupView();
			evt.preventDefault();
		},

		addDataButtonClicked: function(evt)
		{
			app.toggleDataLibrary();
			evt.preventDefault();
		},

		uploadButtonClicked: function(evt)
		{
			app.toggleDataImport();
			evt.preventDefault();
		},

		aboutGeoSenseClicked: function(evt)
		{
			app.showAbout();
			evt.preventDefault();
		},

		aboutMapClicked: function(evt)
		{
			app.showMapInfo();
			evt.preventDefault();
		},

		shareLinkClicked: function(evt)
		{
			app.showShareLink();
			evt.preventDefault();
		},

		postTwitterClicked: function(evt)
		{
			var mapInfo = this.model.attributes,
				tweet = {},
				url = app.genPublicURL(true);
			tweet.url = url;
			tweet.text = __('Check out the %(title)s map:', {
				url: url,
				title: mapInfo.title
			});
			if (mapInfo.twitter) {
				tweet.via = mapInfo.twitter;
			}

			var url = 'https://twitter.com/share?' + $.param(tweet);
			window.open(url, __('Tweet this post'), 'width=650,height=251,toolbar=0,scrollbars=0,status=0,resizable=0,location=0,menuBar=0');
			evt.preventDefault();
		},

		postFacebookClicked: function(evt)
		{
			var mapInfo = this.model.attributes,
				url = 'http://www.facebook.com/sharer.php?u='
			url += encodeURIComponent(app.genPublicURL(true));
			url += '&t=' +encodeURIComponent(__('Check out the %(title)s map', {
				title: mapInfo.title
			}));
			window.open('' + url, __('Share it on Facebook'), 'width=650,height=251,toolbar=0,scrollbars=0,status=0,resizable=0,location=0,menuBar=0');
			evt.preventDefault();
		},

		remove: function()
		{
			$(window).unbind();
			$(this.el).remove();
			return this;
		},

	});

	return HeaderView;
});
<commit_msg>Base opacity added to input<commit_after>define([
	'jquery',
	'underscore',
	'backbone',
	'config',
	'utils',
	'text!templates/header.html',
], function($, _, Backbone, config, utils, templateHtml) {
    "use strict";

	var HeaderView = Backbone.View.extend({

	    tagName: 'div',
		className: 'header-view',

	    events: {
			'click #aboutMap': 'aboutMapClicked',
			'click #aboutGeoSense' : 'aboutGeoSenseClicked',
			'click #shareLink' : 'shareLinkClicked',
			'click #postFacebook' : 'postFacebookClicked',
			'click #postTwitter' : 'postTwitterClicked',
			'click .map-tool.setup' : 'setupButtonClicked',
			'click .map-tool.add-data' : 'addDataButtonClicked',
			'click .map-tool.upload' : 'uploadButtonClicked',
			'click .map-tool.timeline' : 'timelineButtonClicked',
			'click #mapView a' : 'mapViewToggleClicked',
			'click #viewBase .dropdown-menu a' : 'viewBaseToggleClicked',
			'click #viewStyle .dropdown-menu a' : 'viewStyleToggleClicked',

			'keypress input': 'keyEvent',
	    },

	    initialize: function(options)
	    {
		    this.template = _.template(templateHtml);
			this.vent = options.vent;
			this.listenTo(this.model, 'sync', this.populateFromModel);
	    },

	    render: function()
	    {
			$(this.el).html(this.template());
			this.populateFromModel();

			this.$('.search-query').click(function() {
				$(this).select();
			});

			if (!app.isMapAdmin()) {
				this.$('.admin-tool').remove();
			}

			this.$('.base-options').click(function(event) {
				event.stopPropagation();
			});

			var opts = this.model.attributes.viewOptions || {},
				opacity = opts.baselayerOpacity || 1,
				backgroundColor = opts.backgroundColor,
				slider = this.$('.baselayer-opacity .slider'),
				input = this.$('input[name=baselayerOpacity]');

			slider.slider({
				min: 0,
				max: 1,
				range: "min",
				step: .025,
				value: opacity,
				slide: function( event, ui ) {
					app.setViewOptions({baselayerOpacity: ui.value});
					input.val(ui.value);
				}
		    });
		    input.val(opacity);
		    input.change(function() {
		    	var val = parseFloat($(this).val());
		    	if (isNaN(val) || val > 1) val = 1;
		    	if (val < 0) val = 0;
		    	$(this).val(val);
		    	slider.slider('value', val);
		    });

			var colorInput = this.$('input[name=backgroundColor]');
	    	if (backgroundColor != undefined) {
				$(colorInput).miniColors('value', backgroundColor);
	    	}
			$(colorInput).miniColors({
			    change: function(hex, rgb) {
					app.setViewOptions({backgroundColor: hex});
				}
			});
			$(colorInput).change(function() {
				// when blank
				app.setViewOptions({backgroundColor: $(this).val()});
			});

	        return this;
	    },

		keyEvent: function(event)
		{
			if (event.keyCode == 13) {
				if (this.$("#search").is(":focus")) {
					var address = $('#search').val();
					if (address != '') {
						app.zoomToAddress(address);
					}
				}
			}
		},

	    populateFromModel: function()
	    {
			var mapInfo = this.model.attributes;
			var title = $('<a>');
			title.text(mapInfo.title);
			title.attr('href', app.genPublicURL());
			title.click(function() {
				console.log(app.getDefaultVisibleMapArea());
				app.mapView.setVisibleMapArea(app.getDefaultVisibleMapArea());
				return false;
			});
			this.$('.brand h1').html(title);

			if (mapInfo.linkURL) {
				this.$('#authorLink').show();
				this.$('#authorLink a').attr('href', mapInfo.linkURL);
				this.$('#authorLink .text').text(mapInfo.linkTitle || mapInfo.title);
			} else {
				this.$('#authorLink').hide();
			}
		},

		mapViewToggleClicked: function(evt)
		{
			var link = evt.currentTarget;
			var mapViewName = link.href.split('#')[1];
			if (mapViewName != app.mapViewName) {
				app.navigate(app.genMapURI(mapViewName), {trigger: true});
			}
			evt.preventDefault();
		},

		viewBaseToggleClicked: function(evt)
		{
			var link = evt.currentTarget;
			var viewBase = link.href.split('#')[1];
			app.setViewBase(viewBase);
			evt.preventDefault();
		},

		viewStyleToggleClicked: function(evt)
		{
			var link = evt.currentTarget;
			var style = link.href.split('#')[1];
			app.setViewStyle(style);
			evt.preventDefault();
		},

		timelineButtonClicked: function(evt)
		{
			evt.preventDefault();
		},

		setupButtonClicked: function(evt)
		{
			app.showSetupView();
			evt.preventDefault();
		},

		addDataButtonClicked: function(evt)
		{
			app.toggleDataLibrary();
			evt.preventDefault();
		},

		uploadButtonClicked: function(evt)
		{
			app.toggleDataImport();
			evt.preventDefault();
		},

		aboutGeoSenseClicked: function(evt)
		{
			app.showAbout();
			evt.preventDefault();
		},

		aboutMapClicked: function(evt)
		{
			app.showMapInfo();
			evt.preventDefault();
		},

		shareLinkClicked: function(evt)
		{
			app.showShareLink();
			evt.preventDefault();
		},

		postTwitterClicked: function(evt)
		{
			var mapInfo = this.model.attributes,
				tweet = {},
				url = app.genPublicURL(true);
			tweet.url = url;
			tweet.text = __('Check out the %(title)s map:', {
				url: url,
				title: mapInfo.title
			});
			if (mapInfo.twitter) {
				tweet.via = mapInfo.twitter;
			}

			var url = 'https://twitter.com/share?' + $.param(tweet);
			window.open(url, __('Tweet this post'), 'width=650,height=251,toolbar=0,scrollbars=0,status=0,resizable=0,location=0,menuBar=0');
			evt.preventDefault();
		},

		postFacebookClicked: function(evt)
		{
			var mapInfo = this.model.attributes,
				url = 'http://www.facebook.com/sharer.php?u='
			url += encodeURIComponent(app.genPublicURL(true));
			url += '&t=' +encodeURIComponent(__('Check out the %(title)s map', {
				title: mapInfo.title
			}));
			window.open('' + url, __('Share it on Facebook'), 'width=650,height=251,toolbar=0,scrollbars=0,status=0,resizable=0,location=0,menuBar=0');
			evt.preventDefault();
		},

		remove: function()
		{
			$(window).unbind();
			$(this.el).remove();
			return this;
		},

	});

	return HeaderView;
});
<|endoftext|>


<commit_before>define( [

  "dojo/_base/declare"

, "dojo/topic"

, "hotplate/hotDojoAuth/panels/Resume"
, "hotplate/hotDojoWidgets/TempDialog"

], function(
  declare

, topic

, Resume
, TempDialog

){
  // Create the "login" pane, based on a normal ContentPane
  return declare( null, {

    postCreate: function(){
      var self = this;

      this.inherited(arguments);

      topic.subscribe( 'hotDojoSubmit/unauthorized', function( ){

        var tempDialog = new TempDialog( {
          title: "Authenticate",
          hideOn: "hotDojoAuth/resuming",
        } );

        // Make a dialog with the strategies store
        var r = new Resume();
        tempDialog.addChild( r );
        tempDialog.startup();
      });

    },
 });
});

<commit_msg>Old comment out<commit_after>define( [

  "dojo/_base/declare"

, "dojo/topic"

, "hotplate/hotDojoAuth/panels/Resume"
, "hotplate/hotDojoWidgets/TempDialog"

], function(
  declare

, topic

, Resume
, TempDialog

){

  return declare( null, {

    postCreate: function(){
      var self = this;

      this.inherited(arguments);

      topic.subscribe( 'hotDojoSubmit/unauthorized', function( ){

        var tempDialog = new TempDialog( {
          title: "Authenticate",
          hideOn: "hotDojoAuth/resuming",
        } );

        // Make a dialog with the strategies store
        var r = new Resume();
        tempDialog.addChild( r );
        tempDialog.startup();
      });

    },
 });
});

<|endoftext|>