<commit_before>'use strict';
var Alexa = require('alexa-sdk');

//Replace with your app ID (OPTIONAL).  You can find this value at the top of your skill's page on http://developer.amazon.com.
//Make sure to enclose your value in quotes, like this: var APP_ID = "amzn1.ask.skill.bb4045e6-b3e8-4133-b650-72923c5980f1";
var APP_ID = undefined;

var SKILL_NAME = "Capital Whiz";
var GET_FACT_MESSAGE = "The state capital of ";
var WELCOME_MESSAGE = "Welcome to Capital Whiz.  I can recite all 50 state capitals, give the capital for a state of your choice, or give you a quiz.";//  I can give the capital if you give me the state.  And, I can quiz your capital knowledge.  What would you like to do?";
var HELP_MESSAGE = "As an example, you can say what is the capital of Hawaii.";
var HELP_REPROMPT = "I'll wait for your command.";
var CANCEL_MESSAGE = "Sure.  You're in control."
var STOP_MESSAGE = "Goodbye!";

var stateFilter = undefined;
var capitalFilter = undefined;
var recitals = [];
var cardText = [];

var states = [
    {
        "name": "Alabama",
        "capital": "Montgomery"
    },
       {
        "name": "Alaska",
        "capital": "Juneau"
    },
    {
        "name": "Arizona",
        "capital": "Phoenix"
    },
    {
        "name": "Arkansas",
        "capital": "Little Rock"
    },
    {
        "name": "California",
        "capital": "Sacramento"
    },
    {
        "name": "Colorado",
        "capital": "Denver"
    },
    {
        "name": "Connecticut",
        "capital": "Hartford"
    },
    {
        "name": "Delaware",
        "capital": "Dover"
    },
    {
        "name": "Florida",
        "capital": "Tallahassee"
    },
    {
        "name": "Georgia",
        "capital": "Atlanta"
    },
    {
        "name": "Hawaii",
        "capital": "Honolulu"
    },
    {
        "name": "Idaho",
        "capital": "Boise"
    },
    {
        "name": "Illinois",
        "capital": "Springfield"
    },
    {
        "name": "Indiana",
        "capital": "Indianapolis"
    },
    {
        "name": "Iowa",
        "capital": "Des Moines"
    },
    {
        "name": "Kansas",
        "capital": "Topeka"
    },
    {
        "name": "Kentucky",
        "capital": "Frankfort"
    },
    {
        "name": "Louisiana",
        "capital": "Baton Rouge"
    },
    {
        "name": "Maine",
        "capital": "Augusta"
    },
    {
        "name": "Maryland",
        "capital": "Annapolis"
    },
    {
        "name": "Massachusetts",
        "capital": "Boston"
    },
    {
        "name": "Michigan",
        "capital": "Lansing"
    },
    {
        "name": "Minnesota",
        "capital": "Saint Paul"
    },
    {
        "name": "Mississippi",
        "capital": "Jackson"
    },
    {
        "name": "Missouri",
        "capital": "Jefferson City"
    },
    {
        "name": "Montana",
        "capital": "Helena"
    },
    {
        "name": "Nebraska",
        "capital": "Lincoln"
    },
    {
        "name": "Nevada",
        "capital": "Carson City"
    },
    {
        "name": "New Hampshire",
        "capital": "Concord"
    },
    {
        "name": "New Jersey",
        "capital": "Trenton"
    },
    {
        "name": "New Mexico",
        "capital": "Santa Fe"
    },
    {
        "name": "New York",
        "capital": "Albany"
    },
    {
        "name": "North Carolina",
        "capital": "Raleigh"
    },
    {
        "name": "North Dakota",
        "capital": "Bismarck"
    },
    {
        "name": "Ohio",
        "capital": "Columbus"
    },
    {
        "name": "Oklahoma",
        "capital": "Oklahoma City"
    },
    {
        "name": "Oregon",
        "capital": "Salem"
    },
    {
        "name": "Pennsylvania",
        "capital": "Harrisburg"
    },
    {
        "name": "Rhode Island",
        "capital": "Providence"
    },
    {
        "name": "South Carolina",
        "capital": "Columbia"
    },
    {
        "name": "South Dakota",
        "capital": "Pierre"
    },
    {
        "name": "Tennessee",
        "capital": "Nashville"
    },
    {
        "name": "Texas",
        "capital": "Austin"
    },
    {
        "name": "Utah",
        "capital": "Salt Lake City"
    },
    {
        "name": "Vermont",
        "capital": "Montpelier"
    },
    {
        "name": "Virginia",
        "capital": "Richmond"
    },
    {
        "name": "Washington",
        "capital": "Olympia"
    },
    {
        "name": "West Virginia",
        "capital": "Charleston"
    },
    {
        "name": "Wisconsin",
        "capital": "Madison"
    },
    {
        "name": "Wyoming",
        "capital": "Cheyenne"
    }
];

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.APP_ID = APP_ID;
    alexa.registerHandlers(handlers);
    alexa.execute();
};

var handlers = {
    'LaunchRequest': function () {
        this.emit(':ask', WELCOME_MESSAGE, HELP_REPROMPT);
    },
    'ReciteCapitalsIntent': function () {
        recitals = [];
        cardText = [];

        states.forEach(reciteState);
        var speechOutput = recitals.join(". ");

        states.forEach(cardDisplayState);
        var cardOutput = cardText.join("\r\n");

        this.emit(':askWithCard', speechOutput, HELP_REPROMPT, SKILL_NAME, cardOutput);
    },
    'GiveCapitalIntent': function () {
        stateFilter = this.event.request.intent.slots.State.value;
        var capital = states.find(findState).capital;
        this.emit(':ask', capital + ', ' + stateFilter, HELP_REPROMPT);
    },
    'QuizIntent': function () {
        var state = nextState().name;
        this.attributes['lastState'] = state;
        var question = 'what is the capital of ' + state;
        this.emit(':ask', question, question);
    },
    'QuizAnswerIntent': function () {
        capitalFilter = this.event.request.intent.slots.Capital.value;
        var state = states.find(findStateByCapital);

        var result = 'wrong';
        if(state !== undefined && state.name === this.attributes['lastState'])
            result = 'correct';

        state = nextState().name;
        this.attributes['lastState'] = state;
        var question = 'what is the capital of ' + state;

        this.emit(':ask', result, question);
    },
    'AMAZON.HelpIntent': function () {
        var speechOutput = HELP_MESSAGE;
        var reprompt = HELP_REPROMPT;
        this.emit(':ask', speechOutput, reprompt);
    },
    'AMAZON.CancelIntent': function () {
        this.emit(':tell', CANCEL_MESSAGE);
    },
    'AMAZON.StopIntent': function () {
        this.emit(':tell', STOP_MESSAGE);
    }
};

function findState(state) {
    return state.name === stateFilter;
}

function findStateByCapital(state) {
    return state.capital === capitalFilter;
}

function reciteState(state) {
    recitals.push(GET_FACT_MESSAGE + state.name + ' is ' + state.capital);
}

function cardDisplayState(state) {
    cardText.push(state.capital + ', ' + state.name);
}

function nextState() {
    return states[Math.floor(Math.random() * states.length)];
}<commit_msg>add more forensics on answers via logging and card output<commit_after>'use strict';
var Alexa = require('alexa-sdk');

//Replace with your app ID (OPTIONAL).  You can find this value at the top of your skill's page on http://developer.amazon.com.
//Make sure to enclose your value in quotes, like this: var APP_ID = "amzn1.ask.skill.bb4045e6-b3e8-4133-b650-72923c5980f1";
var APP_ID = undefined;

var SKILL_NAME = "Capital Whiz";
var GET_FACT_MESSAGE = "The state capital of ";
var WELCOME_MESSAGE = "Welcome to Capital Whiz.  I can recite all 50 state capitals, give the capital for a state of your choice, or give you a quiz.";//  I can give the capital if you give me the state.  And, I can quiz your capital knowledge.  What would you like to do?";
var HELP_MESSAGE = "As an example, you can say what is the capital of Hawaii.";
var HELP_REPROMPT = "I'll wait for your command.";
var CANCEL_MESSAGE = "Sure.  You're in control."
var STOP_MESSAGE = "Goodbye!";

var stateFilter = undefined;
var capitalFilter = undefined;
var recitals = [];
var cardText = [];

