<commit_before>var domain = document.domain;
var url = document.URL;
var journalId = 2;

if(typeof(String.prototype.trim) === "undefined")
{
    String.prototype.trim = function()
    {
        return String(this).replace(/^\s+|\s+$/g, '');
    };
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function startArticleSubmission(){

    setCookie('articleSubmissionStarted', 1, 24);
    loginAsAuthor();
}

function loginAsAuthor(){
    var current_user = $('.user-menu .dropdown-menu li:eq(0) a').html();
    console.log('current user: '+ current_user);
    if(current_user == '@demo_author'){
        console.log('Correct author user.');
        window.location = 'http://ojs.dev/user';
    }else{
        window.location = "http://ojs.dev/logout";
    }
}

function clickArticleSubmitButton(){
    var subformCount = $('#parse-citations-button').parent().parent().parent().find('.submission-subform').length;
    if(subformCount < 1){
        console.log('not this time');
        return null;
    }
    console.log(typeof submittedArticleForm);
    if(typeof submittedArticleForm == 'boolean'){
        return;
    }
    submittedArticleForm = true;
    $('#ojs_article_submission_save').click();
    console.log('i clicked to submit form');
    setCookie('submitArticleOnPreview', 1, 8);
}

function fillArticleTrAbstract(){

    if(typeof abstractTransformed !== 'undefined'){
        return;
    }
    abstractTransformed = true;
    $('#ojs_article_submission_translations_tr_abstract').remove();
    $('form[name="ojs_article_submission"]').append('<input name="ojs_article_submission[translations][tr][abstract]" value="hello baby whats up" />');
}

if(url == "http://ojs.dev/#workflow-test"){

    startArticleSubmission();
}

if(url == "http://ojs.dev/"){
    if(getCookie('articleSubmissionStarted') == '1'){
        window.location = "http://ojs.dev/login";
    }
}

if(url == "http://ojs.dev/login"){
    if(getCookie('articleSubmissionStarted') == '1'){
        $("#username").val('demo_author');
        $("#password").val('demo');
        $("#password").parent().parent().find('button').click();
    }
}

if(url == 'http://ojs.dev/user'){
    if(getCookie('articleSubmissionStarted') == '1'){
        window.location = 'http://ojs.dev/journal/'+journalId+'/submission/start#workflow-test';
    }
}

if(url == 'http://ojs.dev/journal/'+journalId+'/submission/start#workflow-test'){
    $('#ojs_article_submission_checks_0').prop( "checked", true );
    $('#ojs_article_submission_checks_1').prop( "checked", true );
    $('#ojs_article_submission_checks_2').prop( "checked", true );
    $('#ojs_article_submission_save').click();
}

if(url == 'http://ojs.dev/journal/'+journalId+'/submission/new#workflow-test'){
    $('#ojs_article_submission_articleType').val(5);
    $('#ojs_article_submission_subjects').val([3,4]);
    $('#ojs_article_submission_translations_tr_title').val('hello workflow test tr title');
    $('#ojs_article_submission_translations_tr_keywords').append('<option selected>behram</option>\
    <option selected>workflow</option>\
    <option selected>test</option>');
    setInterval(function(){ fillArticleTrAbstract(); }, 1000);
    $('#raw-citations').val('Amann, Markus. Pulmonary system limitations to endurance exercise performance in humans. Exp Physiol, 2012; 97(3):311–18.');
    $('#parse-citations-button').click();
    $('#ojs_article_submission_articleFiles_0_file').val('article.txt');
    $('#ojs_article_submission_articleFiles_0_title').val('sample workflow test file title ');
    $('#ojs_article_submission_articleFiles_0_description').val('sample workflow test file description');

    setInterval(function(){ clickArticleSubmitButton(); }, 1000);
}

if(url.match(new RegExp('journal/'+journalId+'/submission/preview', 'g'))){
    if(getCookie('submitArticleOnPreview') == '1'){
        $('#ojs_article_submission_note').val('Merhaba editör bu ilk makalem lütfen kkabul edin!');
        var myJavaScript = "var confirm = false;";
        var scriptTag = document.createElement("script");
        scriptTag.innerHTML = myJavaScript;
        document.head.appendChild(scriptTag);

        $('#ojs_article_submission_submit').click();
    }
}

if(url.match(new RegExp('/journal/'+journalId+'/submission/me', 'g'))){
    window.location = 'http://ojs.dev/journal/'+journalId+'/workflow/active';
}

if(url.match(new RegExp('/journal/'+journalId+'/workflow/active', 'g'))){
    window.location = 'http://ojs.dev'+$('#flow-list tr:last td:eq(1) a').attr('href')+'#workflow-test';
}

function closeOkMessages(){
    if($('button.confirm').length > 0){
        $('button.confirm')[0].click();
    }
}
function waitStep1load(){

    if(typeof step1Loaded !== 'undefined'){
        return;
    }
    if($('#dialogs-box-1').length == 1 && $('#dialogs-box-1').text().trim() !== 'installing.dialogs...'){
        $('.panel-heading .dropdown-toggle:eq(0)').click();
        $('.step-actions-menu li:eq(0) a')[0].click();
        setInterval(function(){ assignGrammerEditor(); }, 1000);
        step1Loaded = true;
    }
}

function assignGrammerEditor(){
    if(typeof assignGrammerEditorVar !== 'undefined'){
        return;
    }
    if($('select[name="dialog[users][]"]').length > 0){
        $('select[name="dialog[users][]"]').remove();
        $('form[name="dialog"]').append('<input name="dialog[users][]" value="4"/>');
        $('form[name="dialog"]').parent().find('button')[0].click();
        assignGrammerEditorVar = true;
        console.log('click spelling button');
        console.log('assigned grammer editor');
        setInterval(function(){ closeOkMessages(); }, 500);
        setInterval(function(){ assignSpellingEditor(); }, 1000);
        setTimeout(function(){ $('.step-actions-menu li:eq(1) a')[0].click() }, 4000);
    }
}

function assignSpellingEditor(){
    if(typeof assignSpellingEditorVar !== 'undefined'){
        return;
    }
    if($('select[name="dialog[users][]"]').length > 0){
        console.log('finded form');
        $('select[name="dialog[users][]"]').remove();
        $('form[name="dialog"]').append('<input name="dialog[users][]" value="5"/>');
        $('form[name="dialog"]').parent().find('button')[0].click();
        assignSpellingEditorVar = true;
        console.log('assigned spelling editor');
        setTimeout(function(){ $('.step-actions-menu li:eq(2) a')[0].click() }, 4000);
        setInterval(function(){ askAuthorForCorrection(); }, 1000);
    }else{
        console.log('can not find spelling form');
    }
}

function askAuthorForCorrection(){
    if(typeof askAuthorForCorrectionVar !== 'undefined'){
        return;
    }
    if($('select[name="dialog[users][]"]').length > 0){
        $('select[name="dialog[users][]"]').remove();
        $('form[name="dialog"]').append('<input name="dialog[users][]" value="3"/>');
        $('form[name="dialog"]').parent().find('button')[0].click();
        askAuthorForCorrectionVar = true;
        console.log('assigned author');
        console.log('finished baby');
    }
}

if(url.match(new RegExp('/journal/'+journalId+'/article-workflow/', 'g')) && url.match(new RegExp('#workflow-test', 'g'))){
    setInterval(function(){ waitStep1load(); }, 2000);
}

<commit_msg>get first element for workflow on active workflows page<commit_after>var domain = document.domain;
var url = document.URL;
var journalId = 2;

if(typeof(String.prototype.trim) === "undefined")
{
    String.prototype.trim = function()
    {
        return String(this).replace(/^\s+|\s+$/g, '');
    };
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function startArticleSubmission(){

    setCookie('articleSubmissionStarted', 1, 24);
    loginAsAuthor();
}

function loginAsAuthor(){
    var current_user = $('.user-menu .dropdown-menu li:eq(0) a').html();
    console.log('current user: '+ current_user);
    if(current_user == '@demo_author'){
        console.log('Correct author user.');
        window.location = 'http://ojs.dev/user';
    }else{
        window.location = "http://ojs.dev/logout";
    }
}

function clickArticleSubmitButton(){
    var subformCount = $('#parse-citations-button').parent().parent().parent().find('.submission-subform').length;
    if(subformCount < 1){
        console.log('not this time');
        return null;
    }
    console.log(typeof submittedArticleForm);
    if(typeof submittedArticleForm == 'boolean'){
        return;
    }
    submittedArticleForm = true;
    $('#ojs_article_submission_save').click();
    console.log('i clicked to submit form');
    setCookie('submitArticleOnPreview', 1, 8);
}

function fillArticleTrAbstract(){

    if(typeof abstractTransformed !== 'undefined'){
        return;
    }
    abstractTransformed = true;
    $('#ojs_article_submission_translations_tr_abstract').remove();
    $('form[name="ojs_article_submission"]').append('<input name="ojs_article_submission[translations][tr][abstract]" value="hello baby whats up" />');
}

if(url == "http://ojs.dev/#workflow-test"){

    startArticleSubmission();
}

if(url == "http://ojs.dev/"){
    if(getCookie('articleSubmissionStarted') == '1'){
        window.location = "http://ojs.dev/login";
    }
}

if(url == "http://ojs.dev/login"){
    if(getCookie('articleSubmissionStarted') == '1'){
        $("#username").val('demo_author');
        $("#password").val('demo');
        $("#password").parent().parent().find('button').click();
    }
}

if(url == 'http://ojs.dev/user'){
    if(getCookie('articleSubmissionStarted') == '1'){
        window.location = 'http://ojs.dev/journal/'+journalId+'/submission/start#workflow-test';
    }
}

if(url == 'http://ojs.dev/journal/'+journalId+'/submission/start#workflow-test'){
    $('#ojs_article_submission_checks_0').prop( "checked", true );
    $('#ojs_article_submission_checks_1').prop( "checked", true );
    $('#ojs_article_submission_checks_2').prop( "checked", true );
    $('#ojs_article_submission_save').click();
}

if(url == 'http://ojs.dev/journal/'+journalId+'/submission/new#workflow-test'){
    $('#ojs_article_submission_articleType').val(5);
    $('#ojs_article_submission_subjects').val([3,4]);
    $('#ojs_article_submission_translations_tr_title').val('hello workflow test tr title');
    $('#ojs_article_submission_translations_tr_keywords').append('<option selected>behram</option>\
    <option selected>workflow</option>\
    <option selected>test</option>');
    setInterval(function(){ fillArticleTrAbstract(); }, 1000);
    $('#raw-citations').val('Amann, Markus. Pulmonary system limitations to endurance exercise performance in humans. Exp Physiol, 2012; 97(3):311–18.');
    $('#parse-citations-button').click();
    $('#ojs_article_submission_articleFiles_0_file').val('article.txt');
    $('#ojs_article_submission_articleFiles_0_title').val('sample workflow test file title ');
    $('#ojs_article_submission_articleFiles_0_description').val('sample workflow test file description');

    setInterval(function(){ clickArticleSubmitButton(); }, 1000);
}

if(url.match(new RegExp('journal/'+journalId+'/submission/preview', 'g'))){
    if(getCookie('submitArticleOnPreview') == '1'){
        $('#ojs_article_submission_note').val('Merhaba editör bu ilk makalem lütfen kkabul edin!');
        var myJavaScript = "var confirm = false;";
        var scriptTag = document.createElement("script");
        scriptTag.innerHTML = myJavaScript;
        document.head.appendChild(scriptTag);

        $('#ojs_article_submission_submit').click();
    }
}

if(url.match(new RegExp('/journal/'+journalId+'/submission/me', 'g'))){
    window.location = 'http://ojs.dev/journal/'+journalId+'/workflow/active';
}

if(url.match(new RegExp('/journal/'+journalId+'/workflow/active', 'g'))){
    window.location = 'http://ojs.dev'+$('#flow-list tr:first td:eq(1) a').attr('href')+'#workflow-test';
}

function closeOkMessages(){
    if($('button.confirm').length > 0){
        $('button.confirm')[0].click();
    }
}
function waitStep1load(){

    if(typeof step1Loaded !== 'undefined'){
        return;
    }
    if($('#dialogs-box-1').length == 1 && $('#dialogs-box-1').text().trim() !== 'installing.dialogs...'){
        $('.panel-heading .dropdown-toggle:eq(0)').click();
        $('.step-actions-menu li:eq(0) a')[0].click();
        setInterval(function(){ assignGrammerEditor(); }, 1000);
        step1Loaded = true;
    }
}

function assignGrammerEditor(){
    if(typeof assignGrammerEditorVar !== 'undefined'){
        return;
    }
    if($('select[name="dialog[users][]"]').length > 0){
        $('select[name="dialog[users][]"]').remove();
        $('form[name="dialog"]').append('<input name="dialog[users][]" value="4"/>');
        $('form[name="dialog"]').parent().find('button')[0].click();
        assignGrammerEditorVar = true;
        console.log('click spelling button');
        console.log('assigned grammer editor');
        setInterval(function(){ closeOkMessages(); }, 500);
        setInterval(function(){ assignSpellingEditor(); }, 1000);
        setTimeout(function(){ $('.step-actions-menu li:eq(1) a')[0].click() }, 4000);
    }
}

function assignSpellingEditor(){
    if(typeof assignSpellingEditorVar !== 'undefined'){
        return;
    }
    if($('select[name="dialog[users][]"]').length > 0){
        console.log('finded form');
        $('select[name="dialog[users][]"]').remove();
        $('form[name="dialog"]').append('<input name="dialog[users][]" value="5"/>');
        $('form[name="dialog"]').parent().find('button')[0].click();
        assignSpellingEditorVar = true;
        console.log('assigned spelling editor');
        setTimeout(function(){ $('.step-actions-menu li:eq(2) a')[0].click() }, 4000);
        setInterval(function(){ askAuthorForCorrection(); }, 1000);
    }else{
        console.log('can not find spelling form');
    }
}

function askAuthorForCorrection(){
    if(typeof askAuthorForCorrectionVar !== 'undefined'){
        return;
    }
    if($('select[name="dialog[users][]"]').length > 0){
        $('select[name="dialog[users][]"]').remove();
        $('form[name="dialog"]').append('<input name="dialog[users][]" value="3"/>');
        $('form[name="dialog"]').parent().find('button')[0].click();
        askAuthorForCorrectionVar = true;
        console.log('assigned author');
        console.log('finished baby');
    }
}

if(url.match(new RegExp('/journal/'+journalId+'/article-workflow/', 'g')) && url.match(new RegExp('#workflow-test', 'g'))){
    setInterval(function(){ waitStep1load(); }, 2000);
}

<|endoftext|>


<commit_before>$State = {
    isText: false,
    wordTime: 950, // Time to display a word
    wordAnim: 150, // Time to animate a word
    randomInterval: 18000,
    lastRandomIndex: -1,
    randomTimer: null,
    lastMouseUp: -1
};

// From Stack Overflow
// http://stackoverflow.com/questions/1582534/calculating-text-width-with-jquery
$.fn.textWidth = function () {
    var html_org = $(this).html();
    var html_calc = '' + html_org + '';
    $(this).html(html_calc);
    var width = $(this).find('span:first').width();
    $(this).html(html_org);
    return width;
};

// http://stackoverflow.com/questions/19491336/get-url-parameter-jquery
function getUrlParameter(sParam) {
    //var sPageURL = window.location.search.substring(1);
    //alert(sPageURL);
    var sPageURL = 'msg=HI%20I%20AM%20SAMARITAN';
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
}

$(document).ready(function () {
    // Cache the jquery things
    $State.triangle = $('#triangle');
    $State.text = $('#main p');
    $State.line = $('#main hr');

    $('#userText').addClass('hidden');
//    $('#userButton').addClass('hidden');
    // Start the triangle blinking
    blinkTriangle();
    chatWebsocket();

    // URL parameter message
    var urlMsg = getUrlParameter('msg');
    urlMsg = urlMsg.split('%20').join(' ').split('%22').join('').split('%27').join("'");
    $State.phraselist = [urlMsg];

    setTimeout(function () {
        executeSamaritan(urlMsg);
    }, $State.wordTime);

});

var blinkTriangle = function () {
    // Stop blinking if samaritan is in action
    if ($State.isText)
        return;
    $State.triangle.fadeTo(500, 0).fadeTo(500, 1, blinkTriangle);
};

var chatWebsocket = function () {
    var $msg = $('#msg');
    var $text = $('#userText');

    var WebSocket = window.WebSocket || window.MozWebSocket;

    if (WebSocket) {

        try {
            var socket = new WebSocket('wss://samaritan.tech:8001/websocket');
        } catch (e) {
        }
    }

    if (socket) {
        socket.onmessage = function (event) {
            //$msg.append('
' + event.data + '
');
            $State.text.addClass('talk');
            //var hrWidth;
            document.getElementById("msg").innerHTML = event.data;
            if ($State.text.textWidth() < 1) {
                hrWidth = 80;
            } else {
                hrWidth = $State.text.textWidth() + 20
            }
            $State.line.animate({
                'width': (hrWidth) + "px"
            }, {
                'duration': $State.wordAnim
            })
        };

        $('form').submit(function () {
            socket.send($text.val());
            $text.val('').select();
            return false;
        });
    } else {
        var error_sleep_time = 500;

        function poll() {
            $.ajax({
                url: '/new-msg/',
                type: 'GET',
                success: function (event) {
                    //$msg.append('
' + event + '
');
                    $State.text.addClass('talk');
                    //var hrWidth;
                    document.getElementById("msg").innerHTML = event.data;
                    error_sleep_time = 500;
                    poll();
                },
                error: function () {
                    error_sleep_time *= 2;
                    setTimeout(poll, error_sleep_time);
                }
            });
        }

        poll();

        $('form').submit(function () {
            $.ajax({
                url: '/new-msg/',
                type: 'POST',
                data: {text: $text.val()},
                success: function () {
                    $text.val('').select();
                }
            });
            return false;
        });
    }
};

var executeSamaritan = function (phrase) {
    if ($State.isText)
        return;

    $State.isText = true;
    var phraseArray = phrase.split(" ");
    // First, finish() the blink animation and
    // scale down the marker triangle
    $State.triangle.finish().animate({
        'font-size': '0em',
        'opacity': '1'
    }, {
        'duration': $State.wordAnim,
        // Once animation triangle scale down is complete...
        'done': function () {
            var timeStart = 0;
            // Create timers for each word
            phraseArray.forEach(function (word, i) {
                var wordTime = $State.wordTime;
                if (word.length > 8)
                    wordTime *= (word.length / 8);
                setTimeout(function () {
                    // Set the text to black, and put in the word
                    // so that the length can be measured
                    $State.text.addClass('hidden').html(word);
                    // Then animate the line with extra padding
                    $State.line.animate({
                        'width': ($State.text.textWidth() + 20) + "px"
                    }, {
                        'duration': $State.wordAnim,
                        // When line starts animating, set text to white again
                        'start': $State.text.removeClass('hidden')

                    })
                }, (timeStart + $State.wordAnim));
                timeStart += wordTime;
            });

            // Set a final timer to hide text and show triangle
            setTimeout(function () {
                    // Clear the text
                    $State.text.html("");
                    // Animate trinagle back in
                    $State.triangle.finish().animate({
                        'font-size': '4em',
                        'opacity': '1'
                    }, {
                        'duration': $State.wordAnim,
                        // Once complete, blink the triangle again and animate the line to original size
                        'done': function () {
                            $State.isText = false;
                            blinkTriangle();
                            // show textArea
                            $('#userText').removeClass('hidden');
                            document.querySelector('input').focus();

//                            $('#userButton').removeClass('hidden');
                            $State.line.animate({
                                'width': "80px"
                            }, {
                                'duration': $State.wordAnim,
                                'start': $State.text.removeClass('hidden')
                            })
                        }
                    });
                },
                timeStart + $State.wordTime);
        }
    });
};
<commit_msg>ajax support test<commit_after>$State = {
    isText: false,
    wordTime: 950, // Time to display a word
    wordAnim: 150, // Time to animate a word
    randomInterval: 18000,
    lastRandomIndex: -1,
    randomTimer: null,
    lastMouseUp: -1
};

// From Stack Overflow
// http://stackoverflow.com/questions/1582534/calculating-text-width-with-jquery
$.fn.textWidth = function () {
    var html_org = $(this).html();
    var html_calc = '' + html_org + '';
    $(this).html(html_calc);
    var width = $(this).find('span:first').width();
    $(this).html(html_org);
    return width;
};

// http://stackoverflow.com/questions/19491336/get-url-parameter-jquery
function getUrlParameter(sParam) {
    //var sPageURL = window.location.search.substring(1);
    //alert(sPageURL);
    var sPageURL = 'msg=HI%20I%20AM%20SAMARITAN';
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
}

$(document).ready(function () {
    // Cache the jquery things
    $State.triangle = $('#triangle');
    $State.text = $('#main p');
    $State.line = $('#main hr');

    $('#userText').addClass('hidden');
//    $('#userButton').addClass('hidden');
    // Start the triangle blinking
    blinkTriangle();
    chatWebsocket();

    // URL parameter message
    var urlMsg = getUrlParameter('msg');
    urlMsg = urlMsg.split('%20').join(' ').split('%22').join('').split('%27').join("'");
    $State.phraselist = [urlMsg];

    setTimeout(function () {
        executeSamaritan(urlMsg);
    }, $State.wordTime);

});

var blinkTriangle = function () {
    // Stop blinking if samaritan is in action
    if ($State.isText)
        return;
    $State.triangle.fadeTo(500, 0).fadeTo(500, 1, blinkTriangle);
};

var chatWebsocket = function () {
    var $msg = $('#msg');
    var $text = $('#userText');

    var WebSocket = window.WebSocket || window.MozWebSocket;

    if (WebSocket) {

        try {
            var socket = new WebSocket('wss://samaritan.tech:8001/websocket');
        } catch (e) {
        }
    }

    if (socket) {
        socket.onmessage = function (event) {
            //$msg.append('
' + event.data + '
');
            $State.text.addClass('talk');
            //var hrWidth;
            document.getElementById("msg").innerHTML = event.data;
            if ($State.text.textWidth() < 1) {
                hrWidth = 80;
            } else {
                hrWidth = $State.text.textWidth() + 20
            }
            $State.line.animate({
                'width': (hrWidth) + "px"
            }, {
                'duration': $State.wordAnim
            })
        };

        $('form').submit(function () {
            socket.send($text.val());
            $text.val('').select();
            return false;
        });
    } else {
        var error_sleep_time = 500;

        function poll() {
            $.ajax({
                url: 'https://samaritan.tech:8001/ajax',
                type: 'GET',
                success: function (event) {
                    //$msg.append('
' + event + '
');
                    $State.text.addClass('talk');
                    //var hrWidth;
                    document.getElementById("msg").innerHTML = event.data;
                    error_sleep_time = 500;
                    poll();
                },
                error: function () {
                    error_sleep_time *= 2;
                    setTimeout(poll, error_sleep_time);
                }
            });
        }

        poll();

        $('form').submit(function () {
            $.ajax({
                url: 'https://samaritan.tech:8001/ajax',
                type: 'POST',
                data: {text: $text.val()},
                success: function () {
                    $text.val('').select();
                }
            });
            return false;
        });
    }
};

var executeSamaritan = function (phrase) {
    if ($State.isText)
        return;

    $State.isText = true;
    var phraseArray = phrase.split(" ");
    // First, finish() the blink animation and
    // scale down the marker triangle
    $State.triangle.finish().animate({
        'font-size': '0em',
        'opacity': '1'
    }, {
        'duration': $State.wordAnim,
        // Once animation triangle scale down is complete...
        'done': function () {
            var timeStart = 0;
            // Create timers for each word
            phraseArray.forEach(function (word, i) {
                var wordTime = $State.wordTime;
                if (word.length > 8)
                    wordTime *= (word.length / 8);
                setTimeout(function () {
                    // Set the text to black, and put in the word
                    // so that the length can be measured
                    $State.text.addClass('hidden').html(word);
                    // Then animate the line with extra padding
                    $State.line.animate({
                        'width': ($State.text.textWidth() + 20) + "px"
                    }, {
                        'duration': $State.wordAnim,
                        // When line starts animating, set text to white again
                        'start': $State.text.removeClass('hidden')

                    })
                }, (timeStart + $State.wordAnim));
                timeStart += wordTime;
            });

            // Set a final timer to hide text and show triangle
            setTimeout(function () {
                    // Clear the text
                    $State.text.html("");
                    // Animate trinagle back in
                    $State.triangle.finish().animate({
                        'font-size': '4em',
                        'opacity': '1'
                    }, {
                        'duration': $State.wordAnim,
                        // Once complete, blink the triangle again and animate the line to original size
                        'done': function () {
                            $State.isText = false;
                            blinkTriangle();
                            // show textArea
                            $('#userText').removeClass('hidden');
                            document.querySelector('input').focus();

//                            $('#userButton').removeClass('hidden');
                            $State.line.animate({
                                'width': "80px"
                            }, {
                                'duration': $State.wordAnim,
                                'start': $State.text.removeClass('hidden')
                            })
                        }
                    });
                },
                timeStart + $State.wordTime);
        }
    });
};
<|endoftext|>


<commit_before>(function ($) {

	var RoomsRoom = this.RoomsRoom = Room.extend({
		minWidth: 320,
		maxWidth: 1024,
		type: 'rooms',
		title: 'Rooms',
		isSideRoom: true,
		initialize: function () {
			this.$el.addClass('ps-room-light').addClass('scrollable');
			var buf = '
<button class="button" style="float:right;font-size:10pt;margin-top:3px" name="closeHide"> Hide</button>

Loading...

<button name="joinRoomPopup" class="button">Join other room</button>

';
			this.$el.html(buf);
			app.on('response:rooms', this.update, this);
			app.send('/cmd rooms');
			app.user.on('change:named', this.updateUser, this);
			this.update();
		},
		updateUser: function () {
			this.update();
		},
		focus: function () {
			if (new Date().getTime() - this.lastUpdate > 60 * 1000) {
				app.send('/cmd rooms');
				this.lastUpdate = new Date().getTime();
			}
			var prevPos = this.$el.scrollTop();
			this.$('button[name=joinRoomPopup]').focus();
			this.$el.scrollTop(prevPos);
		},
		joinRoomPopup: function () {
			app.addPopupPrompt("Room name:", "Join room", function (room) {
				room = toRoomid(room);
				if (!room) return;
				app.tryJoinRoom(room);
			});
		},
		update: function (rooms) {
			var firstOpen = !app.roomsData;
			if (rooms) {
				this.lastUpdate = new Date().getTime();
				app.roomsData = rooms;
			} else {
				rooms = app.roomsData;
			}
			if (!rooms) return;
			this.updateRoomList();
			if (!app.roomsFirstOpen && window.location.host !== 'demo.psim.us') {
				if (Config.roomsFirstOpenScript) {
					Config.roomsFirstOpenScript();
				}
				app.roomsFirstOpen = 2;
			}
		},
		updateRoomList: function () {
			var rooms = app.roomsData;
			var buf = '';

			if (rooms.userCount) {
				var userCount = Number(rooms.userCount);
				var battleCount = Number(rooms.battleCount);
				buf += '

';
				buf += ' <button class="button" name="finduser" title="Find an online user">' + userCount + ' ' + (userCount == 1 ? 'user' : 'users') + ' online</button>	';
				buf += '<button class="button" name="roomlist" title="Watch an active battle">' + battleCount + ' active ' + (battleCount == 1 ? 'battle' : 'battles') + '</button> ';
				buf += '

';
				this.$('.roomlisttop').html(buf);
			}

			buf = '';
			buf += '
Official chat rooms
';
			for (var i = 0; i < rooms.official.length; i++) {
				var roomData = rooms.official[i];
				var id = toId(roomData.title);
				buf += '
(' + Number(roomData.userCount) + ' users) ' + Tools.escapeHTML(roomData.title) + '
' + Tools.escapeHTML(roomData.desc || '') + '
';
			}
			this.$('.roomlist').first().html(buf);

			buf = '';
			buf += '
Chat rooms
';
			rooms.chat.sort(function (a, b) {
				return b.userCount - a.userCount;
			});
			for (var i = 0; i < rooms.chat.length; i++) {
				var roomData = rooms.chat[i];
				var id = toId(roomData.title);
				var escapedDesc = Tools.escapeHTML(roomData.desc || '');
				buf += '
(' + Number(roomData.userCount) + ' users) ' + Tools.escapeHTML(roomData.title) + '
' + escapedDesc + '
';
			}
			this.$('.roomlist').last().html(buf);
		},
		roomlist: function () {
			app.joinRoom('battles');
		},
		closeHide: function () {
			app.sideRoom = app.curSideRoom = null;
			this.close();
		},
		finduser: function () {
			if (app.isDisconnected) {
				app.addPopupMessage("You are offline.");
				return;
			}
			app.addPopupPrompt("Username", "Open", function (target) {
				if (!target) return;
				if (toId(target) === 'zarel') {
					app.addPopup(Popup, {htmlMessage: "Zarel is very busy; please don't contact him this way. If you're looking for help, try joining the Help room?"});
					return;
				}
				app.addPopup(UserPopup, {name: target});
			});
		}
	});

	var BattlesRoom = this.BattlesRoom = Room.extend({
		minWidth: 320,
		maxWidth: 1024,
		type: 'battles',
		title: 'Battles',
		isSideRoom: true,
		initialize: function () {
			this.$el.addClass('ps-room-light').addClass('scrollable');
			var buf = '
<button class="button" style="float:right;font-size:10pt;margin-top:3px" name="close"> Close</button>

<button class="button" name="refresh"> Refresh</button>
';

			buf += '
Format:
<button class="select formatselect" name="selectFormat">(All formats)</button>
';
			buf += '

Loading...

';
			buf += '

';

			this.$el.html(buf);
			this.$list = this.$('.list');

			this.format = '';
			app.on('init:formats', this.initialize, this);
			app.on('response:roomlist', this.update, this);
			app.send('/cmd roomlist');
			this.update();
		},
		selectFormat: function (format, button) {
			if (!window.BattleFormats) {
				return;
			}
			var self = this;
			app.addPopup(FormatPopup, {format: format, sourceEl: button, selectType: 'watch', onselect: function (newFormat) {
				self.changeFormat(newFormat);
			}});
		},
		changeFormat: function (format) {
			this.format = format;
			app.send('/cmd roomlist ' + this.format);
			this.update();
		},
		focus: function (e) {
			if (e && $(e.target).closest('select, a').length) return;
			if (new Date().getTime() - this.lastUpdate > 60 * 1000) {
				app.send('/cmd roomlist');
				this.lastUpdate = new Date().getTime();
			}
			var prevPos = this.$el.scrollTop();
			this.$('button[name=refresh]').focus();
			this.$el.scrollTop(prevPos);
		},
		update: function (data) {
			if (!data && !this.data) {
				if (app.isDisconnected) {
					this.$list.html('
You are offline.
');
				} else {
					this.$list.html('
Loading...
');
				}
				return;
			}
			this.$('button[name=refresh]')[0].disabled = false;
			if (!data) {
				data = this.data;
			} else {
				this.data = data;
			}
			var buf = '';

			var i = 0;
			for (var id in data.rooms) {
				var roomData = data.rooms[id];
				var matches = ChatRoom.parseBattleID(id);
				if (!matches) {
					continue; // bogus room ID could be used to inject JavaScript
				}
				var format = (matches[1] || '');
				if (this.format && format !== this.format) continue;
				var formatBuf = (format ? '[' + Tools.escapeFormat(format) + ']
' : '');
				var roomDesc = formatBuf + '' + Tools.escapeHTML(roomData.p1) + ' vs. ' + Tools.escapeHTML(roomData.p2) + '';
				if (!roomData.p1) {
					matches = id.match(/[^0-9]([0-9]*)$/);
					roomDesc = formatBuf + 'empty room ' + matches[1];
				} else if (!roomData.p2) {
					roomDesc = formatBuf + '' + Tools.escapeHTML(roomData.p1) + '';
				}
				buf += '
' + roomDesc + '
';
				i++;
			}

			if (!i) {
				buf = '
No ' + Tools.escapeFormat(this.format) + ' battles are going on right now.
';
			} else {
				buf = '
' + i + (i === 100 ? '+' : '') + ' ' + Tools.escapeFormat(this.format) + ' ' + (i === 1 ? 'battle' : 'battles') + '
' + buf;
			}

			this.$list.html(buf);
		},
		refresh: function (i, button) {
			button.disabled = true;
			app.send('/cmd roomlist ' + this.format);
		}
	});

}).call(this, jQuery);
<commit_msg>Show rating/tour data in battle list<commit_after>(function ($) {

	var RoomsRoom = this.RoomsRoom = Room.extend({
		minWidth: 320,
		maxWidth: 1024,
		type: 'rooms',
		title: 'Rooms',
		isSideRoom: true,
		initialize: function () {
			this.$el.addClass('ps-room-light').addClass('scrollable');
			var buf = '
<button class="button" style="float:right;font-size:10pt;margin-top:3px" name="closeHide"> Hide</button>

Loading...

<button name="joinRoomPopup" class="button">Join other room</button>

';
			this.$el.html(buf);
			app.on('response:rooms', this.update, this);
			app.send('/cmd rooms');
			app.user.on('change:named', this.updateUser, this);
			this.update();
		},
		updateUser: function () {
			this.update();
		},
		focus: function () {
			if (new Date().getTime() - this.lastUpdate > 60 * 1000) {
				app.send('/cmd rooms');
				this.lastUpdate = new Date().getTime();
			}
			var prevPos = this.$el.scrollTop();
			this.$('button[name=joinRoomPopup]').focus();
			this.$el.scrollTop(prevPos);
		},
		joinRoomPopup: function () {
			app.addPopupPrompt("Room name:", "Join room", function (room) {
				room = toRoomid(room);
				if (!room) return;
				app.tryJoinRoom(room);
			});
		},
		update: function (rooms) {
			var firstOpen = !app.roomsData;
			if (rooms) {
				this.lastUpdate = new Date().getTime();
				app.roomsData = rooms;
			} else {
				rooms = app.roomsData;
			}
			if (!rooms) return;
			this.updateRoomList();
			if (!app.roomsFirstOpen && window.location.host !== 'demo.psim.us') {
				if (Config.roomsFirstOpenScript) {
					Config.roomsFirstOpenScript();
				}
				app.roomsFirstOpen = 2;
			}
		},
		updateRoomList: function () {
			var rooms = app.roomsData;
			var buf = '';

			if (rooms.userCount) {
				var userCount = Number(rooms.userCount);
				var battleCount = Number(rooms.battleCount);
				buf += '

';
				buf += ' <button class="button" name="finduser" title="Find an online user">' + userCount + ' ' + (userCount == 1 ? 'user' : 'users') + ' online</button>	';
				buf += '<button class="button" name="roomlist" title="Watch an active battle">' + battleCount + ' active ' + (battleCount == 1 ? 'battle' : 'battles') + '</button> ';
				buf += '

';
				this.$('.roomlisttop').html(buf);
			}

			buf = '';
			buf += '
Official chat rooms
';
			for (var i = 0; i < rooms.official.length; i++) {
				var roomData = rooms.official[i];
				var id = toId(roomData.title);
				buf += '
(' + Number(roomData.userCount) + ' users) ' + Tools.escapeHTML(roomData.title) + '
' + Tools.escapeHTML(roomData.desc || '') + '
';
			}
			this.$('.roomlist').first().html(buf);

			buf = '';
			buf += '
Chat rooms
';
			rooms.chat.sort(function (a, b) {
				return b.userCount - a.userCount;
			});
			for (var i = 0; i < rooms.chat.length; i++) {
				var roomData = rooms.chat[i];
				var id = toId(roomData.title);
				var escapedDesc = Tools.escapeHTML(roomData.desc || '');
				buf += '
(' + Number(roomData.userCount) + ' users) ' + Tools.escapeHTML(roomData.title) + '
' + escapedDesc + '
';
			}
			this.$('.roomlist').last().html(buf);
		},
		roomlist: function () {
			app.joinRoom('battles');
		},
		closeHide: function () {
			app.sideRoom = app.curSideRoom = null;
			this.close();
		},
		finduser: function () {
			if (app.isDisconnected) {
				app.addPopupMessage("You are offline.");
				return;
			}
			app.addPopupPrompt("Username", "Open", function (target) {
				if (!target) return;
				if (toId(target) === 'zarel') {
					app.addPopup(Popup, {htmlMessage: "Zarel is very busy; please don't contact him this way. If you're looking for help, try joining the Help room?"});
					return;
				}
				app.addPopup(UserPopup, {name: target});
			});
		}
	});

	var BattlesRoom = this.BattlesRoom = Room.extend({
		minWidth: 320,
		maxWidth: 1024,
		type: 'battles',
		title: 'Battles',
		isSideRoom: true,
		initialize: function () {
			this.$el.addClass('ps-room-light').addClass('scrollable');
			var buf = '
<button class="button" style="float:right;font-size:10pt;margin-top:3px" name="close"> Close</button>

<button class="button" name="refresh"> Refresh</button>
';

			buf += '
Format:
<button class="select formatselect" name="selectFormat">(All formats)</button>
';
			buf += '

Loading...

';
			buf += '

';

			this.$el.html(buf);
			this.$list = this.$('.list');

			this.format = '';
			app.on('init:formats', this.initialize, this);
			app.on('response:roomlist', this.update, this);
			app.send('/cmd roomlist');
			this.update();
		},
		selectFormat: function (format, button) {
			if (!window.BattleFormats) {
				return;
			}
			var self = this;
			app.addPopup(FormatPopup, {format: format, sourceEl: button, selectType: 'watch', onselect: function (newFormat) {
				self.changeFormat(newFormat);
			}});
		},
		changeFormat: function (format) {
			this.format = format;
			app.send('/cmd roomlist ' + this.format);
			this.update();
		},
		focus: function (e) {
			if (e && $(e.target).closest('select, a').length) return;
			if (new Date().getTime() - this.lastUpdate > 60 * 1000) {
				app.send('/cmd roomlist');
				this.lastUpdate = new Date().getTime();
			}
			var prevPos = this.$el.scrollTop();
			this.$('button[name=refresh]').focus();
			this.$el.scrollTop(prevPos);
		},
		update: function (data) {
			if (!data && !this.data) {
				if (app.isDisconnected) {
					this.$list.html('
You are offline.
');
				} else {
					this.$list.html('
Loading...
');
				}
				return;
			}
			this.$('button[name=refresh]')[0].disabled = false;
			if (!data) {
				data = this.data;
			} else {
				this.data = data;
			}
			var buf = '';

			var i = 0;
			for (var id in data.rooms) {
				var roomData = data.rooms[id];
				var matches = ChatRoom.parseBattleID(id);
				if (!matches) {
					continue; // bogus room ID could be used to inject JavaScript
				}
				var format = (matches[1] || '');
				if (this.format && format !== this.format) continue;
				var formatBuf = '';
				if (roomData.minElo) formatBuf += '(' + (typeof roomData.minElo === 'number' ? 'rated: ' : '') + roomData.minElo + ')';
				formatBuf += (format ? '[' + Tools.escapeFormat(format) + ']
' : '');
				var roomDesc = formatBuf + '' + Tools.escapeHTML(roomData.p1) + ' vs. ' + Tools.escapeHTML(roomData.p2) + '';
				if (!roomData.p1) {
					matches = id.match(/[^0-9]([0-9]*)$/);
					roomDesc = formatBuf + 'empty room ' + matches[1];
				} else if (!roomData.p2) {
					roomDesc = formatBuf + '' + Tools.escapeHTML(roomData.p1) + '';
				}
				buf += '
' + roomDesc + '
';
				i++;
			}

			if (!i) {
				buf = '
No ' + Tools.escapeFormat(this.format) + ' battles are going on right now.
';
			} else {
				buf = '
' + i + (i === 100 ? '+' : '') + ' ' + Tools.escapeFormat(this.format) + ' ' + (i === 1 ? 'battle' : 'battles') + '
' + buf;
			}

			this.$list.html(buf);
		},
		refresh: function (i, button) {
			button.disabled = true;
			app.send('/cmd roomlist ' + this.format);
		}
	});

}).call(this, jQuery);
<|endoftext|>


<commit_before>/**
 * @fileOverview Stub a mongoose model.
 */
var __ = require('lodash');

var mongoose = require('mongoose');
var Promise = require('bluebird');

var Entity = require('../..');
var fix = require('../fixture/data.fix');

var mong = module.exports = {};

var _init = false;

/**
 * Define the mong schema
 * @type {Object}
 */
mong.Schema = {
  name: {type: String, trim: true, required: true},
  sortby: {type: Number},
  _isActive: {type: Boolean, required: true, default: true},
};

/**
 * Define the mong schema related to the original
 * @type {Object}
 */
mong.SchemaRel = {
  darname: {type: String},
  parent: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'stubModel',
  },
};

/**
 * Define the mong schema with multiple relations to the original
 * @type {Object}
 */
mong.SchemaRelMult = {
  darname: {type: String},
  parents: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'stubModel',
  }],
};

/** @type {?Mongoose.Model} */
mong.Model = null;

/**
 * Initialize all the models.
 *
 * @private
 */
mong._initModels = function() {
  // init schemas
  mong.schema = new mongoose.Schema(mong.Schema);
  mong.schemaRel = new mongoose.Schema(mong.SchemaRel);
  mong.schemaRelMult = new mongoose.Schema(mong.SchemaRelMult);

  // init models
  mong.Model = mongoose.model('stubModel', mong.schema);
  mong.ModelRel = mongoose.model('stubModelRel', mong.schemaRel);
  mong.ModelRelMult = mongoose.model('stubModelRelMult', mong.schemaRelMult);
};

/**
 * Nuke the stub database.
 *
 * @param  {Function} done callback
 */
mong.nukedb = function(done) {
  // perform drop db
  mongoose.connection.db.dropDatabase(done);
};

/**
 * Create a connection with mongo.
 *
 * @param {Function(Error=)} done Optionally define a callback.
 */
mong.connect = function(done) {
  if (_init) {return done();}
  _init = true;

  // check if already connected
  if (1 === mongoose.connection.readyState) {
    done();
    return;
  }

  // http://mongoosejs.com/docs/connections.html
  var mongoUri = 'mongodb://127.0.0.1/crude-test';
  var mongoOpts = {
    server: {
      socketOptions: {
        keepAlive: 1
      }
    }
  };

  mongoose.connect(mongoUri, mongoOpts);
  var db = mongoose.connection.db;

  // rather silly callback mechanism.
  var cbDone = false;
  function onErrorLocal(err) {
    if (cbDone) {return;}
    cbDone = true;
    db.removeListener('open', onOpenLocal);
    done(err);
  }
  function onOpenLocal() {
    if (cbDone) {return;}
    cbDone = true;
    db.removeListener('error', onErrorLocal);

    mong._initModels();
    done();
  }

  mongoose.connection.once('error', onErrorLocal);
  mongoose.connection.once('open', onOpenLocal);
  // setup global mongoose event error handler
  mongoose.connection.on('error', function(err) {
    console.error('Mongoose ERROR:', err);
    throw err;
  });
};

/**
 * Setup and teardown records for testing.
 *
 */
mong.setupRecords = function() {
  setup(function() {
    var EntMong = Entity.Mongoose.extend();
    this.entity = new EntMong();
    this.entity.setModel(mong.Model);

    var EntRelMong = Entity.Mongoose.extend();
    this.entityRel = new EntRelMong();
    this.entityRel.setModel(mong.ModelRel);
    this.entityRel.eagerLoad('parent');

    var EntRelMultMong = Entity.Mongoose.extend();
    this.entityRelMult = new EntRelMultMong();
    this.entityRelMult.setModel(mong.ModelRelMult);
    this.entityRelMult.eagerLoad('parents');

  });
  setup(function() {
    return Promise.all([
      this.entity.create(fix.one),
      this.entity.create(fix.two),
    ])
      .bind(this)
      .then(function(res) {
        this.recordOne = res[0];
        this.recordTwo = res[1];
      });
  });
  setup(function() {
    var fixOne = __.clone(fix.relOne);
    var fixTwo = __.clone(fix.relTwo);
    fixOne.parent = this.recordOne._id;
    fixTwo.parent = this.recordTwo._id;

    return Promise.all([
      this.entityRel.create(fixOne),
      this.entityRel.create(fixTwo),
    ])
      .bind(this)
      .then(function(res) {
        this.recordRelOne = res[0];
        this.recordRelTwo = res[1];
      });
  });
  setup(function() {
    var fixOne = __.clone(fix.relOne);
    var fixTwo = __.clone(fix.relTwo);
    fixOne.parents = [this.recordOne._id, this.recordTwo._id];
    fixTwo.parents = [this.recordTwo._id];

    return Promise.all([
      this.entityRelMult.create(fixOne),
      this.entityRelMult.create(fixTwo),
    ])
      .bind(this)
      .then(function(res) {
        this.recordRelMultOne = res[0];
        this.recordRelMultTwo = res[1];
      });
  });
  teardown(function() {
    return Promise.all([
      this.entity.delete(),
      this.entityRel.delete(),
    ]);
  });
};
<commit_msg>update mongoose config<commit_after>/**
 * @fileOverview Stub a mongoose model.
 */
var __ = require('lodash');

var mongoose = require('mongoose');
var Promise = require('bluebird');

var Entity = require('../..');
var fix = require('../fixture/data.fix');

var mong = module.exports = {};

var _init = false;

/**
 * Define the mong schema
 * @type {Object}
 */
mong.Schema = {
  name: {type: String, trim: true, required: true},
  sortby: {type: Number},
  _isActive: {type: Boolean, required: true, default: true},
};

/**
 * Define the mong schema related to the original
 * @type {Object}
 */
mong.SchemaRel = {
  darname: {type: String},
  parent: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'stubModel',
  },
};

/**
 * Define the mong schema with multiple relations to the original
 * @type {Object}
 */
mong.SchemaRelMult = {
  darname: {type: String},
  parents: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'stubModel',
  }],
};

/** @type {?Mongoose.Model} */
mong.Model = null;

/**
 * Initialize all the models.
 *
 * @private
 */
mong._initModels = function() {
  // init schemas
  mong.schema = new mongoose.Schema(mong.Schema);
  mong.schemaRel = new mongoose.Schema(mong.SchemaRel);
  mong.schemaRelMult = new mongoose.Schema(mong.SchemaRelMult);

  // init models
  mong.Model = mongoose.model('stubModel', mong.schema);
  mong.ModelRel = mongoose.model('stubModelRel', mong.schemaRel);
  mong.ModelRelMult = mongoose.model('stubModelRelMult', mong.schemaRelMult);
};

/**
 * Nuke the stub database.
 *
 * @param  {Function} done callback
 */
mong.nukedb = function(done) {
  // perform drop db
  mongoose.connection.db.dropDatabase(done);
};

/**
 * Create a connection with mongo.
 *
 * @param {Function(Error=)} done Optionally define a callback.
 */
mong.connect = function(done) {
  if (_init) {return done();}
  _init = true;

  // check if already connected
  if (1 === mongoose.connection.readyState) {
    done();
    return;
  }

  // http://mongoosejs.com/docs/connections.html
  var mongoUri = 'mongodb://127.0.0.1/crude-test';
  var mongoOpts = {
      useNewUrlParser: true,
  };

  mongoose.connect(mongoUri, mongoOpts);
  var db = mongoose.connection.db;

  // rather silly callback mechanism.
  var cbDone = false;
  function onErrorLocal(err) {
    if (cbDone) {return;}
    cbDone = true;
    db.removeListener('open', onOpenLocal);
    done(err);
  }
  function onOpenLocal() {
    if (cbDone) {return;}
    cbDone = true;
    db.removeListener('error', onErrorLocal);

    mong._initModels();
    done();
  }

  mongoose.connection.once('error', onErrorLocal);
  mongoose.connection.once('open', onOpenLocal);
  // setup global mongoose event error handler
  mongoose.connection.on('error', function(err) {
    console.error('Mongoose ERROR:', err);
    throw err;
  });
};

/**
 * Setup and teardown records for testing.
 *
 */
mong.setupRecords = function() {
  setup(function() {
    var EntMong = Entity.Mongoose.extend();
    this.entity = new EntMong();
    this.entity.setModel(mong.Model);

    var EntRelMong = Entity.Mongoose.extend();
    this.entityRel = new EntRelMong();
    this.entityRel.setModel(mong.ModelRel);
    this.entityRel.eagerLoad('parent');

    var EntRelMultMong = Entity.Mongoose.extend();
    this.entityRelMult = new EntRelMultMong();
    this.entityRelMult.setModel(mong.ModelRelMult);
    this.entityRelMult.eagerLoad('parents');

  });
  setup(function() {
    return Promise.all([
      this.entity.create(fix.one),
      this.entity.create(fix.two),
    ])
      .bind(this)
      .then(function(res) {
        this.recordOne = res[0];
        this.recordTwo = res[1];
      });
  });
  setup(function() {
    var fixOne = __.clone(fix.relOne);
    var fixTwo = __.clone(fix.relTwo);
    fixOne.parent = this.recordOne._id;
    fixTwo.parent = this.recordTwo._id;

    return Promise.all([
      this.entityRel.create(fixOne),
      this.entityRel.create(fixTwo),
    ])
      .bind(this)
      .then(function(res) {
        this.recordRelOne = res[0];
        this.recordRelTwo = res[1];
      });
  });
  setup(function() {
    var fixOne = __.clone(fix.relOne);
    var fixTwo = __.clone(fix.relTwo);
    fixOne.parents = [this.recordOne._id, this.recordTwo._id];
    fixTwo.parents = [this.recordTwo._id];

    return Promise.all([
      this.entityRelMult.create(fixOne),
      this.entityRelMult.create(fixTwo),
    ])
      .bind(this)
      .then(function(res) {
        this.recordRelMultOne = res[0];
        this.recordRelMultTwo = res[1];
      });
  });
  teardown(function() {
    return Promise.all([
      this.entity.delete(),
      this.entityRel.delete(),
    ]);
  });
};
<|endoftext|>


<commit_before>Template.geomList.helpers({
	geoms: function() {
		return Geoms.find({projectId: Session.get('currentProjectId')}, { sort: {created_at: -1} });
	}
});<commit_msg>Added remove function to point<commit_after>Template.geomList.helpers({
	geoms: function() {
		return Geoms.find({projectId: Session.get('currentProjectId')}, { sort: {created_at: -1} });
	}
});

Template.geomList.events({
	'click #delete-point': function (e) {
		e.preventDefault();

		var confirmDelete = confirm("Are you sure you want to delete point? " + this.name);

		if (confirmDelete) {
			Geoms.remove(this._id);
		}
	}
});<|endoftext|>


<commit_before>// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Event Types.
 *
 * @author arv@google.com (Erik Arvidsson)
 * @author mirkov@google.com (Mirko Visontai)
 */

goog.provide('goog.events.EventType');

goog.require('goog.userAgent');

/**
 * Constants for event names.
 * @enum {string}
 */
goog.events.EventType = {
  // Mouse events
  CLICK: 'click',
  DBLCLICK: 'dblclick',
  MOUSEDOWN: 'mousedown',
  MOUSEUP: 'mouseup',
  MOUSEOVER: 'mouseover',
  MOUSEOUT: 'mouseout',
  MOUSEMOVE: 'mousemove',
  SELECTSTART: 'selectstart', // IE, Safari, Chrome

  // Key events
  KEYPRESS: 'keypress',
  KEYDOWN: 'keydown',
  KEYUP: 'keyup',

  // Focus
  BLUR: 'blur',
  FOCUS: 'focus',
  DEACTIVATE: 'deactivate', // IE only
  // NOTE: The following two events are not stable in cross-browser usage.
  //     WebKit and Opera implement DOMFocusIn/Out.
  //     IE implements focusin/out.
  //     Gecko implements neither see bug at
  //     https://bugzilla.mozilla.org/show_bug.cgi?id=396927.
  // The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin:
  //     http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
  // You can use FOCUS in Capture phase until implementations converge.
  FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
  FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',

  // Forms
  CHANGE: 'change',
  SELECT: 'select',
  SUBMIT: 'submit',
  INPUT: 'input',
  PROPERTYCHANGE: 'propertychange', // IE only

  // Drag and drop
  DRAGSTART: 'dragstart',
  DRAGENTER: 'dragenter',
  DRAGOVER: 'dragover',
  DRAGLEAVE: 'dragleave',
  DROP: 'drop',

  // WebKit touch events.
  TOUCHSTART: 'touchstart',
  TOUCHMOVE: 'touchmove',
  TOUCHEND: 'touchend',
  TOUCHCANCEL: 'touchcancel',

  // Misc
  CONTEXTMENU: 'contextmenu',
  ERROR: 'error',
  HELP: 'help',
  LOAD: 'load',
  LOSECAPTURE: 'losecapture',
  READYSTATECHANGE: 'readystatechange',
  RESIZE: 'resize',
  SCROLL: 'scroll',
  UNLOAD: 'unload',

  // HTML 5 History events
  // See http://www.w3.org/TR/html5/history.html#event-definitions
  HASHCHANGE: 'hashchange',
  PAGEHIDE: 'pagehide',
  PAGESHOW: 'pageshow',
  POPSTATE: 'popstate',

  // Copy and Paste
  // Support is limited. Make sure it works on your favorite browser
  // before using.
  // http://www.quirksmode.org/dom/events/cutcopypaste.html
  COPY: 'copy',
  PASTE: 'paste',
  CUT: 'cut',
  BEFORECOPY: 'beforecopy',
  BEFORECUT: 'beforecut',
  BEFOREPASTE: 'beforepaste',

  // HTML5 online/offline events.
  // http://www.w3.org/TR/offline-webapps/#related
  ONLINE: 'online',
  OFFLINE: 'offline',

  // HTML 5 worker events
  MESSAGE: 'message',
  CONNECT: 'connect',

  // CSS transition events. Based on the browser support described at:
  // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility
  TRANSITIONEND: goog.userAgent.WEBKIT ? 'webkitTransitionEnd' :
      (goog.userAgent.OPERA ? 'oTransitionEnd' : 'transitionend')
};
<commit_msg><commit_after>// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Event Types.
 *
 * @author arv@google.com (Erik Arvidsson)
 * @author mirkov@google.com (Mirko Visontai)
 */

goog.provide('goog.events.EventType');

goog.require('goog.userAgent');

/**
 * Constants for event names.
 * @enum {string}
 */
goog.events.EventType = {
  // Mouse events
  CLICK: 'click',
  DBLCLICK: 'dblclick',
  MOUSEDOWN: 'mousedown',
  MOUSEUP: 'mouseup',
  MOUSEOVER: 'mouseover',
  MOUSEOUT: 'mouseout',
  MOUSEMOVE: 'mousemove',
  SELECTSTART: 'selectstart', // IE, Safari, Chrome

  // Key events
  KEYPRESS: 'keypress',
  KEYDOWN: 'keydown',
  KEYUP: 'keyup',

  // Focus
  BLUR: 'blur',
  FOCUS: 'focus',
  DEACTIVATE: 'deactivate', // IE only
  // NOTE: The following two events are not stable in cross-browser usage.
  //     WebKit and Opera implement DOMFocusIn/Out.
  //     IE implements focusin/out.
  //     Gecko implements neither see bug at
  //     https://bugzilla.mozilla.org/show_bug.cgi?id=396927.
  // The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin:
  //     http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
  // You can use FOCUS in Capture phase until implementations converge.
  FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
  FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',

  // Forms
  CHANGE: 'change',
  SELECT: 'select',
  SUBMIT: 'submit',
  INPUT: 'input',
  PROPERTYCHANGE: 'propertychange', // IE only

  // Drag and drop
  DRAGSTART: 'dragstart',
  DRAGENTER: 'dragenter',
  DRAGOVER: 'dragover',
  DRAGLEAVE: 'dragleave',
  DROP: 'drop',

  // WebKit touch events.
  TOUCHSTART: 'touchstart',
  TOUCHMOVE: 'touchmove',
  TOUCHEND: 'touchend',
  TOUCHCANCEL: 'touchcancel',

  // Misc
  BEFOREUNLOAD: 'beforeunload',
  CONTEXTMENU: 'contextmenu',
  ERROR: 'error',
  HELP: 'help',
  LOAD: 'load',
  LOSECAPTURE: 'losecapture',
  READYSTATECHANGE: 'readystatechange',
  RESIZE: 'resize',
  SCROLL: 'scroll',
  UNLOAD: 'unload',

  // HTML 5 History events
  // See http://www.w3.org/TR/html5/history.html#event-definitions
  HASHCHANGE: 'hashchange',
  PAGEHIDE: 'pagehide',
  PAGESHOW: 'pageshow',
  POPSTATE: 'popstate',

  // Copy and Paste
  // Support is limited. Make sure it works on your favorite browser
  // before using.
  // http://www.quirksmode.org/dom/events/cutcopypaste.html
  COPY: 'copy',
  PASTE: 'paste',
  CUT: 'cut',
  BEFORECOPY: 'beforecopy',
  BEFORECUT: 'beforecut',
  BEFOREPASTE: 'beforepaste',

  // HTML5 online/offline events.
  // http://www.w3.org/TR/offline-webapps/#related
  ONLINE: 'online',
  OFFLINE: 'offline',

  // HTML 5 worker events
  MESSAGE: 'message',
  CONNECT: 'connect',

  // CSS transition events. Based on the browser support described at:
  // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility
  TRANSITIONEND: goog.userAgent.WEBKIT ? 'webkitTransitionEnd' :
      (goog.userAgent.OPERA ? 'oTransitionEnd' : 'transitionend')
};
<|endoftext|>


<commit_before>// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Event Types.
 *
 * @author arv@google.com (Erik Arvidsson)
 */

goog.provide('goog.events.EventType');

goog.require('goog.userAgent');

/**
 * Returns a prefixed event name for the current browser.
 * @param {string} eventName The name of the event.
 * @return {string} The prefixed event name.
 * @suppress {missingRequire|missingProvide}
 * @private
 */
goog.events.getVendorPrefixedName_ = function(eventName) {
  return goog.userAgent.WEBKIT ?
      'webkit' + eventName :
      (goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() :
                              eventName.toLowerCase());
};

/**
 * Constants for event names.
 * @enum {string}
 */
goog.events.EventType = {
  // Mouse events
  CLICK: 'click',
  RIGHTCLICK: 'rightclick',
  DBLCLICK: 'dblclick',
  MOUSEDOWN: 'mousedown',
  MOUSEUP: 'mouseup',
  MOUSEOVER: 'mouseover',
  MOUSEOUT: 'mouseout',
  MOUSEMOVE: 'mousemove',
  MOUSEENTER: 'mouseenter',
  MOUSELEAVE: 'mouseleave',

  // Selection events.
  // https://www.w3.org/TR/selection-api/
  SELECTIONCHANGE: 'selectionchange',
  SELECTSTART: 'selectstart',  // IE, Safari, Chrome

  // Wheel events
  // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
  WHEEL: 'wheel',

  // Key events
  KEYPRESS: 'keypress',
  KEYDOWN: 'keydown',
  KEYUP: 'keyup',

  // Focus
  BLUR: 'blur',
  FOCUS: 'focus',
  DEACTIVATE: 'deactivate',  // IE only
  // NOTE: The following two events are not stable in cross-browser usage.
  //     WebKit and Opera implement DOMFocusIn/Out.
  //     IE implements focusin/out.
  //     Gecko implements neither see bug at
  //     https://bugzilla.mozilla.org/show_bug.cgi?id=396927.
  // The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin:
  //     http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
  // You can use FOCUS in Capture phase until implementations converge.
  FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
  FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',

  // Forms
  CHANGE: 'change',
  RESET: 'reset',
  SELECT: 'select',
  SUBMIT: 'submit',
  INPUT: 'input',
  PROPERTYCHANGE: 'propertychange',  // IE only

  // Drag and drop
  DRAGSTART: 'dragstart',
  DRAG: 'drag',
  DRAGENTER: 'dragenter',
  DRAGOVER: 'dragover',
  DRAGLEAVE: 'dragleave',
  DROP: 'drop',
  DRAGEND: 'dragend',

  // Touch events
  // Note that other touch events exist, but we should follow the W3C list here.
  // http://www.w3.org/TR/touch-events/#list-of-touchevent-types
  TOUCHSTART: 'touchstart',
  TOUCHMOVE: 'touchmove',
  TOUCHEND: 'touchend',
  TOUCHCANCEL: 'touchcancel',

  // Misc
  BEFOREUNLOAD: 'beforeunload',
  CONSOLEMESSAGE: 'consolemessage',
  CONTEXTMENU: 'contextmenu',
  DEVICEMOTION: 'devicemotion',
  DEVICEORIENTATION: 'deviceorientation',
  DOMCONTENTLOADED: 'DOMContentLoaded',
  ERROR: 'error',
  HELP: 'help',
  LOAD: 'load',
  LOSECAPTURE: 'losecapture',
  ORIENTATIONCHANGE: 'orientationchange',
  READYSTATECHANGE: 'readystatechange',
  RESIZE: 'resize',
  SCROLL: 'scroll',
  UNLOAD: 'unload',

  // Media events
  CANPLAY: 'canplay',
  CANPLAYTHROUGH: 'canplaythrough',
  DURATIONCHANGE: 'durationchange',
  EMPTIED: 'emptied',
  ENDED: 'ended',
  LOADEDDATA: 'loadeddata',
  LOADEDMETADATA: 'loadedmetadata',
  PAUSE: 'pause',
  PLAY: 'play',
  PLAYING: 'playing',
  RATECHANGE: 'ratechange',
  SEEKED: 'seeked',
  SEEKING: 'seeking',
  STALLED: 'stalled',
  SUSPEND: 'suspend',
  TIMEUPDATE: 'timeupdate',
  VOLUMECHANGE: 'volumechange',
  WAITING: 'waiting',

  // HTML 5 History events
  // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0
  HASHCHANGE: 'hashchange',
  PAGEHIDE: 'pagehide',
  PAGESHOW: 'pageshow',
  POPSTATE: 'popstate',

  // Copy and Paste
  // Support is limited. Make sure it works on your favorite browser
  // before using.
  // http://www.quirksmode.org/dom/events/cutcopypaste.html
  COPY: 'copy',
  PASTE: 'paste',
  CUT: 'cut',
  BEFORECOPY: 'beforecopy',
  BEFORECUT: 'beforecut',
  BEFOREPASTE: 'beforepaste',

  // HTML5 online/offline events.
  // http://www.w3.org/TR/offline-webapps/#related
  ONLINE: 'online',
  OFFLINE: 'offline',

  // HTML 5 worker events
  MESSAGE: 'message',
  CONNECT: 'connect',

  // CSS animation events.
  /** @suppress {missingRequire} */
  ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'),
  /** @suppress {missingRequire} */
  ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'),
  /** @suppress {missingRequire} */
  ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'),

  // CSS transition events. Based on the browser support described at:
  // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility
  /** @suppress {missingRequire} */
  TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'),

  // W3C Pointer Events
  // http://www.w3.org/TR/pointerevents/
  POINTERDOWN: 'pointerdown',
  POINTERUP: 'pointerup',
  POINTERCANCEL: 'pointercancel',
  POINTERMOVE: 'pointermove',
  POINTEROVER: 'pointerover',
  POINTEROUT: 'pointerout',
  POINTERENTER: 'pointerenter',
  POINTERLEAVE: 'pointerleave',
  GOTPOINTERCAPTURE: 'gotpointercapture',
  LOSTPOINTERCAPTURE: 'lostpointercapture',

  // IE specific events.
  // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx
  // Note: these events will be supplanted in IE11.
  MSGESTURECHANGE: 'MSGestureChange',
  MSGESTUREEND: 'MSGestureEnd',
  MSGESTUREHOLD: 'MSGestureHold',
  MSGESTURESTART: 'MSGestureStart',
  MSGESTURETAP: 'MSGestureTap',
  MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',
  MSINERTIASTART: 'MSInertiaStart',
  MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',
  MSPOINTERCANCEL: 'MSPointerCancel',
  MSPOINTERDOWN: 'MSPointerDown',
  MSPOINTERENTER: 'MSPointerEnter',
  MSPOINTERHOVER: 'MSPointerHover',
  MSPOINTERLEAVE: 'MSPointerLeave',
  MSPOINTERMOVE: 'MSPointerMove',
  MSPOINTEROUT: 'MSPointerOut',
  MSPOINTEROVER: 'MSPointerOver',
  MSPOINTERUP: 'MSPointerUp',

  // Native IMEs/input tools events.
  TEXT: 'text',
  TEXTINPUT: 'textInput',
  COMPOSITIONSTART: 'compositionstart',
  COMPOSITIONUPDATE: 'compositionupdate',
  COMPOSITIONEND: 'compositionend',

  // Webview tag events
  // See http://developer.chrome.com/dev/apps/webview_tag.html
  EXIT: 'exit',
  LOADABORT: 'loadabort',
  LOADCOMMIT: 'loadcommit',
  LOADREDIRECT: 'loadredirect',
  LOADSTART: 'loadstart',
  LOADSTOP: 'loadstop',
  RESPONSIVE: 'responsive',
  SIZECHANGED: 'sizechanged',
  UNRESPONSIVE: 'unresponsive',

  // HTML5 Page Visibility API.  See details at
  // {@code goog.labs.dom.PageVisibilityMonitor}.
  VISIBILITYCHANGE: 'visibilitychange',

  // LocalStorage event.
  STORAGE: 'storage',

  // DOM Level 2 mutation events (deprecated).
  DOMSUBTREEMODIFIED: 'DOMSubtreeModified',
  DOMNODEINSERTED: 'DOMNodeInserted',
  DOMNODEREMOVED: 'DOMNodeRemoved',
  DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',
  DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',
  DOMATTRMODIFIED: 'DOMAttrModified',
  DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',

  // Print events.
  BEFOREPRINT: 'beforeprint',
  AFTERPRINT: 'afterprint'
};
<commit_msg>Update the TEXTINPUT event to use 'textinput' instead of 'textInput' for IE.<commit_after>// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Event Types.
 *
 * @author arv@google.com (Erik Arvidsson)
 */

goog.provide('goog.events.EventType');

goog.require('goog.userAgent');

/**
 * Returns a prefixed event name for the current browser.
 * @param {string} eventName The name of the event.
 * @return {string} The prefixed event name.
 * @suppress {missingRequire|missingProvide}
 * @private
 */
goog.events.getVendorPrefixedName_ = function(eventName) {
  return goog.userAgent.WEBKIT ?
      'webkit' + eventName :
      (goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() :
                              eventName.toLowerCase());
};

/**
 * Constants for event names.
 * @enum {string}
 */
goog.events.EventType = {
  // Mouse events
  CLICK: 'click',
  RIGHTCLICK: 'rightclick',
  DBLCLICK: 'dblclick',
  MOUSEDOWN: 'mousedown',
  MOUSEUP: 'mouseup',
  MOUSEOVER: 'mouseover',
  MOUSEOUT: 'mouseout',
  MOUSEMOVE: 'mousemove',
  MOUSEENTER: 'mouseenter',
  MOUSELEAVE: 'mouseleave',

  // Selection events.
  // https://www.w3.org/TR/selection-api/
  SELECTIONCHANGE: 'selectionchange',
  SELECTSTART: 'selectstart',  // IE, Safari, Chrome

  // Wheel events
  // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
  WHEEL: 'wheel',

  // Key events
  KEYPRESS: 'keypress',
  KEYDOWN: 'keydown',
  KEYUP: 'keyup',

  // Focus
  BLUR: 'blur',
  FOCUS: 'focus',
  DEACTIVATE: 'deactivate',  // IE only
  // NOTE: The following two events are not stable in cross-browser usage.
  //     WebKit and Opera implement DOMFocusIn/Out.
  //     IE implements focusin/out.
  //     Gecko implements neither see bug at
  //     https://bugzilla.mozilla.org/show_bug.cgi?id=396927.
  // The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin:
  //     http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
  // You can use FOCUS in Capture phase until implementations converge.
  FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
  FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',

  // Forms
  CHANGE: 'change',
  RESET: 'reset',
  SELECT: 'select',
  SUBMIT: 'submit',
  INPUT: 'input',
  PROPERTYCHANGE: 'propertychange',  // IE only

  // Drag and drop
  DRAGSTART: 'dragstart',
  DRAG: 'drag',
  DRAGENTER: 'dragenter',
  DRAGOVER: 'dragover',
  DRAGLEAVE: 'dragleave',
  DROP: 'drop',
  DRAGEND: 'dragend',

  // Touch events
  // Note that other touch events exist, but we should follow the W3C list here.
  // http://www.w3.org/TR/touch-events/#list-of-touchevent-types
  TOUCHSTART: 'touchstart',
  TOUCHMOVE: 'touchmove',
  TOUCHEND: 'touchend',
  TOUCHCANCEL: 'touchcancel',

  // Misc
  BEFOREUNLOAD: 'beforeunload',
  CONSOLEMESSAGE: 'consolemessage',
  CONTEXTMENU: 'contextmenu',
  DEVICEMOTION: 'devicemotion',
  DEVICEORIENTATION: 'deviceorientation',
  DOMCONTENTLOADED: 'DOMContentLoaded',
  ERROR: 'error',
  HELP: 'help',
  LOAD: 'load',
  LOSECAPTURE: 'losecapture',
  ORIENTATIONCHANGE: 'orientationchange',
  READYSTATECHANGE: 'readystatechange',
  RESIZE: 'resize',
  SCROLL: 'scroll',
  UNLOAD: 'unload',

  // Media events
  CANPLAY: 'canplay',
  CANPLAYTHROUGH: 'canplaythrough',
  DURATIONCHANGE: 'durationchange',
  EMPTIED: 'emptied',
  ENDED: 'ended',
  LOADEDDATA: 'loadeddata',
  LOADEDMETADATA: 'loadedmetadata',
  PAUSE: 'pause',
  PLAY: 'play',
  PLAYING: 'playing',
  RATECHANGE: 'ratechange',
  SEEKED: 'seeked',
  SEEKING: 'seeking',
  STALLED: 'stalled',
  SUSPEND: 'suspend',
  TIMEUPDATE: 'timeupdate',
  VOLUMECHANGE: 'volumechange',
  WAITING: 'waiting',

  // HTML 5 History events
  // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0
  HASHCHANGE: 'hashchange',
  PAGEHIDE: 'pagehide',
  PAGESHOW: 'pageshow',
  POPSTATE: 'popstate',

  // Copy and Paste
  // Support is limited. Make sure it works on your favorite browser
  // before using.
  // http://www.quirksmode.org/dom/events/cutcopypaste.html
  COPY: 'copy',
  PASTE: 'paste',
  CUT: 'cut',
  BEFORECOPY: 'beforecopy',
  BEFORECUT: 'beforecut',
  BEFOREPASTE: 'beforepaste',

  // HTML5 online/offline events.
  // http://www.w3.org/TR/offline-webapps/#related
  ONLINE: 'online',
  OFFLINE: 'offline',

  // HTML 5 worker events
  MESSAGE: 'message',
  CONNECT: 'connect',

  // CSS animation events.
  /** @suppress {missingRequire} */
  ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'),
  /** @suppress {missingRequire} */
  ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'),
  /** @suppress {missingRequire} */
  ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'),

  // CSS transition events. Based on the browser support described at:
  // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility
  /** @suppress {missingRequire} */
  TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'),

  // W3C Pointer Events
  // http://www.w3.org/TR/pointerevents/
  POINTERDOWN: 'pointerdown',
  POINTERUP: 'pointerup',
  POINTERCANCEL: 'pointercancel',
  POINTERMOVE: 'pointermove',
  POINTEROVER: 'pointerover',
  POINTEROUT: 'pointerout',
  POINTERENTER: 'pointerenter',
  POINTERLEAVE: 'pointerleave',
  GOTPOINTERCAPTURE: 'gotpointercapture',
  LOSTPOINTERCAPTURE: 'lostpointercapture',

  // IE specific events.
  // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx
  // Note: these events will be supplanted in IE11.
  MSGESTURECHANGE: 'MSGestureChange',
  MSGESTUREEND: 'MSGestureEnd',
  MSGESTUREHOLD: 'MSGestureHold',
  MSGESTURESTART: 'MSGestureStart',
  MSGESTURETAP: 'MSGestureTap',
  MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',
  MSINERTIASTART: 'MSInertiaStart',
  MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',
  MSPOINTERCANCEL: 'MSPointerCancel',
  MSPOINTERDOWN: 'MSPointerDown',
  MSPOINTERENTER: 'MSPointerEnter',
  MSPOINTERHOVER: 'MSPointerHover',
  MSPOINTERLEAVE: 'MSPointerLeave',
  MSPOINTERMOVE: 'MSPointerMove',
  MSPOINTEROUT: 'MSPointerOut',
  MSPOINTEROVER: 'MSPointerOver',
  MSPOINTERUP: 'MSPointerUp',

  // Native IMEs/input tools events.
  TEXT: 'text',
  // The textInput event is supported in IE9+, but only in lower case. All other
  // browsers use the camel-case event name.
  TEXTINPUT: goog.userAgent.IE ? 'textinput' : 'textInput',
  COMPOSITIONSTART: 'compositionstart',
  COMPOSITIONUPDATE: 'compositionupdate',
  COMPOSITIONEND: 'compositionend',

  // Webview tag events
  // See http://developer.chrome.com/dev/apps/webview_tag.html
  EXIT: 'exit',
  LOADABORT: 'loadabort',
  LOADCOMMIT: 'loadcommit',
  LOADREDIRECT: 'loadredirect',
  LOADSTART: 'loadstart',
  LOADSTOP: 'loadstop',
  RESPONSIVE: 'responsive',
  SIZECHANGED: 'sizechanged',
  UNRESPONSIVE: 'unresponsive',

  // HTML5 Page Visibility API.  See details at
  // {@code goog.labs.dom.PageVisibilityMonitor}.
  VISIBILITYCHANGE: 'visibilitychange',

  // LocalStorage event.
  STORAGE: 'storage',

  // DOM Level 2 mutation events (deprecated).
  DOMSUBTREEMODIFIED: 'DOMSubtreeModified',
  DOMNODEINSERTED: 'DOMNodeInserted',
  DOMNODEREMOVED: 'DOMNodeRemoved',
  DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',
  DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',
  DOMATTRMODIFIED: 'DOMAttrModified',
  DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',

  // Print events.
  BEFOREPRINT: 'beforeprint',
  AFTERPRINT: 'afterprint'
};
<|endoftext|>


<commit_before>// Modification of original decisionTree.js for mobile

var treeData,
    branches,
    backendUrl = 'http://loyolalawtech.org/idt/', //url for server to handle logging
    treeId = '1374682207'; //id of the tree, as generated by IDT.

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady(){
    var networkState = navigator.connection.type;
    var states = {};
    if (networkState === 'none'){
        $('.panel-body').html('
You are offline

Your device appears to be offline. ' +
        'You need to be connected to the internet to use this application');
        return;
    } else {
        //Get rid of any previous sessions -THIS NEEDS TO BE LOCALSTORAGE instead
        if (window.localStorage.getItem('idt-sess-id')){
            window.localStorage.removeItem('idt-sess-id');
        }
        var branches = [];
        var options = {};
        loadData();
    }
}

function loadData() {
	$.ajax({
		type: 'GET',
		url: 'data/data.xml',
		dataType: 'xml',
		success: function(xml){
			buildNodes(xml, treeId );
		}
	});
}

function TreeBranch() {
	this.id = '';
	this.content = '';
	this.forkIDs = [];
	this.forkLabels = [];
}

function buildNodes(xmlData, id) {
	var maxDepth = 0;
    branches = [];
	treeData = xmlData;
	$(xmlData).find('branch').each(function(){
			var branch = new TreeBranch();
			branch.id = $(this).attr('id');
			branch.content = $(this).find('content').text();
			$(this).find('fork').each(
				function(){
					branch.forkIDs.push( $(this).attr('target') );
					branch.forkLabels.push( $(this).text() );
				}
			);
			branches.push( branch );
			var branchDepthParts = branch.id.split('.');
			if( branchDepthParts.length > maxDepth ){
				maxDepth = branchDepthParts.length;
			}
        });

	var resetText = $(xmlData).find('resetText').text();
    if (resetText !== ''){
        $('#tree-reset').html(resetText);
    } else {
        $('#tree-reset').remove();
    }

    //New code to show description and disclaimer
    $('.app-title, title ').text($(xmlData).find('title').text());
	$('.panel-body').html($(xmlData).find('description').text() );
    var existingUser = '';
    if (window.localStorage.getItem('idt-user')){ //this "user" has has done a tree before
        existingUser = window.localStorage.getItem('idt-user');
    } else {
        existingUser = '';
    }

    if ($(xmlData).find('disclaimer').length){
        $('.panel-footer').html('<button type="button" class="btn btn-info show-disclaimer">Please Read the Disclaimer</button>');

        $('#tree-window .show-disclaimer').on('click', function (event) {
            event.preventDefault();
            $('.panel-body').html($(xmlData).find('disclaimer').text());
            $('.panel-footer').html('
  <input type="checkbox" id="agree"> I agree.
');
            $('#agree').on('change', function (event) {
                $.post(backendUrl + 'private/backend.php', {'action': 'log', 'existing_user': existingUser, 'tree_id': treeId, 'mobile': '1'}, function(data) {
                    var resp = $.parseJSON(data);
                    window.localStorage.setItem('idt-user', resp.userid);
                    window.localStorage.setItem('idt-sess-id', resp.sessid);
                    showBranch(1);
                    $('.page-header').hide();
                    $('.navbar').removeClass('hidden');
                });
            });
        });
    } else {
        $('.panel-footer').html('<button type="button" class="btn btn-info begin-tree">Begin</button>');
        $('#tree-window .begin-tree').on('click', function (event) {
            event.preventDefault();
            $.post(backendUrl + 'private/backend.php', {'action':'log','existing_user':existingUser, 'tree_id': id}, function(data) {
                var resp = $.parseJSON(data);
                window.localStorage.setItem('idt-user', resp.userid);
                window.localStorage.setItem('idt-sess-id', resp.sessid);
                showBranch(1);
                $('.page-header').hide();
                $('.navbar').removeClass('hidden');
            });
        });
    }
}

function resetActionLinks(){
	$('.decision-links a').unbind('click');
	$('a.back-link').unbind('click');

	$('.decision-links .btn').click(function(e){
		if( !$(this).attr('href') ){
            //JM track here
			showBranch( $(this).attr('id') );
            $.post(backendUrl + 'private/backend.php', {'action': 'progress', 'session_id': window.localStorage.getItem('idt-sess-id'),'last_link': $(this).attr('id')});
		}
	});
	$('a.back-link').click(function(){
        //Go to previous item in xml tree
        var lastQ = $('.panel-body').attr('data-branch').slice(0,-2);
        showBranch(lastQ);
	});
}

function showBranch(id){
    var currentBranch;

	for(var i = 0; i < branches.length; i++ ){
		if( branches[i].id == id ){
			currentBranch = branches[i];
			break;
		}
	}

	var decisionLinksHTML = '
';
	if(currentBranch.id !== '1'){
		decisionLinksHTML += '

   Back

';
    }
    else {
		decisionLinksHTML += '

';
    }

	for(var d = 0; d < currentBranch.forkIDs.length; d++ ){
		var link = '';
		var forkContent = $(treeData).find('branch[id="' + currentBranch.forkIDs[d] + '"]').find('content').text();
		if( forkContent.indexOf('http://') == 0 || forkContent.indexOf('https://') == 0 ){
			link = 'href="' + forkContent + '"';
		}
        if (d === 1){
            decisionLinksHTML += '
' + currentBranch.forkLabels[d] + '
';
        } else {
            decisionLinksHTML += '
' + currentBranch.forkLabels[d] + '
';
        }
	}

	decisionLinksHTML += '
';

    //insert referral link here
    var scanTxt = currentBranch.content.replace('{{','').replace('}}','');
	var branchHTML = '

' + scanTxt + '

';
	$('.panel-body').html(branchHTML).attr('data-branch',currentBranch.id);
    $('.panel-footer').html(decisionLinksHTML);

	resetActionLinks();
}

function addReferralListeners(){

    $('.panel-default').hide();

    $('.ref-toggle').click(function (e){
        $('.ref-chooser').removeClass('hidden');
    });

    //Add listener for user change
    $('#refSubmit').click(function (e) {
        e.preventDefault();
        generateReferralManual($('#zipCode').val(),$('#geoRange').val());

    });

    //Add listener for user referral click
    $('.click-through').click(function (e) {
        var url = $(this).attr('href');
        var refId = $(this).attr('data-id');

        $.post(backendUrl + 'private/backend.php',{'action':'link_click','referral_id': refId}, function (data){
            window.open(url, '_system', 'location=yes');
            //navigator.app.loadUrl(url, { openExternal:true });

        });
    });

}

function generateReferralManual(zip, distance){

    var url = backendUrl + 'private/referral_mobile.php?zip=' + zip + '&geo_range=' + distance;
    $('#referral-results').load(url, function (){
        $('#zipCode').val(zip);
        $('#geoRange').val(distance);
        addReferralListeners();
    });
}

function generateReferralGeo() {
    var sessId = window.localStorage.getItem('idt-sess-id');

    $('.panel-body').html('Attempting to get your location.');
    navigator.geolocation.getCurrentPosition(function succcess(position){
        $.post(backendUrl + 'private/backend.php', {
            action: 'update_location',
            lat: position.coords.latitude,
            long: position.coords.longitude,
            user_id: window.localStorage.getItem('idt-user')
        },function (e){
            $('.panel-body').html('Finding referrals for you.');
        });
        $('#referral-results').load(backendUrl + 'private/referral_mobile.php?sess_id=' + sessId, function (){
            addReferralListeners();
            $('#zipCode').attr('placeholder', '[Your Current Location]');
        });
    }, function fail(){
        var zipForm = '
Geolocation is unavailable.
' +
        '<form name="zip_only"><input name="zip" placeholder="Enter Your Zip Code"><button type="submit">Go</button></form>';
        $('.panel-body').html(zipForm);
        $('form[name="zip_only"]').submit(function (e) {
            e.preventDefault();
            var userZip = $(this).find('input').val();
            generateReferralManual(userZip,'105600');
        });
    },
    { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }
    );

}

<commit_msg>Fix on link click<commit_after>// Modification of original decisionTree.js for mobile

var treeData,
    branches,
    backendUrl = 'http://loyolalawtech.org/idt/', //url for server to handle logging
    treeId = '1374682207'; //id of the tree, as generated by IDT.

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady(){
    var networkState = navigator.connection.type;
    var states = {};
    if (networkState === 'none'){
        $('.panel-body').html('
You are offline

Your device appears to be offline. ' +
        'You need to be connected to the internet to use this application');
        return;
    } else {
        //Get rid of any previous sessions -THIS NEEDS TO BE LOCALSTORAGE instead
        if (window.localStorage.getItem('idt-sess-id')){
            window.localStorage.removeItem('idt-sess-id');
        }
        var branches = [];
        var options = {};
        loadData();
    }
}

function loadData() {
	$.ajax({
		type: 'GET',
		url: 'data/data.xml',
		dataType: 'xml',
		success: function(xml){
			buildNodes(xml, treeId );
		}
	});
}

function TreeBranch() {
	this.id = '';
	this.content = '';
	this.forkIDs = [];
	this.forkLabels = [];
}

function buildNodes(xmlData, id) {
	var maxDepth = 0;
    branches = [];
	treeData = xmlData;
	$(xmlData).find('branch').each(function(){
			var branch = new TreeBranch();
			branch.id = $(this).attr('id');
			branch.content = $(this).find('content').text();
			$(this).find('fork').each(
				function(){
					branch.forkIDs.push( $(this).attr('target') );
					branch.forkLabels.push( $(this).text() );
				}
			);
			branches.push( branch );
			var branchDepthParts = branch.id.split('.');
			if( branchDepthParts.length > maxDepth ){
				maxDepth = branchDepthParts.length;
			}
        });

	var resetText = $(xmlData).find('resetText').text();
    if (resetText !== ''){
        $('#tree-reset').html(resetText);
    } else {
        $('#tree-reset').remove();
    }

    //New code to show description and disclaimer
    $('.app-title, title ').text($(xmlData).find('title').text());
	$('.panel-body').html($(xmlData).find('description').text() );
    var existingUser = '';
    if (window.localStorage.getItem('idt-user')){ //this "user" has has done a tree before
        existingUser = window.localStorage.getItem('idt-user');
    } else {
        existingUser = '';
    }

    if ($(xmlData).find('disclaimer').length){
        $('.panel-footer').html('<button type="button" class="btn btn-info show-disclaimer">Please Read the Disclaimer</button>');

        $('#tree-window .show-disclaimer').on('click', function (event) {
            event.preventDefault();
            $('.panel-body').html($(xmlData).find('disclaimer').text());
            $('.panel-footer').html('
  <input type="checkbox" id="agree"> I agree.
');
            $('#agree').on('change', function (event) {
                $.post(backendUrl + 'private/backend.php', {'action': 'log', 'existing_user': existingUser, 'tree_id': treeId, 'mobile': '1'}, function(data) {
                    var resp = $.parseJSON(data);
                    window.localStorage.setItem('idt-user', resp.userid);
                    window.localStorage.setItem('idt-sess-id', resp.sessid);
                    showBranch(1);
                    $('.page-header').hide();
                    $('.navbar').removeClass('hidden');
                });
            });
        });
    } else {
        $('.panel-footer').html('<button type="button" class="btn btn-info begin-tree">Begin</button>');
        $('#tree-window .begin-tree').on('click', function (event) {
            event.preventDefault();
            $.post(backendUrl + 'private/backend.php', {'action':'log','existing_user':existingUser, 'tree_id': id}, function(data) {
                var resp = $.parseJSON(data);
                window.localStorage.setItem('idt-user', resp.userid);
                window.localStorage.setItem('idt-sess-id', resp.sessid);
                showBranch(1);
                $('.page-header').hide();
                $('.navbar').removeClass('hidden');
            });
        });
    }
}

function resetActionLinks(){
	$('.decision-links a').unbind('click');
	$('a.back-link').unbind('click');

	$('.decision-links .btn').click(function(e){
		if( !$(this).attr('href') ){
            //JM track here
			showBranch( $(this).attr('id') );
            $.post(backendUrl + 'private/backend.php', {'action': 'progress', 'session_id': window.localStorage.getItem('idt-sess-id'),'last_link': $(this).attr('id')});
		}
	});
	$('a.back-link').click(function(){
        //Go to previous item in xml tree
        var lastQ = $('.panel-body').attr('data-branch').slice(0,-2);
        showBranch(lastQ);
	});
}

function showBranch(id){
    var currentBranch;

	for(var i = 0; i < branches.length; i++ ){
		if( branches[i].id == id ){
			currentBranch = branches[i];
			break;
		}
	}

	var decisionLinksHTML = '
';
	if(currentBranch.id !== '1'){
		decisionLinksHTML += '

   Back

';
    }
    else {
		decisionLinksHTML += '

';
    }

	for(var d = 0; d < currentBranch.forkIDs.length; d++ ){
		var link = '';
		var forkContent = $(treeData).find('branch[id="' + currentBranch.forkIDs[d] + '"]').find('content').text();
		if( forkContent.indexOf('http://') == 0 || forkContent.indexOf('https://') == 0 ){
			link = 'href="' + forkContent + '"';
		}
        if (d === 1){
            decisionLinksHTML += '
' + currentBranch.forkLabels[d] + '
';
        } else {
            decisionLinksHTML += '
' + currentBranch.forkLabels[d] + '
';
        }
	}

	decisionLinksHTML += '
';

    //insert referral link here
    var scanTxt = currentBranch.content.replace('{{','').replace('}}','');
	var branchHTML = '

' + scanTxt + '

';
	$('.panel-body').html(branchHTML).attr('data-branch',currentBranch.id);
    $('.panel-footer').html(decisionLinksHTML);

	resetActionLinks();
}

function addReferralListeners(){

    $('.panel-default').hide();

    $('.ref-toggle').click(function (e){
        $('.ref-chooser').removeClass('hidden');
    });

    //Add listener for user change
    $('#refSubmit').click(function (e) {
        e.preventDefault();
        generateReferralManual($('#zipCode').val(),$('#geoRange').val());

    });

    //Add listener for user referral click
    $('.click-through').click(function (e) {
        e.preventDefault();
        var url = $(this).attr('href');
        var refId = $(this).attr('data-id');

        $.post(backendUrl + 'private/backend.php',{'action':'link_click','referral_id': refId}, function (data){
            window.open(url, '_system', 'location=yes');
            //navigator.app.loadUrl(url, { openExternal:true });

        });
    });

}

function generateReferralManual(zip, distance){

    var url = backendUrl + 'private/referral_mobile.php?zip=' + zip + '&geo_range=' + distance;
    $('#referral-results').load(url, function (){
        $('#zipCode').val(zip);
        $('#geoRange').val(distance);
        addReferralListeners();
    });
}

function generateReferralGeo() {
    var sessId = window.localStorage.getItem('idt-sess-id');

    $('.panel-body').html('Attempting to get your location.');
    navigator.geolocation.getCurrentPosition(function succcess(position){
        $.post(backendUrl + 'private/backend.php', {
            action: 'update_location',
            lat: position.coords.latitude,
            long: position.coords.longitude,
            user_id: window.localStorage.getItem('idt-user')
        },function (e){
            $('.panel-body').html('Finding referrals for you.');
        });
        $('#referral-results').load(backendUrl + 'private/referral_mobile.php?sess_id=' + sessId, function (){
            addReferralListeners();
            $('#zipCode').attr('placeholder', '[Your Current Location]');
        });
    }, function fail(){
        var zipForm = '
Geolocation is unavailable.
' +
        '<form name="zip_only"><input name="zip" placeholder="Enter Your Zip Code"><button type="submit">Go</button></form>';
        $('.panel-body').html(zipForm);
        $('form[name="zip_only"]').submit(function (e) {
            e.preventDefault();
            var userZip = $(this).find('input').val();
            generateReferralManual(userZip,'105600');
        });
    },
    { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }
    );

}

<|endoftext|>