var states = [
    {
        "name": "Alabama",
        "capital": "Montgomery"
    },
       {
        "name": "Alaska",
        "capital": "Juneau"
    },
    {
        "name": "Arizona",
        "capital": "Phoenix"
    },
    {
        "name": "Arkansas",
        "capital": "Little Rock"
    },
    {
        "name": "California",
        "capital": "Sacramento"
    },
    {
        "name": "Colorado",
        "capital": "Denver"
    },
    {
        "name": "Connecticut",
        "capital": "Hartford"
    },
    {
        "name": "Delaware",
        "capital": "Dover"
    },
    {
        "name": "Florida",
        "capital": "Tallahassee"
    },
    {
        "name": "Georgia",
        "capital": "Atlanta"
    },
    {
        "name": "Hawaii",
        "capital": "Honolulu"
    },
    {
        "name": "Idaho",
        "capital": "Boise"
    },
    {
        "name": "Illinois",
        "capital": "Springfield"
    },
    {
        "name": "Indiana",
        "capital": "Indianapolis"
    },
    {
        "name": "Iowa",
        "capital": "Des Moines"
    },
    {
        "name": "Kansas",
        "capital": "Topeka"
    },
    {
        "name": "Kentucky",
        "capital": "Frankfort"
    },
    {
        "name": "Louisiana",
        "capital": "Baton Rouge"
    },
    {
        "name": "Maine",
        "capital": "Augusta"
    },
    {
        "name": "Maryland",
        "capital": "Annapolis"
    },
    {
        "name": "Massachusetts",
        "capital": "Boston"
    },
    {
        "name": "Michigan",
        "capital": "Lansing"
    },
    {
        "name": "Minnesota",
        "capital": "Saint Paul"
    },
    {
        "name": "Mississippi",
        "capital": "Jackson"
    },
    {
        "name": "Missouri",
        "capital": "Jefferson City"
    },
    {
        "name": "Montana",
        "capital": "Helena"
    },
    {
        "name": "Nebraska",
        "capital": "Lincoln"
    },
    {
        "name": "Nevada",
        "capital": "Carson City"
    },
    {
        "name": "New Hampshire",
        "capital": "Concord"
    },
    {
        "name": "New Jersey",
        "capital": "Trenton"
    },
    {
        "name": "New Mexico",
        "capital": "Santa Fe"
    },
    {
        "name": "New York",
        "capital": "Albany"
    },
    {
        "name": "North Carolina",
        "capital": "Raleigh"
    },
    {
        "name": "North Dakota",
        "capital": "Bismarck"
    },
    {
        "name": "Ohio",
        "capital": "Columbus"
    },
    {
        "name": "Oklahoma",
        "capital": "Oklahoma City"
    },
    {
        "name": "Oregon",
        "capital": "Salem"
    },
    {
        "name": "Pennsylvania",
        "capital": "Harrisburg"
    },
    {
        "name": "Rhode Island",
        "capital": "Providence"
    },
    {
        "name": "South Carolina",
        "capital": "Columbia"
    },
    {
        "name": "South Dakota",
        "capital": "Pierre"
    },
    {
        "name": "Tennessee",
        "capital": "Nashville"
    },
    {
        "name": "Texas",
        "capital": "Austin"
    },
    {
        "name": "Utah",
        "capital": "Salt Lake City"
    },
    {
        "name": "Vermont",
        "capital": "Montpelier"
    },
    {
        "name": "Virginia",
        "capital": "Richmond"
    },
    {
        "name": "Washington",
        "capital": "Olympia"
    },
    {
        "name": "West Virginia",
        "capital": "Charleston"
    },
    {
        "name": "Wisconsin",
        "capital": "Madison"
    },
    {
        "name": "Wyoming",
        "capital": "Cheyenne"
    }
];

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.APP_ID = APP_ID;
    alexa.registerHandlers(handlers);
    alexa.execute();
};

var handlers = {
    'LaunchRequest': function () {
        this.emit(':ask', WELCOME_MESSAGE, HELP_REPROMPT);
    },
    'ReciteCapitalsIntent': function () {
        recitals = [];
        cardText = [];

        states.forEach(reciteState);
        var speechOutput = recitals.join(". ");

        states.forEach(cardDisplayState);
        var cardOutput = cardText.join("\r\n");

        this.emit(':askWithCard', speechOutput, HELP_REPROMPT, SKILL_NAME, cardOutput);
    },
    'GiveCapitalIntent': function () {
        stateFilter = this.event.request.intent.slots.State.value;
        var capital = states.find(findState).capital;
        this.emit(':ask', capital + ', ' + stateFilter, HELP_REPROMPT);
    },
    'QuizIntent': function () {
        var state = nextState().name;
        this.attributes['lastState'] = state;
        var question = 'what is the capital of ' + state;
        this.emit(':ask', question, question);
    },
    'QuizAnswerIntent': function () {

        var cardText = [];

        // get and compare answer
        var expectedState = this.attributes['lastState'];
        console.log('alexa asked for capital of: ' + expectedState);
        cardText.push('I asked you for the capital of ' + expectedState);

        capitalFilter = this.event.request.intent.slots.Capital.value;
        console.log('user answered: ' + capitalFilter);
        cardText.push('You answered ' + capitalFilter);

        var result = 'wrong';
        var state = states.find(findStateByCapital);
        if(state === undefined) {
            console.log('state lookup: ' + state);
            cardText.push('Your capital answer equates to ' + state + ' state')
        }
        else if(state.name !== expectedState) {
            console.log('state lookup: ' + state.name);
            cardText.push('Your capital answer equates to ' + state.name + ' state')
        }
        else {
            result = 'correct';
        }

        console.log('answer is: ' + result);
        cardText.push('You answer is ' + result + '.');

        // pick next state and ask next question
        state = nextState().name;
        this.attributes['lastState'] = state;
        var question = 'what is the capital of ' + state;

        var cardOutput = cardText.join('.\r\n');
        this.emit(':askWithCard', result, question, SKILL_NAME, cardOutput);
    },
    'AMAZON.HelpIntent': function () {
        var speechOutput = HELP_MESSAGE;
        var reprompt = HELP_REPROMPT;
        this.emit(':ask', speechOutput, reprompt);
    },
    'AMAZON.CancelIntent': function () {
        this.emit(':tell', CANCEL_MESSAGE);
    },
    'AMAZON.StopIntent': function () {
        this.emit(':tell', STOP_MESSAGE);
    }
};

function findState(state) {
    return state.name === stateFilter;
}

function findStateByCapital(state) {
    return state.capital === capitalFilter;
}

function reciteState(state) {
    recitals.push(GET_FACT_MESSAGE + state.name + ' is ' + state.capital);
}

function cardDisplayState(state) {
    cardText.push(state.capital + ', ' + state.name);
}

function nextState() {
    return states[Math.floor(Math.random() * states.length)];
}<|endoftext|>


<commit_before>var height = 20;
var stroke_width = 1;
var box_fill = "#000";
var stroke_color = "#000";

var font_size = 8;
var red_color = "#c02137";
var green_color = "#4e9c62";
var blue_color = "#00668e";

function refernceGraph(type){
    var width = $(".js-container-" + type).width();

    if(type == "full"){
        xLowNorm = 0.400;
        widthNorm = 2.294;

        waveLengths = [[0.435, 0.451, 1, "#6ca4d3", "Coastal/Aerosol"],
                           [0.452, 0.512, 2, blue_color, "Blue"],
                           [0.533, 0.590, 3, green_color, "Green"],
                           [0.636, 0.673, 4, red_color, "Red"],
                           [0.851, 0.879, 5, "#c5a3be", "Near Infrared (NIR)"],
                           [1.566, 1.651, 6, "#d49979", "SWIR 1"],
                           [2.107, 2.294, 7, "#999b98", "SWIR 2"],
                           [1.362, 1.384, 9, "#7f87b5", "Cirrus"]];
    }else{
        xLowNorm = 0.400;
        widthNorm = 0.673;

        waveLengths = [[0.452, 0.512, 2, blue_color, "Blue"],
                       [0.533, 0.590, 3, green_color, "Green"],
                       [0.636, 0.673, 4, red_color, "Red"]];
    }

    var svgBar = d3.selectAll("#js-reference-" + type)
            .append("svg")
            .attr("width", width)
            .attr("height", height + stroke_width)
            .attr('class', 'spectrumMap');

    var tip = d3.tip()
        .attr('class', 'd3-tip')
        .offset([height *2 , 0])
        .html(function(d) {
            return '
' + d[2] + ': ' + d[4] + ' (' + d[0] + " - " + d[1] + ' µm)' + '
';
            });

    svgBar.call(tip);

    svgBar.append("rect")
        .attr("x", 0 + "px")
        .attr("y", 0 + "px")
        .attr("width", width)
        .attr("height", height + stroke_width);

    svgBar.selectAll("rect")
        .data(waveLengths, function(d){return d;})
        .enter()
        .append("rect")
        .attr("stroke-width", stroke_width)
        .attr("stroke", stroke_color)
        .attr("fill", function (d){ return (d[3]); })
        .attr("x", function (d){ return (width * ((d[0] - xLowNorm) / widthNorm)) + "px"; })
        .attr("y", 0 + "px")
        .attr("width", function (d){ return (width * (d[1] - d[0]) / (widthNorm - xLowNorm)) + "px"; })
        .attr("height", height + "px")
        .on('mouseover', tip.show)
        .on('mouseout', tip.hide);

    svgBar.selectAll("text")
        .data(waveLengths, function(d){return d;})
        .enter()
        .append("text")
        .attr("x", function (d){ return (width * ((d[0] - xLowNorm) / widthNorm)) + "px"; })
        .attr("y", 0 + "px")
        .attr("text-anchor", "middle")
        .attr("dx", function (d){ return ((width * (d[1] - d[0]) / (widthNorm - xLowNorm)) / 2) + "px"; })
        .attr("dy", height / 2 + font_size / 2)
        .attr("font-size", font_size)
        .text(function(d) { return d[2]; })
        .attr("pointer-events", "none");
}

function graph(graphId, type) {
    var id = '#'.concat(graphId);
    var red_band = Number($(id).parent().find($(".band-red")).html());
    var green_band = Number($(id).parent().find($(".band-green")).html());
    var blue_band = Number($(id).parent().find($(".band-blue")).html());

    var width = $(id).parent().width();

    var waveLengths = [[red_band, red_color],
                       [blue_band, blue_color],
                       [green_band, green_color]];

    var svgBar = d3.selectAll(id)
            .append("svg")
            .attr("width", width)
            .attr("height", height + stroke_width)
            .attr('class', 'spectrumMap');

    svgBar.append("rect")
        .attr("x", 0 + "px")
        .attr("y", 0 + "px")
        .attr("width", width)
        .attr("height", height + stroke_width);

    svgBar.selectAll("rect")
        .data(waveLengths, function(d){return d;})
        .enter()
        .append("rect")
        .attr("stroke-width", stroke_width)
        .attr("stroke", stroke_color)
        .attr("fill", function (d){ return (d[1]); })
        .attr("x", function (d){ return ((width / 11) * (d[0] - 1)) + "px"; })
        .attr("y", 0 + "px")
        .attr("width", function (d){ return (width / 11)+ "px"; })
        .attr("height", height + "px")
        .attr("pointer-events", "none");
}

$(document).ready(function(){
    $(".preview").each(function(){
        graphId = $(this).find($(".js-graph")).attr("id");
        graph(graphId, "preview");
        });

    refernceGraph("full");
    refernceGraph("visible");

});

$(window).on('resize', function (){
    $(".js-graph").contents().remove();

    $(".preview").each(function(){
        graphId = $(this).find($(".js-graph")).attr("id");
        graph(graphId, "preview");
        });

    refernceGraph("full");
    refernceGraph("visible");
});
<commit_msg>#84 fix mapping of frequency range to width<commit_after>var height = 20;
var stroke_width = 1;
var box_fill = "#000";
var stroke_color = "#000";

var font_size = 8;
var red_color = "#c02137";
var green_color = "#4e9c62";
var blue_color = "#00668e";
var freqOffset = 0.035;

function refernceGraph(type){
    var width = $(".js-container-" + type).width();

    if(type == "full"){
        freqMin = 0.435;
        freqMax = 2.294;
        xLowNorm = freqMin - freqOffset;
        widthNorm = freqMax + freqOffset;

        waveLengths = [[0.435, 0.451, 1, "#6ca4d3", "Coastal/Aerosol"],
                       [0.452, 0.512, 2, blue_color, "Blue"],
                       [0.533, 0.590, 3, green_color, "Green"],
                       [0.636, 0.673, 4, red_color, "Red"],
                       [0.851, 0.879, 5, "#c5a3be", "Near Infrared (NIR)"],
                       [1.566, 1.651, 6, "#d49979", "SWIR 1"],
                       [2.107, 2.294, 7, "#999b98", "SWIR 2"],
                       [1.362, 1.384, 9, "#7f87b5", "Cirrus"]];
    }else{
        freqMin = 0.435;
        freqMax = 0.673;
        xLowNorm = freqMin - freqOffset;
        widthNorm = freqMax + freqOffset;

        waveLengths = [[0.452, 0.512, 2, blue_color, "Blue"],
                       [0.533, 0.590, 3, green_color, "Green"],
                       [0.636, 0.673, 4, red_color, "Red"]];
    }

    var svgBar = d3.selectAll("#js-reference-" + type)
            .append("svg")
            .attr("width", width)
            .attr("height", height + stroke_width)
            .attr('class', 'spectrumMap');

    var tip = d3.tip()
        .attr('class', 'd3-tip')
        .offset([height * 2 , 0])
        .html(function(d) {
            return '
' + d[2] + ': ' + d[4] + ' (' + d[0] + " - " + d[1] + ' µm)' + '
';
            });

    svgBar.call(tip);

    svgBar.append("rect")
        .attr("x", 0 + "px")
        .attr("y", 0 + "px")
        .attr("width", width)
        .attr("height", height + stroke_width);

    svgBar.selectAll("rect")
        .data(waveLengths, function(d){return d;})
        .enter()
        .append("rect")
        .attr("stroke-width", stroke_width)
        .attr("stroke", stroke_color)
        .attr("fill", function (d){ return (d[3]); })
        .attr("x", function (d){ return ((d[0] - xLowNorm) * width / (widthNorm - xLowNorm)) + "px"; })
        .attr("y", 0 + "px")
        .attr("width", function (d){ return (width * (d[1] - d[0]) / (widthNorm - xLowNorm)) + "px"; })
        .attr("height", height + "px")
        .on('mouseover', tip.show)
        .on('mouseout', tip.hide);

    svgBar.selectAll("text")
        .data(waveLengths, function(d){return d;})
        .enter()
        .append("text")
        .attr("x", function (d){ return (width * ((d[0] - xLowNorm) / widthNorm)) + "px"; })
        .attr("y", 0 + "px")
        .attr("text-anchor", "middle")
        .attr("dx", function (d){ return ((width * (d[1] - d[0]) / (widthNorm - xLowNorm)) / 2) + "px"; })
        .attr("dy", height / 2 + font_size / 2)
        .attr("font-size", font_size)
        .text(function(d) { return d[2]; })
        .attr("pointer-events", "none");
}

function graph(graphId, type) {
    var id = '#'.concat(graphId);
    var red_band = Number($(id).parent().find($(".band-red")).html());
    var green_band = Number($(id).parent().find($(".band-green")).html());
    var blue_band = Number($(id).parent().find($(".band-blue")).html());

    var width = $(id).parent().width();

    var waveLengths = [[red_band, red_color],
                       [blue_band, blue_color],
                       [green_band, green_color]];

    var svgBar = d3.selectAll(id)
            .append("svg")
            .attr("width", width)
            .attr("height", height + stroke_width)
            .attr('class', 'spectrumMap');

    svgBar.append("rect")
        .attr("x", 0 + "px")
        .attr("y", 0 + "px")
        .attr("width", width)
        .attr("height", height + stroke_width);

    svgBar.selectAll("rect")
        .data(waveLengths, function(d){return d;})
        .enter()
        .append("rect")
        .attr("stroke-width", stroke_width)
        .attr("stroke", stroke_color)
        .attr("fill", function (d){ return (d[1]); })
        .attr("x", function (d){ return ((width / 11) * (d[0] - 1)) + "px"; })
        .attr("y", 0 + "px")
        .attr("width", function (d){ return (width / 11)+ "px"; })
        .attr("height", height + "px")
        .attr("pointer-events", "none");
}

$(document).ready(function(){
    $(".preview").each(function(){
        graphId = $(this).find($(".js-graph")).attr("id");
        graph(graphId, "preview");
        });

    refernceGraph("full");
    refernceGraph("visible");

});

$(window).on('resize', function (){
    $(".js-graph").contents().remove();

    $(".preview").each(function(){
        graphId = $(this).find($(".js-graph")).attr("id");
        graph(graphId, "preview");
        });

    refernceGraph("full");
    refernceGraph("visible");
});
<|endoftext|>


<commit_before>/*global emit: false, start: false, log: false, getRow: false, send: false,
  $: false*/

var utils = require('./utils'),
    templates = require('kanso/templates');

exports.types = function (doc, req) {
    var settings = utils.appRequire(doc, 'kanso/settings');
    var app = utils.appRequire(doc, settings.load);

    var types = [];
    if (app.types) {
        for (var k in app.types) {
            if (app.types.hasOwnProperty(k)) {
                types.push(k);
            }
        }
    }

    var res = {code: 200, headers: {'Content-Type': 'text/html'}};

    var content = templates.render('types.html', req, {
        types: types,
        app: settings.name,
        app_heading: utils.capitalize(settings.name)
    });

    if (req.client) {
        $('#content').html(content);
        document.title = settings.name + ' - Types';
    }
    else {
        res.body = templates.render('base.html', req, {
            title: settings.name + ' - Types',
            content: content
        });
    }

    return res;
};

exports.addtype = function (doc, req) {
    if (!req.client) {
        return templates.render('base.html', req, {
            title: req.query.app + ' - Types - ' + req.query.type,
            content: templates.render('noscript.html', req, {})
        });
    }
    utils.getDesignDoc(req.query.app, function (err, ddoc) {
        if (err) {
            return alert(err);
        }
        var settings = utils.appRequire(ddoc, 'kanso/settings'),
            app = utils.appRequire(ddoc, settings.load),
            type = app.types ? app.types[req.query.type]: undefined;

        var forms = utils.appRequire(ddoc, 'kanso/forms'),
            form = new forms.Form(type);

        if (req.method === 'POST') {
            form.validate(req);
        }
        var content = templates.render('add_type.html', req, {
            app: req.query.app,
            app_heading: utils.capitalize(req.query.app),
            type: req.query.type,
            type_heading: utils.typeHeading(req.query.type),
            form: form.toHTML(forms.render.table)
        });
        $('#content').html(content);
        document.title = settings.name + ' - Types - ' + req.query.type;
    });
};

exports.edittype = function (doc, req) {
    if (!req.client) {
        return templates.render('base.html', req, {
            title: req.query.app + ' - Types - ' + req.query.type,
            content: templates.render('noscript.html', req, {})
        });
    }
    utils.getDesignDoc(req.query.app, function (err, ddoc) {
        var settings = utils.appRequire(ddoc, 'kanso/settings'),
            app = utils.appRequire(ddoc, settings.load),
            type = app.types ? app.types[req.query.type]: undefined;

        var forms = utils.appRequire(ddoc, 'kanso/forms'),
            form = new forms.Form(type, doc);

        var content = templates.render('edit_type.html', req, {
            app: req.query.app,
            app_heading: utils.capitalize(req.query.app),
            type: req.query.type,
            type_heading: utils.typeHeading(req.query.type),
            id: req.query.id,
            form: form.toHTML(forms.render.table)
        });

        $('#content').html(content);
        document.title = settings.name + ' - Types - ' + req.query.type;
    });
};
<commit_msg>admin app - refactor show functions<commit_after>/*global emit: false, start: false, log: false, getRow: false, send: false,
  $: false*/

var utils = require('./utils'),
    templates = require('kanso/templates');

var adminShow = function (fn) {
    return function (doc, req) {
        if (!req.client) {
            return templates.render('base.html', req, {
                title: 'Admin',
                content: templates.render('noscript.html', req, {})
            });
        }
        utils.getDesignDoc(req.query.app, function (err, ddoc) {
            if (err) {
                return alert(err);
            }
            fn(doc, ddoc, req);
        });
    }
};

exports.types = adminShow(function (doc, ddoc, req) {
    var settings = utils.appRequire(ddoc, 'kanso/settings');
    var app = utils.appRequire(ddoc, settings.load);

    var types = [];
    if (app.types) {
        for (var k in app.types) {
            if (app.types.hasOwnProperty(k)) {
                types.push(k);
            }
        }
    }

    var res = {code: 200, headers: {'Content-Type': 'text/html'}};

    var content = templates.render('types.html', req, {
        types: types,
        app: settings.name,
        app_heading: utils.capitalize(settings.name)
    });

    if (req.client) {
        $('#content').html(content);
        document.title = settings.name + ' - Types';
    }
    else {
        res.body = templates.render('base.html', req, {
            title: settings.name + ' - Types',
            content: content
        });
    }

    return res;
});

exports.addtype = adminShow(function (doc, ddoc, req) {
    var settings = utils.appRequire(ddoc, 'kanso/settings'),
        app = utils.appRequire(ddoc, settings.load),
        type = app.types ? app.types[req.query.type]: undefined;

    var forms = utils.appRequire(ddoc, 'kanso/forms'),
        form = new forms.Form(type);

    if (req.method === 'POST') {
        form.validate(req);
    }
    var content = templates.render('add_type.html', req, {
        app: req.query.app,
        app_heading: utils.capitalize(req.query.app),
        type: req.query.type,
        type_heading: utils.typeHeading(req.query.type),
        form: form.toHTML(forms.render.table)
    });
    $('#content').html(content);
    document.title = settings.name + ' - Types - ' + req.query.type;
});

exports.edittype = adminShow(function (doc, ddoc, req) {
    var settings = utils.appRequire(ddoc, 'kanso/settings'),
        app = utils.appRequire(ddoc, settings.load),
        type = app.types ? app.types[req.query.type]: undefined;

    var forms = utils.appRequire(ddoc, 'kanso/forms'),
        form = new forms.Form(type, doc);

    var content = templates.render('edit_type.html', req, {
        app: req.query.app,
        app_heading: utils.capitalize(req.query.app),
        type: req.query.type,
        type_heading: utils.typeHeading(req.query.type),
        id: req.query.id,
        form: form.toHTML(forms.render.table)
    });

    $('#content').html(content);
    document.title = settings.name + ' - Types - ' + req.query.type;
});
<|endoftext|>


<commit_before>'use strict';

var omit = require('lodash.omit');
var assign = require('lodash.assign');

/**
 * Returns a gleipnir publisher that will use the passed configuration to publish messages
 *
 * @param  {Gleipnir} gleipnir Gleipnir client
 * @param  {Object}   opts     Object of options to use. Required parameters: `exchangeName` and `routingKey`
 * @return {Object}            Returns the publish API, consisting of `publish()` and `sendToQueue()`
 */
function publisher(gleipnir, opts) {
    // Ensure that the passed client has the necessary methods
    if (!gleipnir || typeof gleipnir.addReadyListener !== 'function') {
        throw new TypeError('First argument must be a valid gleipnir client');
    }

    // Instance options
    var options = opts || {};
    var writeCallbackQueue = [];
    var messageQueue = [];
    var isReady = false;
    var channel;

    // Inform gleipnir that we want to know when it's ready for us to publish
    gleipnir.addReadyListener(onReady);

    // External API
    return {
        publish: publish,
        sendToQueue: sendToQueue
    };

    /**
     * Method called once Gleipnir client is ready to receive publish-calls
     *
     * @param {AmqpChannel} chan
     */
    function onReady(chan) {
        channel = chan;
        isReady = true;

        channel.on('drain', triggerWriteCallbacks);
        flushQueue();
    }

    /**
     * Publish a message to the defined exchange name
     *
     * @param  {Buffer}   content  Content of the message
     * @param  {Object}   msgOpts  Optional message-specific options - will be merged with publisher options
     * @param  {Function} callback Function to call when message has been written to the write buffer
     * @return {void}
     */
    function publish(content, msgOpts, callback) {
        if (!isReady) {
            return messageQueue.push({
                content: content,
                opts: msgOpts,
                callback: callback
            });
        }

        if (typeof msgOpts === 'function') {
            callback = msgOpts;
            msgOpts = {};
        }

        msgOpts = assign({}, options, msgOpts);

        if (channel.publish(
            msgOpts.exchangeName || options.exchangeName,
            msgOpts.routingKey || options.routingKey,
            Buffer.isBuffer(content) ? content : new Buffer(content),
            omit(msgOpts, ['exchangeName', 'routingKey'])
        )) {
            // Written to buffer, return
            return callback && setImmediate(callback);
        }

        if (callback) {
            writeCallbackQueue.push(callback);
        }
    }

    /**
     * Send a message directly to a queue
     *
     * @param  {String}   queue    Queue to send message to
     * @param  {Buffer}   content  Content of the message
     * @param  {Object}   msgOpts  Optional message-specific options - will be merged with publisher options
     * @param  {Function} callback Function to call when message has been written to the write buffer
     * @return {void}
     */
    function sendToQueue(queue, content, msgOpts, callback) {
        if (!isReady) {
            return messageQueue.push({
                content: content,
                opts: msgOpts,
                queue: queue,
                callback: callback
            });
        }

        if (typeof msgOpts === 'function') {
            callback = msgOpts;
            msgOpts = {};
        }

        msgOpts = assign({}, options, msgOpts);

        if (channel.sendToQueue(
            queue,
            Buffer.isBuffer(content) ? content : new Buffer(content),
            omit(msgOpts, ['exchangeName', 'routingKey'])
        )) {
            return callback && setImmediate(callback);
        }

        if (callback) {
            writeCallbackQueue.push(callback);
        }
    }

    /**
     * Flush the internal queue of unpublished messages
     *
     * @return {void}
     */
    function flushQueue() {
        var msg;
        while (messageQueue.length) {
            msg = messageQueue.shift();

            if (msg.queue) {
                sendToQueue(msg.queue, msg.content, msg.opts, msg.callback);
            } else {
                publish(msg.content, msg.opts, msg.callback);
            }
        }
    }

    /**
     * Trigger all the queued write callbacks
     *
     * @return {void}
     */
    function triggerWriteCallbacks() {
        while (writeCallbackQueue.length) {
            writeCallbackQueue.shift()();
        }
    }
}

module.exports = publisher;
<commit_msg>Fix coding standard issues<commit_after>'use strict';

var omit = require('lodash.omit');
var assign = require('lodash.assign');

/**
 * Returns a gleipnir publisher that will use the passed configuration to publish messages
 *
 * @param  {Gleipnir} gleipnir Gleipnir client
 * @param  {Object}   opts     Object of options to use. Required parameters: `exchangeName` and `routingKey`
 * @return {Object}            Returns the publish API, consisting of `publish()` and `sendToQueue()`
 */
function publisher(gleipnir, opts) {
    // Ensure that the passed client has the necessary methods
    if (!gleipnir || typeof gleipnir.addReadyListener !== 'function') {
        throw new TypeError('First argument must be a valid gleipnir client');
    }

    // Instance options
    var options = opts || {};
    var writeCallbackQueue = [];
    var messageQueue = [];
    var isReady = false;
    var channel;

    // Inform gleipnir that we want to know when it's ready for us to publish
    gleipnir.addReadyListener(onReady);

    // External API
    return {
        publish: publish,
        sendToQueue: sendToQueue
    };

    /**
     * Method called once Gleipnir client is ready to receive publish-calls
     *
     * @param {AmqpChannel} chan
     */
    function onReady(chan) {
        channel = chan;
        isReady = true;

        channel.on('drain', triggerWriteCallbacks);
        flushQueue();
    }

    /**
     * Publish a message to the defined exchange name
     *
     * @param  {Buffer}   content  Content of the message
     * @param  {Object}   msgOpts  Optional message-specific options - will be merged with publisher options
     * @param  {Function} callback Function to call when message has been written to the write buffer
     * @return {void}
     */
    function publish(content, msgOpts, callback) {
        if (!isReady) {
            return messageQueue.push({
                content: content,
                opts: msgOpts,
                callback: callback
            });
        }

        if (typeof msgOpts === 'function') {
            callback = msgOpts;
            msgOpts = {};
        }

        msgOpts = assign({}, options, msgOpts);

        if (channel.publish(
            msgOpts.exchangeName || options.exchangeName,
            msgOpts.routingKey || options.routingKey,
            Buffer.isBuffer(content) ? content : new Buffer(content),
            omit(msgOpts, ['exchangeName', 'routingKey'])
        )) {
            // Written to buffer, return
            return callback && setImmediate(callback);
        }

        if (callback) {
            writeCallbackQueue.push(callback);
        }

        return null;
    }

    /**
     * Send a message directly to a queue
     *
     * @param  {String}   queue    Queue to send message to
     * @param  {Buffer}   content  Content of the message
     * @param  {Object}   msgOpts  Optional message-specific options - will be merged with publisher options
     * @param  {Function} callback Function to call when message has been written to the write buffer
     * @return {void}
     */
    function sendToQueue(queue, content, msgOpts, callback) {
        if (!isReady) {
            return messageQueue.push({
                content: content,
                opts: msgOpts,
                queue: queue,
                callback: callback
            });
        }

        if (typeof msgOpts === 'function') {
            callback = msgOpts;
            msgOpts = {};
        }

        msgOpts = assign({}, options, msgOpts);

        if (channel.sendToQueue(
            queue,
            Buffer.isBuffer(content) ? content : new Buffer(content),
            omit(msgOpts, ['exchangeName', 'routingKey'])
        )) {
            return callback && setImmediate(callback);
        }

        if (callback) {
            writeCallbackQueue.push(callback);
        }

        return null;
    }

    /**
     * Flush the internal queue of unpublished messages
     *
     * @return {void}
     */
    function flushQueue() {
        var msg;
        while (messageQueue.length) {
            msg = messageQueue.shift();

            if (msg.queue) {
                sendToQueue(msg.queue, msg.content, msg.opts, msg.callback);
            } else {
                publish(msg.content, msg.opts, msg.callback);
            }
        }
    }

    /**
     * Trigger all the queued write callbacks
     *
     * @return {void}
     */
    function triggerWriteCallbacks() {
        while (writeCallbackQueue.length) {
            writeCallbackQueue.shift()();
        }
    }
}

module.exports = publisher;
<|endoftext|>


<commit_before>var XLSX = require('./xlsx');
var XLS = require('xlsjs');
var path = require('path');

var trim = function (s) {
  if (s == undefined) return "";
  s = s.replace(/(^\s*)|(\s*$)/gi, "");
  s = s.replace(/[ ]{2,}/gi, " ");
  s = s.replace(/\n /, "\n");
  return s;
}

var cellIdToCellIdx = function(cellId) {

  var i, col = 0;
  for ( i = 0; i < cellId.length; ++i) {
    if (cellId[i] < 65) {
      break;
    }

    if (i == 1 && col == 0){ //for handing "A_"
      col += ("Z".charCodeAt(0) -65 +1);
    }

    col += cellId.charCodeAt(i) - 65;  // cell[i] - 'A'; zero based
  }

  // col can not be larger then 50
  // thats silly
  if (col > 50)
    col = 50;

  var row = parseInt(cellId.substr(i), 10) - 1;  // the row number the user is looking for (zero-based)

  return {
    row : row,
    col : col
  };
}

exports.getSheets = function(filename, callback){

    var reader;
    if (path.extname(filename).toLowerCase() == ".xls"){
      reader = XLS;
    }
    else if (path.extname(filename).toLowerCase() == ".xlsx"){
      reader = XLSX;
    }

    if (reader == undefined){
      console.log("No reader found for: "+ filename)
    }

    var workbook = reader.readFile(filename);

    callback(workbook);

}

exports.getDimension = function(workbook, sheetName) {
  var splt;

  if (workbook.Sheets[sheetName]['!ref'] == undefined){
    splt = "A1:A1".split(":");
  }
  else{
    splt = workbook.Sheets[sheetName]['!ref'].split(":")
  }

  return {
    min : cellIdToCellIdx(splt[0] || 'A1'),
    max : cellIdToCellIdx(splt[1] || 'A1')
  };
};

exports.readCell = function(workbook, sheetName, cellId){
      var cellContent = workbook.Sheets[sheetName][cellId] == undefined ? "": workbook.Sheets[sheetName][cellId].v;

      if (typeof cellContent === "number") {
        cellContent = cellContent.toString();
      }

      return trim(cellContent);
}

<commit_msg>fix percentage values<commit_after>var XLSX = require('./xlsx');
var XLS = require('xlsjs');
var path = require('path');

var trim = function (s) {
  if (s == undefined) return "";
  s = s.replace(/(^\s*)|(\s*$)/gi, "");
  s = s.replace(/[ ]{2,}/gi, " ");
  s = s.replace(/\n /, "\n");
  return s;
}

var cellIdToCellIdx = function(cellId) {

  var i, col = 0;
  for ( i = 0; i < cellId.length; ++i) {
    if (cellId[i] < 65) {
      break;
    }

    if (i == 1 && col == 0){ //for handing "A_"
      col += ("Z".charCodeAt(0) -65 +1);
    }

    col += cellId.charCodeAt(i) - 65;  // cell[i] - 'A'; zero based
  }

  // col can not be larger then 50
  // thats silly
  if (col > 50)
    col = 50;

  var row = parseInt(cellId.substr(i), 10) - 1;  // the row number the user is looking for (zero-based)

  return {
    row : row,
    col : col
  };
}

exports.getSheets = function(filename, callback){

    var reader;
    if (path.extname(filename).toLowerCase() == ".xls"){
      reader = XLS;
    }
    else if (path.extname(filename).toLowerCase() == ".xlsx"){
      reader = XLSX;
    }

    if (reader == undefined){
      console.log("No reader found for: "+ filename)
    }

    var workbook = reader.readFile(filename);

    callback(workbook);

}

exports.getDimension = function(workbook, sheetName) {
  var splt;

  if (workbook.Sheets[sheetName]['!ref'] == undefined){
    splt = "A1:A1".split(":");
  }
  else{
    splt = workbook.Sheets[sheetName]['!ref'].split(":")
  }

  return {
    min : cellIdToCellIdx(splt[0] || 'A1'),
    max : cellIdToCellIdx(splt[1] || 'A1')
  };
};

exports.readCell = function(workbook, sheetName, cellId){
      var cellContent;

      if (workbook.Sheets[sheetName][cellId] == undefined){
        cellContent = "";
      }
      else{
        cellContent = workbook.Sheets[sheetName][cellId].v;

        //number is in percent form
        if ( workbook.Sheets[sheetName][cellId].w.indexOf("%") > -1 &&
          Number(workbook.Sheets[sheetName][cellId].w.replace(/[^\d.-]/g, '')) == 0 ||
          Number(workbook.Sheets[sheetName][cellId].w.replace(/[^\d.-]/g, '')) / cellContent > 10){
            cellContent = cellContent * 100;
        }

      }

      debugger;
      if (typeof cellContent === "number") {
        cellContent = cellContent.toString();
      }

      return trim(cellContent);
}

<|endoftext|>


<commit_before>Polymer({
    is: 'editor-unit-input',

    behaviors: [EditorUI.focusable, Polymer.IronValidatableBehavior],

    listeners: {
        'keydown': '_onKeyDown',
        'focused-changed': '_onFocusedChanged'
    },

    properties: {
        invalid: {
            type: Boolean,
            value: false
        },

        value: {
            type: Number,
            notify: true,
            value: 0,
            observer: 'valueChanged',
        },

        inputValue: {
            type: Number,
            notify: true,
            value: 0,
            observer: 'inputValueChanged',
        },

        step: {
            type: Number,
            notify: true,
            value: 1,
        },

        min: {
            type: Number,
            notify: true,
            value: null,
        },

        max: {
            type: Number,
            notify: true,
            value: null,
        }
    },

    created: function () {
        this.lastTrueValue = 0;
    },

    ready: function () {
        this._initFocusable(this.$.input);
        this._updateMinMax();
        if (this.$.input.bindValue === '') {
            this.$.input.bindValue = '0';
        }
    },

    attached: function () {
        this.value = this.inputValue = this._convert(this.$.input.bindValue);
    },

    _updateMinMax: function () {
        this._min = (this.min!==null) ? parseFloat(this.min) : -Number.MAX_VALUE;
        this._max = (this.max!==null) ? parseFloat(this.max) : Number.MAX_VALUE;
    },

    inputValueChanged: function () {
        this.$.input.bindValue = this.inputValue.toString();
        this.fire('input-changed');
    },

    valueChanged: function () {
        this.value = this._convert(this.value);
        this.inputValue = this.value;
        this.$.input.bindValue = this._convert(this.value).toString();
    },

    confirm: function () {
        this.value = this._convert(this.$.input.bindValue);
        this.inputValue = this._convert(this.$.input.bindValue);
        this.$.input.bindValue = this.value.toString();
        this.fire('changed');
    },

    cancel: function() {
        this.$.input.bindValue = this.value.toString();
        this.fire('changed');
    },

    _onKeyDown: function (event) {
        // keydown 'enter'
        if (event.keyCode === 13) {
            this.confirm();
            this.setBlur();
            EditorUI.focusParent(this);
        }
        // keydown 'esc'
        else if (event.keyCode === 27) {
            this.cancel();
            this.setBlur();
            EditorUI.focusParent(this);
        }
    },

    _onInputKeyDown: function (event) {
        // keydown 'up'
        if (event.keyCode === 38) {
            event.preventDefault();
            this._stepUp();
        }
        // keydown 'down'
        else if (event.keyCode === 40) {
            event.preventDefault();
            this._stepDown();
        }
    },

    _stepUp: function () {
        if (this._nullToFloat(this.$.input.bindValue) + this.step >= this._max) {
            this.$.input.bindValue = this._max;
        }
        else {
            this.$.input.bindValue = this._nullToFloat(this.$.input.bindValue) + this.step;
        }
    },

    _stepDown: function () {
        if (this._nullToFloat(this.$.input.bindValue) - this.step <= this._min) {
            this.$.input.bindValue = this._min;
        }
        else {
            this.$.input.bindValue = this._nullToFloat(this.$.input.bindValue) - this.step;
        }
    },

    _increase: function (event) {
        this.timeoutID = setTimeout( function () {
            this.holdingID = setInterval( function () {
                this._stepUp();
            }.bind(this), 50);
        }.bind(this), 500 );
    },

    _decrease: function (event) {
        this.timeoutID = setTimeout( function () {
            this.holdingID = setInterval( function () {
                this._stepDown();
            }.bind(this), 50);
        }.bind(this), 500 );
    },

    _stopRoll: function () {
        clearInterval(this.holdingID);
        this.holdingID = null;

        clearTimeout(this.timeoutID);
        this.timeoutID = null;

        setTimeout(function() {
            this.confirm();
        }.bind(this), 1);
    },

    _convert: function ( val ) {
        if (val === '' || isNaN(val)) {
            return this.lastTrueValue;
        }
        val = parseFloat(parseFloat(val));
        if ( isNaN(val) )
            val = 0;
        if (this._min && this._max) {
            val = Math.min( Math.max( val, this._min ), this._max );
        }
        this.lastTrueValue = val;
        return val;
    },

    _nullToFloat: function (val) {
        if (!val) {
            return 0;
        }
        if ( isNaN(val) )
            return 0;
        return parseFloat(val);
    },

    _onBindValueChanged: function () {
        if (this.value === this._convert(this.$.input.bindValue)) {
            this.fire('input-changed');
            return;
        }
        this.inputValue = this._convert(this.$.input.bindValue);
    },

    _onFocusedChanged: function (event) {
        if (!event.detail.value) {
            this.confirm();
        }
    },
});
<commit_msg>fix bug<commit_after>Polymer({
    is: 'editor-unit-input',

    behaviors: [EditorUI.focusable, Polymer.IronValidatableBehavior],

    listeners: {
        'keydown': '_onKeyDown',
        'focused-changed': '_onFocusedChanged'
    },

    properties: {
        invalid: {
            type: Boolean,
            value: false
        },

        value: {
            type: Number,
            notify: true,
            value: 0,
            observer: 'valueChanged',
        },

        inputValue: {
            type: Number,
            notify: true,
            value: 0,
            observer: 'inputValueChanged',
        },

        step: {
            type: Number,
            notify: true,
            value: 1,
        },

        min: {
            type: Number,
            notify: true,
            value: null,
        },

        max: {
            type: Number,
            notify: true,
            value: null,
        }
    },

    created: function () {
        this._lastValidValue = 0;
    },

    ready: function () {
        this._initFocusable(this.$.input);
        this._updateMinMax();
        if (this.$.input.bindValue === '') {
            this.$.input.bindValue = '0';
        }
    },

    _updateMinMax: function () {
        this._min = (this.min!==null) ? parseFloat(this.min) : -Number.MAX_VALUE;
        this._max = (this.max!==null) ? parseFloat(this.max) : Number.MAX_VALUE;
    },

    inputValueChanged: function () {
        this.$.input.bindValue = this.inputValue.toString();
        this.fire('input-changed');
    },

    valueChanged: function () {
        this.value = this._convert(this.value);
        this.inputValue = this.value;
        this.$.input.bindValue = this._convert(this.value).toString();
    },

    confirm: function () {
        this.value = this._convert(this.$.input.bindValue);
        this.inputValue = this._convert(this.$.input.bindValue);
        this.$.input.bindValue = this.value.toString();
        this.fire('changed');
    },

    cancel: function() {
        this.$.input.bindValue = this.value.toString();
        this.fire('changed');
    },

    _onKeyDown: function (event) {
        // keydown 'enter'
        if (event.keyCode === 13) {
            this.confirm();
            this.setBlur();
            EditorUI.focusParent(this);
        }
        // keydown 'esc'
        else if (event.keyCode === 27) {
            this.cancel();
            this.setBlur();
            EditorUI.focusParent(this);
        }
    },

    _onInputKeyDown: function (event) {
        // keydown 'up'
        if (event.keyCode === 38) {
            event.preventDefault();
            this._stepUp();
        }
        // keydown 'down'
        else if (event.keyCode === 40) {
            event.preventDefault();
            this._stepDown();
        }
    },

    _stepUp: function () {
        if (this._nullToFloat(this.$.input.bindValue) + this.step >= this._max) {
            this.$.input.bindValue = this._max.toString();
        }
        else {
            this.$.input.bindValue = (this._nullToFloat(this.$.input.bindValue) + this.step).toString();
        }
    },

    _stepDown: function () {
        if (this._nullToFloat(this.$.input.bindValue) - this.step <= this._min) {
            this.$.input.bindValue = this._min.toString();
        }
        else {
            this.$.input.bindValue = (this._nullToFloat(this.$.input.bindValue) - this.step).toString();
        }
    },

    _increase: function (event) {
        this.timeoutID = setTimeout( function () {
            this.holdingID = setInterval( function () {
                this._stepUp();
            }.bind(this), 50);
        }.bind(this), 500 );
    },

    _decrease: function (event) {
        this.timeoutID = setTimeout( function () {
            this.holdingID = setInterval( function () {
                this._stepDown();
            }.bind(this), 50);
        }.bind(this), 500 );
    },

    _stopRoll: function () {
        clearInterval(this.holdingID);
        this.holdingID = null;

        clearTimeout(this.timeoutID);
        this.timeoutID = null;

        setTimeout(function() {
            this.confirm();
        }.bind(this), 1);
    },

    _convert: function ( val ) {
        if (val === '' || isNaN(val)) {
            return this._lastValidValue;
        }
        val = parseFloat(parseFloat(val));
        if ( isNaN(val) )
            val = 0;
        if (this._min && this._max) {
            val = Math.min( Math.max( val, this._min ), this._max );
        }
        this._lastValidValue = val;
        return val;
    },

    _nullToFloat: function (val) {
        if (!val) {
            return 0;
        }
        if ( isNaN(val) )
            return 0;
        return parseFloat(val);
    },

    _onBindValueChanged: function () {
        if (this.value === this._convert(this.$.input.bindValue)) {
            this.fire('input-changed');
            return;
        }
        this.inputValue = this._convert(this.$.input.bindValue);
    },

    _onFocusedChanged: function (event) {
        if (!event.detail.value) {
            this.confirm();
        }
    },
});
<|endoftext|>


<commit_before>var apiMeta = document.getElementById("api-host");
m.postgrest.init(apiMeta.getAttribute('content'), {method: "GET", url: "/api_token"});

<commit_msg>Refactors mithril-postgrest initialization script<commit_after>var apiMeta = document.getElementById("api-host");
postgrest.init(apiMeta.getAttribute('content'), {method: "GET", url: "/api_token"});

<|endoftext|>


<commit_before>var path = require('path');
var vow = require('vow');
var EventEmitter = require('events').EventEmitter;
var MakePlatform = require('enb/lib/make');
var MagicConfig = require('./magic-config');

/**
 * Хэлпер предназначен для решения задач, связанных с созданием новых нод и таргетов в процессе выполнения сборки.
 *
 * В процессе создания конфигуратора будет зарегистрирован таск c указанным именем, который предназначается для:
 * 1. Создания директорий и файлов, формирующих уровни-сеты.
 * 2. Регистрации нод и таргетов по созданным директориям и файлам.
 * 3. Запуска сборки зарегистрированных таргетов, а также всех таргетов в рамках зарегистрированных нод.
 *
 * Общение между хэлперами происходит через каналы событий. По умолчанию каждый из хэлперов создаёт следующие события:
 *
 * 1. **start** `function () { }`
 *
 * Срабатывает, когда происходит запуск таска.
 *
 * 2. **prebuild** `function (nodes, targets) { }`
 *
 * Срабатывает после создания всех уровней-сетов на файловой системе. Возвращает список всех зарегистрированных `nodes`,
 * а также список всех зарегистрированных таргетов `targets` ноды, которых не были зарегистрированны.
 *
 * 3. **build** `function (targets) { }`
 *
 * Срабатывает в случае успешного завершения сборки, возвращая список собранных таргетов.
 *
 * 4. **error** `function (err) { }`
 *
 * Срабатывает при возникновении ошибки в процессе построения или сборки уровней-сетов.
 *
 * @name MagicHelper
 * @extends EventEmitter
 * @param {String} taskName
 * @param {ProjectConfig} projectConfig
 * @constructor
 */
var MagicHelper = function (taskName, projectConfig) {
    this._chains = [];

    this._taskName = taskName;
    this._projectConfig = projectConfig;
    this._eventChannel = new EventEmitter();

    this._configureTask();
};

/**
 * Возвращает название таска, в котором происходит создание и нод и таргетов.
 *
 * @returns {String}
 */
MagicHelper.prototype.getTaskName = function () {
    return this._taskName;
};

/**
 * Возвращает конфиг, с помощью которого производится настройка сборки нод и таргетов.
 *
 * @returns {ProjectConfig}
 */
MagicHelper.prototype.getProjectConfig = function () {
    return this._projectConfig;
};

/**
 * Возвращает канал событий данного хэлпера.
 *
 * @returns {EventEmitter}
 */
MagicHelper.prototype.getEventChannel = function () {
    return this._eventChannel;
};

/**
 * Позволяет декларировать создание нод и таргетов на файловой системе для последующей их сборки.
 * Функции `callback` первым аргументом будет передан инстанс `MagicConfig`.
 *
 * Предполагается, что в функции `callback` будут производиться некие действия по созданию нод и таргетов
 * на файловой системе, которые будут зарегистрированы с помощью `MagicConfig`.
 *
 * Если несколько раз задекларировать создание уровней-сетов, то каждая такая `callback` функция будет выполняться
 * асинхронно, т.е. независимо от остальных.
 *
 * @param {Function} callback
 */
MagicHelper.prototype.prebuild = function (callback) {
    this._chains.push(callback);
};

MagicHelper.prototype._configureTask = function () {
    var _this = this;
    var projectConfig = this._projectConfig;
    var taskName = this._taskName;
    var channel = this._eventChannel;

    projectConfig.task(taskName, function (task) {
        channel.emit('start');

        var args = [].slice.call(arguments, 1);
        var magicConfig = new MagicConfig(args);

        // Запускаем сборку задекларированных `callback`-функций
        return vow.all(_this._chains.map(function (callback) {
                return callback.apply(this, [magicConfig]);
            }))
            .then(function () {
                var registeredNodes = magicConfig.getRegisteredNodes();
                var targets = magicConfig.getRegisteredTargets();
                var nodes = magicConfig.getNodes();
                var toBuild = {};

                channel.emit('prebuild', registeredNodes, targets);

                // Ничего не делаем, если нет зарегистрированных нод и таргетов
                if (nodes.length === 0 && targets.length === 0) {
                    task.log('building finished - ' + (new Date() - _this._startTime) + 'ms');
                    channel.emit('build', []);

                    return vow.resolve([]);
                }

                // Собираем все ноды, если пользователь не указал ожидаемых целей
                if (!args.length) {
                    return _this._buildTargets(nodes);
                }

                // Раскрываем цели в список нод и таргетов для сборки
                args.forEach(function (arg) {
                    // Добавляем цель в сборку, если она была зарегистрированна
                    // или входит в явно или косвенно зарегистрированную ноду
                    if (magicConfig.isRegisteredTarget(arg) || nodes.indexOf(path.dirname(arg)) !== -1) {
                        toBuild[arg] = true;
                    }

                    if (magicConfig.isRequiredNode(arg)) {
                        // Раскрываем цель в список нод
                        nodes.forEach(function (node) {
                            if (node.indexOf(arg) === 0) {
                                toBuild[node] = true;
                            }
                        });
                    }
                });

                return _this._buildTargets(Object.keys(toBuild));
            });
    });

    this._taskConfig = projectConfig.getTaskConfig(taskName);
};

MagicHelper.prototype._buildTargets = function (targets) {
    var task = this._taskConfig;
    var root = task.getMakePlatform().getDir();
    var makePlatform = new MakePlatform();
    var projectConfig = this._projectConfig;
    var channel = this._eventChannel;

    return makePlatform.init(root)
        .then(function () {
            makePlatform.loadCache();
            makePlatform._projectConfig = projectConfig;

            return makePlatform.buildTargets(targets);
        })
        .then(function () {
            makePlatform.destruct();

            channel.emit('build', targets);

            return targets;
        })
        .fail(function (err) {
            makePlatform.destruct();

            channel.emit('error', err);

            throw err;
        });
};

module.exports = MagicHelper;
<commit_msg>Removed task logging<commit_after>var path = require('path');
var vow = require('vow');
var EventEmitter = require('events').EventEmitter;
var MakePlatform = require('enb/lib/make');
var MagicConfig = require('./magic-config');

/**
 * Хэлпер предназначен для решения задач, связанных с созданием новых нод и таргетов в процессе выполнения сборки.
 *
 * В процессе создания конфигуратора будет зарегистрирован таск c указанным именем, который предназначается для:
 * 1. Создания директорий и файлов, формирующих уровни-сеты.
 * 2. Регистрации нод и таргетов по созданным директориям и файлам.
 * 3. Запуска сборки зарегистрированных таргетов, а также всех таргетов в рамках зарегистрированных нод.
 *
 * Общение между хэлперами происходит через каналы событий. По умолчанию каждый из хэлперов создаёт следующие события:
 *
 * 1. **start** `function () { }`
 *
 * Срабатывает, когда происходит запуск таска.
 *
 * 2. **prebuild** `function (nodes, targets) { }`
 *
 * Срабатывает после создания всех уровней-сетов на файловой системе. Возвращает список всех зарегистрированных `nodes`,
 * а также список всех зарегистрированных таргетов `targets` ноды, которых не были зарегистрированны.
 *
 * 3. **build** `function (targets) { }`
 *
 * Срабатывает в случае успешного завершения сборки, возвращая список собранных таргетов.
 *
 * 4. **error** `function (err) { }`
 *
 * Срабатывает при возникновении ошибки в процессе построения или сборки уровней-сетов.
 *
 * @name MagicHelper
 * @extends EventEmitter
 * @param {String} taskName
 * @param {ProjectConfig} projectConfig
 * @constructor
 */
var MagicHelper = function (taskName, projectConfig) {
    this._chains = [];

    this._taskName = taskName;
    this._projectConfig = projectConfig;
    this._eventChannel = new EventEmitter();

    this._configureTask();
};

/**
 * Возвращает название таска, в котором происходит создание и нод и таргетов.
 *
 * @returns {String}
 */
MagicHelper.prototype.getTaskName = function () {
    return this._taskName;
};

/**
 * Возвращает конфиг, с помощью которого производится настройка сборки нод и таргетов.
 *
 * @returns {ProjectConfig}
 */
MagicHelper.prototype.getProjectConfig = function () {
    return this._projectConfig;
};

/**
 * Возвращает канал событий данного хэлпера.
 *
 * @returns {EventEmitter}
 */
MagicHelper.prototype.getEventChannel = function () {
    return this._eventChannel;
};

/**
 * Позволяет декларировать создание нод и таргетов на файловой системе для последующей их сборки.
 * Функции `callback` первым аргументом будет передан инстанс `MagicConfig`.
 *
 * Предполагается, что в функции `callback` будут производиться некие действия по созданию нод и таргетов
 * на файловой системе, которые будут зарегистрированы с помощью `MagicConfig`.
 *
 * Если несколько раз задекларировать создание уровней-сетов, то каждая такая `callback` функция будет выполняться
 * асинхронно, т.е. независимо от остальных.
 *
 * @param {Function} callback
 */
MagicHelper.prototype.prebuild = function (callback) {
    this._chains.push(callback);
};

MagicHelper.prototype._configureTask = function () {
    var _this = this;
    var projectConfig = this._projectConfig;
    var taskName = this._taskName;
    var channel = this._eventChannel;

    projectConfig.task(taskName, function (task) {
        channel.emit('start');

        var args = [].slice.call(arguments, 1);
        var magicConfig = new MagicConfig(args);

        // Запускаем сборку задекларированных `callback`-функций
        return vow.all(_this._chains.map(function (callback) {
                return callback.apply(this, [magicConfig]);
            }))
            .then(function () {
                var registeredNodes = magicConfig.getRegisteredNodes();
                var targets = magicConfig.getRegisteredTargets();
                var nodes = magicConfig.getNodes();
                var toBuild = {};

                channel.emit('prebuild', registeredNodes, targets);

                // Ничего не делаем, если нет зарегистрированных нод и таргетов
                if (nodes.length === 0 && targets.length === 0) {
                    channel.emit('build', []);

                    return vow.resolve([]);
                }

                // Собираем все ноды, если пользователь не указал ожидаемых целей
                if (!args.length) {
                    return _this._buildTargets(nodes);
                }

                // Раскрываем цели в список нод и таргетов для сборки
                args.forEach(function (arg) {
                    // Добавляем цель в сборку, если она была зарегистрированна
                    // или входит в явно или косвенно зарегистрированную ноду
                    if (magicConfig.isRegisteredTarget(arg) || nodes.indexOf(path.dirname(arg)) !== -1) {
                        toBuild[arg] = true;
                    }

                    if (magicConfig.isRequiredNode(arg)) {
                        // Раскрываем цель в список нод
                        nodes.forEach(function (node) {
                            if (node.indexOf(arg) === 0) {
                                toBuild[node] = true;
                            }
                        });
                    }
                });

                return _this._buildTargets(Object.keys(toBuild));
            });
    });

    this._taskConfig = projectConfig.getTaskConfig(taskName);
};

MagicHelper.prototype._buildTargets = function (targets) {
    var task = this._taskConfig;
    var root = task.getMakePlatform().getDir();
    var makePlatform = new MakePlatform();
    var projectConfig = this._projectConfig;
    var channel = this._eventChannel;

    return makePlatform.init(root)
        .then(function () {
            makePlatform.loadCache();
            makePlatform._projectConfig = projectConfig;

            return makePlatform.buildTargets(targets);
        })
        .then(function () {
            makePlatform.destruct();

            channel.emit('build', targets);

            return targets;
        })
        .fail(function (err) {
            makePlatform.destruct();

            channel.emit('error', err);

            throw err;
        });
};

module.exports = MagicHelper;
<|endoftext|>


<commit_before>define([
    'dojo/text!ijit/widgets/notify/templates/ChangeRequest.html',

    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/Color',
    'dojo/_base/array',
    'dojo/_base/json',

    'dojo/dom-style',
    'dojo/dom-attr',
    'dojo/dom-class',

    'dojo/on',
    'dojo/query',
    'dojo/string',
    'dojo/aspect',
    'dojo/request',

    'dijit/_WidgetBase',
    'dijit/_TemplatedMixin',

    'esri/toolbars/draw',
    'esri/symbols/SimpleLineSymbol',
    'esri/graphic'
], function(
    template,

    declare,
    lang,
    Color,
    array,
    dojoJson,

    style,
    domAttr,
    domClass,

    on,
    query,
    dojoString,
    aspect,
    request,

    widgetBase,
    templatedMixin,

    Draw,
    SimpleLineSymbol,
    Graphic
) {
    // summary:
    //      Allows a user to markup a map, give a description,
    //      and submit the shape and description for review.
    //      This widget hits the email service.
    //      A separate viewer page will show the markup made.

    return declare([widgetBase, templatedMixin], {
        templateString: template,
        baseClass: 'change-request',
        map: null,
        title: 'Report Map Issue',
        graphicsLayer: null,
        _graphic: null,
        toolbar: null,
        symbol: null,

        constructor: function() {
            // summary:
            //      first function to fire after page loads
            console.info('agrc.ijit.widgets.notify.ChangeRequest::constructor', arguments, arguments);
        },

        postMixInProperties: function() {
            // summary:
            //      postMixin properties like symbol and graphics layer
            // description:
            //      decide whether to use default graphics layer and symbol
            // tags:
            //      public
            console.info('agrc.ijit.widgets.notify.ChangeRequest::postMixInProperties', arguments);

            // default to use the map's graphics layer if none was passed in
            if (!this.graphicsLayer && !!this.map) {
                this.graphicsLayer = this.map.graphics;

                //if maps already loaded just set this first.
                this.own(
                    on(this.map, 'Load', lang.hitch(this, function() {
                        this.graphicsLayer = this.map.graphics;
                    }))
                );
            }

            // create symbol if none was provided in options
            if (!this.symbol && !!this.map) {
                this.symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                    new Color([255, 0, 0]), 1);
            }

            this.toolbar = new Draw(this.map);
            this.toolbar.setLineSymbol(this.symbol);
        },

        postCreate: function() {
            console.info('agrc.ijit.widgets.notify.ChangeRequest::postCreate', arguments);

            this.formRedline.onsubmit = function() {
                return false;
            };

            var scoped = this;
            this.own(
                on(this.btnSubmit, 'click', lang.hitch(this, 'submitRedline')),
                on(this.btnRedline, 'click', lang.hitch(this, 'onDrawStart')),
                aspect.after(this.toolbar, 'onDrawEnd', lang.hitch(this, 'onDrawEnd'), true),
                aspect.after(this.toolbar, 'activate', function() {
                    domAttr.set(scoped.btnRedline, 'disabled', true);
                }),
                aspect.after(this.toolbar, 'deactivate', function() {
                    domAttr.set(scoped.btnRedline, 'disabled', false);
                })
            );
        },

        onDrawStart: function() {
            console.info('agrc.ijit.widgets.notify.ChangeRequest::onDrawStart', arguments);

            if (this.map && this._graphic) {
                this.graphicsLayer.remove(this._graphic);
            }

            this.toolbar.activate(Draw.FREEHAND_POLYLINE);
        },

        onDrawEnd: function(geometry) {
            console.info('agrc.ijit.widgets.notify.ChangeRequest::onDrawEnd', arguments);

            this._graphic = new Graphic(geometry, this.symbol);
            this.graphicsLayer.add(this._graphic);

            this.toolbar.deactivate();

            //this.txtDescription.focus();
        },

        submitRedline: function() {
            // summary:
            //      submits the change request.
            console.info('agrc.ijit.widgets.notify.ChangeRequest::submitRedline', arguments);

            if (!this._validate()) {
                return false;
            }

            if (this.map && this._graphic) {
                this.graphicsLayer.remove(this._graphic);
            }

            var description = this.txtDescription.value;

            if (this.request) {
                this.request.cancel('duplicate in flight');
                this.request = null;
            }

            this.btnSubmit.innerHTML = 'Submitting...';

            this.request = this._invokeWebService({
                description: description
            }).then(
                lang.hitch(this, 'completed'), lang.hitch(this, 'error')
            );

            return false;
        },

        _validate: function() {
            // summary:
            //      validates the widget
            // description:
            //      makes sure everything is the way it needs to be
            // tags:
            //      private
            // returns:
            //      bool
            console.info('agrc.ijit.widgets.notify.ChangeRequest::_validate', arguments);

            var that = this;

            // hide error messages
            query('.help-inline.error', this.domNode).style('display', 'none');
            query('.control-group', this.domNode).removeClass('error');

            return array.every([
                    this.txtDescription
                ],
                function(tb) {
                    return that._isValid(tb);
                });
        },

        _isValid: function(textBox) {
            // summary:
            //      validates that there are values in the textbox
            // textBox: TextBox Element
            console.log('agrc.ijit.widgets.notify.ChangeRequest::_isValid', arguments);

            var valid = dojoString.trim(textBox.value).length > 0;

            if (!valid) {
                query('span', textBox.parentElement).style('display', 'inline');
                domClass.add(textBox.parentElement.parentElement, 'error');
            }

            return valid;
        },

        _invokeWebService: function(args) {
            // summary:
            //      calls the web service
            // description:
            //      sends the request to the service
            // tags:
            //      private
            // returns:
            //     Deferred
            console.info('agrc.ijit.widgets.notify.ChangeRequest::_invokeWebService', arguments);

            var url = '/sendemailservice/notify';

            var options = {
                email: {
                    toIds: [3],
                    fromId: 2
                },
                template: {
                    templateId: 3,
                    templateValues: {
                        description: args.description,
                        application: window.location.href,
                        basemap: this.map.layerIds[0]
                    }
                }
            };

            if (this._graphic && this._graphic.geometry) {
                options.template.templateValues.link = 'http://localhost/experimental/GraphicViewer?' +
                    'center={{center}}&level={{level}}&redline={{redline}}';
                options.template.templateValues.center = this.map.extent.getCenter().toJson();
                options.template.templateValues.level = this.map.getLevel();
                options.template.templateValues.redline = this._graphic.geometry.toJson();
            }

            //options.template = dojoJson.toJson(options.template);
            return request.post(url, {
                data: dojoJson.toJson(options),
                headers: {
                    'Content-Type': 'application/json'
                }
            });
        },

        completed: function() {
            console.info('agrc.ijit.widgets.notify.ChangeRequest::completed', arguments);

            this._graphic = null;
            this.txtDescription.value = '';
            this.btnSubmit.innerHTML = 'Thanks!';
        },

        error: function() {
            // summary:
            //      handles script io error
            // description:
            //      publishes error
            // tags:
            //      private
            // returns:
            //
            console.info('agrc.ijit.widgets.notify.ChangeRequest::error', arguments);

            style.set(this.errorMsg, 'display', 'inline');
            domClass.add(this.errorMsg.parentElement.parentElement, 'error');
            this.btnSubmit.innerHTML = 'Whoops.';
        }
    });
});<commit_msg>update redline viewer to be a param<commit_after>define([
    'dojo/text!ijit/widgets/notify/templates/ChangeRequest.html',

    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/Color',
    'dojo/_base/array',
    'dojo/_base/json',

    'dojo/dom-style',
    'dojo/dom-attr',
    'dojo/dom-class',

    'dojo/on',
    'dojo/query',
    'dojo/string',
    'dojo/aspect',
    'dojo/request',

    'dijit/_WidgetBase',
    'dijit/_TemplatedMixin',

    'esri/toolbars/draw',
    'esri/symbols/SimpleLineSymbol',
    'esri/graphic'
], function(
    template,

    declare,
    lang,
    Color,
    array,
    dojoJson,

    style,
    domAttr,
    domClass,

    on,
    query,
    dojoString,
    aspect,
    request,

    widgetBase,
    templatedMixin,

    Draw,
    SimpleLineSymbol,
    Graphic
) {
    // summary:
    //      Allows a user to markup a map, give a description,
    //      and submit the shape and description for review.
    //      This widget hits the email service.
    //      A separate viewer page will show the markup made.

    return declare([widgetBase, templatedMixin], {
        templateString: template,
        baseClass: 'change-request',
        // a reference to the map
        map: null,
        // the title to display on the widget
        title: 'Report Map Issue',
        // a reference to the graphics layer
        graphicsLayer: null,
        // a reference to the graphic on the map
        _graphic: null,
        // the drawing toolbar
        toolbar: null,
        // the redline symbol
        symbol: null,
        // the base url to the redliner applicatin
        redliner: null,

        constructor: function() {
            // summary:
            //      first function to fire after page loads
            console.info('agrc.ijit.widgets.notify.ChangeRequest::constructor', arguments, arguments);
        },

        postMixInProperties: function() {
            // summary:
            //      postMixin properties like symbol and graphics layer
            // description:
            //      decide whether to use default graphics layer and symbol
            // tags:
            //      public
            console.info('agrc.ijit.widgets.notify.ChangeRequest::postMixInProperties', arguments);

            // default to use the map's graphics layer if none was passed in
            if (!this.graphicsLayer && !!this.map) {
                this.graphicsLayer = this.map.graphics;

                //if maps already loaded just set this first.
                this.own(
                    on(this.map, 'Load', lang.hitch(this, function() {
                        this.graphicsLayer = this.map.graphics;
                    }))
                );
            }

            // create symbol if none was provided in options
            if (!this.symbol && !!this.map) {
                this.symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                    new Color([255, 0, 0]), 1);
            }

            this.toolbar = new Draw(this.map);
            this.toolbar.setLineSymbol(this.symbol);
        },

        postCreate: function() {
            console.info('agrc.ijit.widgets.notify.ChangeRequest::postCreate', arguments);

            this.formRedline.onsubmit = function() {
                return false;
            };

            var scoped = this;
            this.own(
                on(this.btnSubmit, 'click', lang.hitch(this, 'submitRedline')),
                on(this.btnRedline, 'click', lang.hitch(this, 'onDrawStart')),
                aspect.after(this.toolbar, 'onDrawEnd', lang.hitch(this, 'onDrawEnd'), true),
                aspect.after(this.toolbar, 'activate', function() {
                    domAttr.set(scoped.btnRedline, 'disabled', true);
                }),
                aspect.after(this.toolbar, 'deactivate', function() {
                    domAttr.set(scoped.btnRedline, 'disabled', false);
                })
            );
        },

        onDrawStart: function() {
            console.info('agrc.ijit.widgets.notify.ChangeRequest::onDrawStart', arguments);

            if (this.map && this._graphic) {
                this.graphicsLayer.remove(this._graphic);
            }

            this.toolbar.activate(Draw.FREEHAND_POLYLINE);
        },

        onDrawEnd: function(geometry) {
            console.info('agrc.ijit.widgets.notify.ChangeRequest::onDrawEnd', arguments);

            this._graphic = new Graphic(geometry, this.symbol);
            this.graphicsLayer.add(this._graphic);

            this.toolbar.deactivate();
        },

        submitRedline: function() {
            // summary:
            //      submits the change request.
            console.info('agrc.ijit.widgets.notify.ChangeRequest::submitRedline', arguments);

            if (!this._validate()) {
                return false;
            }

            if (this.map && this._graphic) {
                this.graphicsLayer.remove(this._graphic);
            }

            var description = this.txtDescription.value;

            if (this.request) {
                this.request.cancel('duplicate in flight');
                this.request = null;
            }

            this.btnSubmit.innerHTML = 'Submitting...';

            this.request = this._invokeWebService({
                description: description
            }).then(
                lang.hitch(this, 'completed'), lang.hitch(this, 'error')
            );

            return false;
        },

        _validate: function() {
            // summary:
            //      validates the widget
            // description:
            //      makes sure everything is the way it needs to be
            // tags:
            //      private
            // returns:
            //      bool
            console.info('agrc.ijit.widgets.notify.ChangeRequest::_validate', arguments);

            var that = this;

            // hide error messages
            query('.help-inline.error', this.domNode).style('display', 'none');
            query('.control-group', this.domNode).removeClass('error');

            return array.every([
                    this.txtDescription
                ],
                function(tb) {
                    return that._isValid(tb);
                });
        },

        _isValid: function(textBox) {
            // summary:
            //      validates that there are values in the textbox
            // textBox: TextBox Element
            console.log('agrc.ijit.widgets.notify.ChangeRequest::_isValid', arguments);

            var valid = dojoString.trim(textBox.value).length > 0;

            if (!valid) {
                query('span', textBox.parentElement).style('display', 'inline');
                domClass.add(textBox.parentElement.parentElement, 'error');
            }

            return valid;
        },

        _invokeWebService: function(args) {
            // summary:
            //      calls the web service
            // description:
            //      sends the request to the service
            // tags:
            //      private
            // returns:
            //     Deferred
            console.info('agrc.ijit.widgets.notify.ChangeRequest::_invokeWebService', arguments);

            var url = '/sendemailservice/notify';

            var options = {
                email: {
                    toIds: [3],
                    fromId: 2
                },
                template: {
                    templateId: 3,
                    templateValues: {
                        description: args.description,
                        application: window.location.href,
                        basemap: this.map.layerIds[0]
                    }
                }
            };

            if (this._graphic && this._graphic.geometry) {
                options.template.templateValues.link = this.redliner +
                    '?center={{center}}&level={{level}}&redline={{redline}}';
                options.template.templateValues.center = this.map.extent.getCenter().toJson();
                options.template.templateValues.level = this.map.getLevel();
                options.template.templateValues.redline = this._graphic.geometry.toJson();
            }

            //options.template = dojoJson.toJson(options.template);
            return request.post(url, {
                data: dojoJson.toJson(options),
                headers: {
                    'Content-Type': 'application/json'
                }
            });
        },

        completed: function() {
            console.info('agrc.ijit.widgets.notify.ChangeRequest::completed', arguments);

            this._graphic = null;
            this.txtDescription.value = '';
            this.btnSubmit.innerHTML = 'Thanks!';
        },

        error: function() {
            // summary:
            //      handles script io error
            // description:
            //      publishes error
            // tags:
            //      private
            // returns:
            //
            console.info('agrc.ijit.widgets.notify.ChangeRequest::error', arguments);

            style.set(this.errorMsg, 'display', 'inline');
            domClass.add(this.errorMsg.parentElement.parentElement, 'error');
            this.btnSubmit.innerHTML = 'Whoops.';
        }
    });
});<|endoftext|>