<commit_before>/*
 * This file is part of the RedKite CMS Application and it is distributed
 * under the MIT License. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <webmaster@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    MIT License
 *
 */

;(function($){
    var methods = {
        init: function()
        {
            $('.al_element_selector').unbind().pages('select');
            $("#al_page_saver").unbind().pages('save');
            $("#al_page_save_as_new").unbind().pages('save_as_new');
            $(".rk-page-remover").unbind().pages('remove');
            $(".rk-page-language").unbind().pages('changeLanguage');

        },
        select: function()
        {
            this.each(function()
            {
                $(this).click(function()
                {
                    // Deselects the current selected page and selects the new one
                    ResetWholeForm();
                    if(!$(this).hasClass('al_element_selected'))
                    {
                        Select($(this));
                        if($('#seo_attributes_idLanguage option:selected').val() != 'none')
                        {
                            LoadSeoAttributes($(this).attr('data-page-id'));
                        }
                        else
                        {
                            $('#seo_attributes_idPage').val($(this).attr('data-page-id'));
                        }
                    }
                    else
                    {
                        $(this).removeClass('al_element_selected');
                        $('#seo_attributes_idPage').val('');
                    }

                    return false;
                });
            });
        },
        save: function()
        {
            $(this).click(function()
            {
                var pageId = $('#al_pages_list .al_element_selected').attr('data-page-id');
                var languageId = 0;
                if (pageId != null) {
                     languageId = $('#rk_language_' + pageId).val();
                }

                save(languageId, pageId)

                return false;
            });
        },
        save_as_new: function()
        {
            $(this).click(function()
            {
                var pageId = $('#al_pages_list .al_element_selected').attr('data-page-id');
                save(0, pageId)

                return false;
            });
        },
        remove: function()
        {
            $(this).click(function()
            {
                if(confirm(translate("Are you sure to remove the page and its attributes")))
                {
                    try{
                        var pageId = $(this).attr('data-page-id');

                        $.ajax({
                            type: 'POST',
                            url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_deletePage',
                            data: {'language' : $('#al_languages_navigator').html(),
                                   'page' : $('#al_pages_navigator').html(),
                                   'languageId' : $('#rk_language_' + pageId).val(),
                                   'pageId' : pageId
                               },
                            beforeSend: function()
                            {
                                $('body').AddAjaxLoader();
                            },
                            success: function(response)
                            {
                                UpdatePagesJSon(response);

                                ResetWholeForm();
                                $('#seo_attributes_idPage').val('');
                            },
                            error: function(err)
                            {
                                $('body').showAlert(err.responseText, 0, 'alert-error alert-danger');
                            },
                            complete: function()
                            {
                                $('body').RemoveAjaxLoader();
                            }
                        });
                    }
                    catch(e){
                        $('body').showAlert('An unespected error occoured in al-pages file while removing a page. Here is the error from the server:

' + e + '

Please open an issue at Github reporting this entire message.', 0, 'alert-error alert-danger');
                    }
                }

                return false;
            });
        },
        changeLanguage: function()
        {
            $(this).change(function()
            {
                var idPage = $(this).attr('rel');
                if (idPage) {
                    LoadSeoAttributes(idPage);
                    Select($('#rk_page_' + idPage));
                }

                return false;
            });
        }
    };

    function save(languageId, pageId)
    {
        try{
            var isHome = ($('#pages_isHome').is(':checked')) ? 1 : 0;
            var isPublished = ($('#pages_isPublished').is(':checked')) ? 1 : 0;
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_savePage',
                data: {'language' : $('#al_languages_navigator').html(),
                       'page' : $('#al_pages_navigator').html(),
                       'pageId' : pageId,
                       'languageId' : languageId,
                       'pageName' : $('#pages_pageName').val(),
                       'templateName' : $('#pages_template').val(),
                       'permalink' : $('#seo_attributes_permalink').val(),
                       'isHome' : isHome,
                       'isPublished' : isPublished,
                       'title' : $('#seo_attributes_title').val(),
                       'description' : $('#seo_attributes_description').val(),
                       'keywords' : $('#seo_attributes_keywords').val(),
                       'sitemapChangeFreq' : $('#seo_attributes_sitemapChangeFreq').val(),
                       'sitemapPriority' : $('#seo_attributes_sitemapPriority').val()
                   },
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(response)
                {
                    ResetWholeForm();
                    UpdatePagesJSon(response);
                },
                error: function(err)
                {
                    $('body').showAlert(err.responseText, 0, 'alert-error alert-danger');
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });
        }
        catch(e){
            var operation = (languageId == null || languageId == 'none') ? 'adding' : 'editing';
            $('body').showAlert('An unespected error occoured in al-pages file while ' + operation + ' a page. Here is the error from the server:

' + e + '

Please open an issue at Github reporting this entire message.', 0, 'alert-error alert-danger');
        }
    }

    function LoadSeoAttributes(idPage)
    {
        try{
            ResetWholeForm();
            $('#seo_attributes_idPage').val(idPage);
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_loadSeoAttributes',
                data: {'language' : $('#al_languages_navigator').html(),
                       'page' : $('#al_pages_navigator').html(),
                       'languageId' : $('#rk_language_' + idPage).val(),
                       'pageId' : idPage},
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(response)
                {
                    $(response).each(function(key, el)
                    {
                        switch(el.name)
                        {
                            case '#pages_isHome':
                            case '#pages_isPublished':
                                if(el.value == 1)
                                {
                                    $(el.name).attr('checked', 'checked');
                                }
                                else
                                {
                                    $(el.name).removeAttr("checked");
                                }
                                break;
                            default:
                                $(el.name).val(el.value);
                                break;
                        }
                    });
                },
                error: function(err)
                {
                    $('body').showAlert(err.responseText, 0, 'alert-error alert-danger');
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });
        }
        catch(e){
            $('body').showAlert('An unespected error occoured in al-pages file while loading page\'s attributes. Here is the error from the server:

' + e + '

Please open an issue at Github reporting this entire message.', 0, 'alert-error alert-danger');
        }
    }

    function Select(element)
    {
        $('#al_pages_list .al_element_selected').removeClass('al_element_selected');
        element.addClass('al_element_selected');
    }

    function ResetWholeForm()
    {
        $("#al_page_form").ResetFormElements();
        $("#al_attributes_form").ResetFormElements();
        $("#al_sitemp_form").ResetFormElements();
    }

    function UpdatePagesJSon(response)
    {
        $(response).each(function(key, item)
        {
            switch(item.key)
            {
                case "message":
                    $('body').showAlert(item.value);

                case "pages_list":
                    var idSelectedPage = $('#al_pages_list .al_element_selected').attr('data-page-id');
                    $('#al_pages_list').html(item.value);
                    $('#al_pages_list .al_element_selector').each(function(key, item)
                    {
                        if(idSelectedPage == $(item).attr('data-page-id'))
                        {
                            $(item).addClass('al_element_selected');
                            return;
                        }
                    });

                    break;
                case "pages":
                    $('.rk-pages-navigator-box').html(item.value);
                    $('.al_page_item').click(function()
                    {
                        Navigate($('#al_languages_navigator').html(), $(this).attr('rel'));

                        return false;
                    });

                    break;
                case "permalinks":
                    $('#al_page_name').remove()
                    $('body').append(item.value);
                    break;
                case "permalink":
                    if($('#seo_attributes_permalink').val() != item.value) $('#seo_attributes_permalink').val(item.value);
                    break;
            }
        });

        $('body').pages('init');
    }

    $.fn.pages = function( method ) {
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.inlinelist' );
        }
    };
})($);<commit_msg>added an argument to force is home as the given value and fixed bug that copying from the home page will generate a new home page<commit_after>/*
 * This file is part of the RedKite CMS Application and it is distributed
 * under the MIT License. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <webmaster@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    MIT License
 *
 */

;(function($){
    var methods = {
        init: function()
        {
            $('.al_element_selector').unbind().pages('select');
            $("#al_page_saver").unbind().pages('save');
            $("#al_page_save_as_new").unbind().pages('save_as_new');
            $(".rk-page-remover").unbind().pages('remove');
            $(".rk-page-language").unbind().pages('changeLanguage');

        },
        select: function()
        {
            this.each(function()
            {
                $(this).click(function()
                {
                    // Deselects the current selected page and selects the new one
                    ResetWholeForm();
                    if(!$(this).hasClass('al_element_selected'))
                    {
                        Select($(this));
                        if($('#seo_attributes_idLanguage option:selected').val() != 'none')
                        {
                            LoadSeoAttributes($(this).attr('data-page-id'));
                        }
                        else
                        {
                            $('#seo_attributes_idPage').val($(this).attr('data-page-id'));
                        }
                    }
                    else
                    {
                        $(this).removeClass('al_element_selected');
                        $('#seo_attributes_idPage').val('');
                    }

                    return false;
                });
            });
        },
        save: function()
        {
            $(this).click(function()
            {
                var pageId = $('#al_pages_list .al_element_selected').attr('data-page-id');
                var languageId = 0;
                if (pageId != null) {
                     languageId = $('#rk_language_' + pageId).val();
                }

                save(languageId, pageId)

                return false;
            });
        },
        save_as_new: function()
        {
            $(this).click(function()
            {
                var pageId = $('#al_pages_list .al_element_selected').attr('data-page-id');
                save(0, pageId, 0)

                return false;
            });
        },
        remove: function()
        {
            $(this).click(function()
            {
                if(confirm(translate("Are you sure to remove the page and its attributes")))
                {
                    try{
                        var pageId = $(this).attr('data-page-id');

                        $.ajax({
                            type: 'POST',
                            url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_deletePage',
                            data: {'language' : $('#al_languages_navigator').html(),
                                   'page' : $('#al_pages_navigator').html(),
                                   'languageId' : $('#rk_language_' + pageId).val(),
                                   'pageId' : pageId
                               },
                            beforeSend: function()
                            {
                                $('body').AddAjaxLoader();
                            },
                            success: function(response)
                            {
                                UpdatePagesJSon(response);

                                ResetWholeForm();
                                $('#seo_attributes_idPage').val('');
                            },
                            error: function(err)
                            {
                                $('body').showAlert(err.responseText, 0, 'alert-error alert-danger');
                            },
                            complete: function()
                            {
                                $('body').RemoveAjaxLoader();
                            }
                        });
                    }
                    catch(e){
                        $('body').showAlert('An unespected error occoured in al-pages file while removing a page. Here is the error from the server:

' + e + '

Please open an issue at Github reporting this entire message.', 0, 'alert-error alert-danger');
                    }
                }

                return false;
            });
        },
        changeLanguage: function()
        {
            $(this).change(function()
            {
                var idPage = $(this).attr('rel');
                if (idPage) {
                    LoadSeoAttributes(idPage);
                    Select($('#rk_page_' + idPage));
                }

                return false;
            });
        }
    };

    function save(languageId, pageId, forceIsHome)
    {
        try{
            var isHome = ($('#pages_isHome').is(':checked')) ? 1 : 0;
            if (forceIsHome != null){
                isHome = forceIsHome;
            }

            var isPublished = ($('#pages_isPublished').is(':checked')) ? 1 : 0;
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_savePage',
                data: {'language' : $('#al_languages_navigator').html(),
                       'page' : $('#al_pages_navigator').html(),
                       'pageId' : pageId,
                       'languageId' : languageId,
                       'pageName' : $('#pages_pageName').val(),
                       'templateName' : $('#pages_template').val(),
                       'permalink' : $('#seo_attributes_permalink').val(),
                       'isHome' : isHome,
                       'isPublished' : isPublished,
                       'title' : $('#seo_attributes_title').val(),
                       'description' : $('#seo_attributes_description').val(),
                       'keywords' : $('#seo_attributes_keywords').val(),
                       'sitemapChangeFreq' : $('#seo_attributes_sitemapChangeFreq').val(),
                       'sitemapPriority' : $('#seo_attributes_sitemapPriority').val()
                   },
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(response)
                {
                    ResetWholeForm();
                    UpdatePagesJSon(response);
                },
                error: function(err)
                {
                    $('body').showAlert(err.responseText, 0, 'alert-error alert-danger');
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });
        }
        catch(e){
            var operation = (languageId == null || languageId == 'none') ? 'adding' : 'editing';
            $('body').showAlert('An unespected error occoured in al-pages file while ' + operation + ' a page. Here is the error from the server:

' + e + '

Please open an issue at Github reporting this entire message.', 0, 'alert-error alert-danger');
        }
    }

    function LoadSeoAttributes(idPage)
    {
        try{
            ResetWholeForm();
            $('#seo_attributes_idPage').val(idPage);
            $.ajax({
                type: 'POST',
                url: frontController + 'backend/' + $('#al_available_languages option:selected').val() + '/al_loadSeoAttributes',
                data: {'language' : $('#al_languages_navigator').html(),
                       'page' : $('#al_pages_navigator').html(),
                       'languageId' : $('#rk_language_' + idPage).val(),
                       'pageId' : idPage},
                beforeSend: function()
                {
                    $('body').AddAjaxLoader();
                },
                success: function(response)
                {
                    $(response).each(function(key, el)
                    {
                        switch(el.name)
                        {
                            case '#pages_isHome':
                            case '#pages_isPublished':
                                if(el.value == 1)
                                {
                                    $(el.name).attr('checked', 'checked');
                                }
                                else
                                {
                                    $(el.name).removeAttr("checked");
                                }
                                break;
                            default:
                                $(el.name).val(el.value);
                                break;
                        }
                    });
                },
                error: function(err)
                {
                    $('body').showAlert(err.responseText, 0, 'alert-error alert-danger');
                },
                complete: function()
                {
                    $('body').RemoveAjaxLoader();
                }
            });
        }
        catch(e){
            $('body').showAlert('An unespected error occoured in al-pages file while loading page\'s attributes. Here is the error from the server:

' + e + '

Please open an issue at Github reporting this entire message.', 0, 'alert-error alert-danger');
        }
    }

    function Select(element)
    {
        $('#al_pages_list .al_element_selected').removeClass('al_element_selected');
        element.addClass('al_element_selected');
    }

    function ResetWholeForm()
    {
        $("#al_page_form").ResetFormElements();
        $("#al_attributes_form").ResetFormElements();
        $("#al_sitemp_form").ResetFormElements();
    }

    function UpdatePagesJSon(response)
    {
        $(response).each(function(key, item)
        {
            switch(item.key)
            {
                case "message":
                    $('body').showAlert(item.value);

                case "pages_list":
                    var idSelectedPage = $('#al_pages_list .al_element_selected').attr('data-page-id');
                    $('#al_pages_list').html(item.value);
                    $('#al_pages_list .al_element_selector').each(function(key, item)
                    {
                        if(idSelectedPage == $(item).attr('data-page-id'))
                        {
                            $(item).addClass('al_element_selected');
                            return;
                        }
                    });

                    break;
                case "pages":
                    $('.rk-pages-navigator-box').html(item.value);
                    $('.al_page_item').click(function()
                    {
                        Navigate($('#al_languages_navigator').html(), $(this).attr('rel'));

                        return false;
                    });

                    break;
                case "permalinks":
                    $('#al_page_name').remove()
                    $('body').append(item.value);
                    break;
                case "permalink":
                    if($('#seo_attributes_permalink').val() != item.value) $('#seo_attributes_permalink').val(item.value);
                    break;
            }
        });

        $('body').pages('init');
    }

    $.fn.pages = function( method ) {
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.inlinelist' );
        }
    };
})($);<|endoftext|>


<commit_before>var data_array={
"20151204":4,
"20151203":5.5,
"20151202":6,
"20151201":4.5,
"20151130":5,
"20151129":4,
"20151128":4
};

var width = 900,
    height = 120,
    cellSize = 15; // cell size
    month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    color = ["#eee","#d6e685","#8cc665","#44a340","#1e6823"];
    range = [1,2,4,6];

var day = d3.time.format("%w"),
    week = d3.time.format("%U"),
    percent = d3.format(".1%"),
	format = d3.time.format("%Y%m%d");
	parseDate = d3.time.format("%Y%m%d").parse;

var svg = d3.select(".calender-map").selectAll("svg")
    .data(d3.range(2015, 2016))
  .enter().append("svg")
    .attr("width", '100%')
    .attr("data-height", '0.5678')
    .attr("viewBox",'0 0 ' + width + ' ' + height)
  .append("g")
    .attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")");

svg.append("text")
    .attr("transform", "translate(-10," + cellSize * 3.5 + ")rotate(-90)")
    .style("text-anchor", "middle")
    .text(function(d) { return d; });

var rect = svg.selectAll(".day")
    .data(function(d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
  .enter()
	.append("rect")
    .attr("class", "day")
    .attr("width", cellSize)
    .attr("height", cellSize)
    .attr("x", function(d) { return week(d) * cellSize; })
    .attr("y", function(d) { return day(d) * cellSize; })
    .attr("fill",'#fff')
    .datum(format);

var legend = svg.selectAll(".legend")
      .data(month)
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(" + (((i+1) * 50)+8) + ",0)"; });

svg.selectAll(".month")
    .data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
  .enter().append("path")
    .attr("class", "month")
    .attr("d", monthPath);

function getRange(d) {
  for (i = 0; i < range.length; i++) {
    if (d < range[i])
      return i;
  }
  return range.length;
}

  rect
      .attr("fill", function(d) {if (isNaN(data_array[d])) return color[0];  return color[getRange(data_array[d])]; })
	  .attr("data-title", function(d) { if (isNaN(data_array[d])) ret = "No record on "; else ret = data_array[d] + " hours on "; return ret + month[parseDate(d).getMonth()] + ". " + parseDate(d).getDate()});

d3.csv("",function() {
	$("rect").tooltip({container: 'body'});

});

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1,$2");
    return x;
}

function monthPath(t0) {
  var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
      d0 = +day(t0), w0 = +week(t0),
      d1 = +day(t1), w1 = +week(t1);
  return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize
      + "H" + w0 * cellSize + "V" + 7 * cellSize
      + "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize
      + "H" + (w1 + 1) * cellSize + "V" + 0
      + "H" + (w0 + 1) * cellSize + "Z";
}

<commit_msg>tracker<commit_after>var data_array={
"20151205":7,
"20151204":4,
"20151203":5.5,
"20151202":6,
"20151201":4.5,
"20151130":5,
"20151129":4,
"20151128":4
};

var width = 900,
    height = 120,
    cellSize = 15; // cell size
    month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    color = ["#eee","#d6e685","#8cc665","#44a340","#1e6823"];
    range = [1,2,4,6];

var day = d3.time.format("%w"),
    week = d3.time.format("%U"),
    percent = d3.format(".1%"),
	format = d3.time.format("%Y%m%d");
	parseDate = d3.time.format("%Y%m%d").parse;

var svg = d3.select(".calender-map").selectAll("svg")
    .data(d3.range(2015, 2016))
  .enter().append("svg")
    .attr("width", '100%')
    .attr("data-height", '0.5678')
    .attr("viewBox",'0 0 ' + width + ' ' + height)
  .append("g")
    .attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")");

svg.append("text")
    .attr("transform", "translate(-10," + cellSize * 3.5 + ")rotate(-90)")
    .style("text-anchor", "middle")
    .text(function(d) { return d; });

var rect = svg.selectAll(".day")
    .data(function(d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
  .enter()
	.append("rect")
    .attr("class", "day")
    .attr("width", cellSize)
    .attr("height", cellSize)
    .attr("x", function(d) { return week(d) * cellSize; })
    .attr("y", function(d) { return day(d) * cellSize; })
    .attr("fill",'#fff')
    .datum(format);

var legend = svg.selectAll(".legend")
      .data(month)
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(" + (((i+1) * 50)+8) + ",0)"; });

svg.selectAll(".month")
    .data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
  .enter().append("path")
    .attr("class", "month")
    .attr("d", monthPath);

function getRange(d) {
  for (i = 0; i < range.length; i++) {
    if (d < range[i])
      return i;
  }
  return range.length;
}

  rect
      .attr("fill", function(d) {if (isNaN(data_array[d])) return color[0];  return color[getRange(data_array[d])]; })
	  .attr("data-title", function(d) { if (isNaN(data_array[d])) ret = "No record on "; else ret = data_array[d] + " hours on "; return ret + month[parseDate(d).getMonth()] + ". " + parseDate(d).getDate()});

d3.csv("",function() {
	$("rect").tooltip({container: 'body'});

});

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1,$2");
    return x;
}

function monthPath(t0) {
  var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
      d0 = +day(t0), w0 = +week(t0),
      d1 = +day(t1), w1 = +week(t1);
  return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize
      + "H" + w0 * cellSize + "V" + 7 * cellSize
      + "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize
      + "H" + (w1 + 1) * cellSize + "V" + 0
      + "H" + (w0 + 1) * cellSize + "Z";
}

<|endoftext|>


<commit_before>(function () {
    $(function () {
        if(localStorage['cookies'] === undefined) {
            // Europe Cookie Consent Law - shows for all visitors as GeoBytes sometimes doesn't work
            $('head').append('');

            $('body').prepend('

We use cookies on this site. Our Privacy Policy outlines how we use cookies and what they are.
Close
');
        }
    });
})();
<commit_msg>Cookie banner<commit_after>(function () {
    $(function () {
        if(localStorage['cookies'] === undefined) {
            // Europe Cookie Consent Law - shows for all visitors as GeoBytes sometimes doesn't work
            $('head').append('');

            $('body').prepend('

We use cookies on this site. Our Privacy Policy outlines how we use cookies and what they are.
Close
');
        }
    });
})();
<|endoftext|>


<commit_before>/* Author:

*/

<commit_msg>battle script restored<commit_after>//Global variables
var imageObjects = new Array();
var scale = 10;
var canvas;
var context;
var battleReplay;
var currentStep = 0;

function LoadBattleReplay(replayLink) {
    $.ajax({
        url: replayLink,
        type: 'POST',
        dataType: 'json',
        data: '{id: "ID-javascript" }',
        contentType: 'application/json',
        success: function (data) { battleReplay = data; },
        complete: function () { InitResources(); },
        async: false
    });
}

function InitResources() {
    canvas = document.getElementById("canva");
    canvas.width = battleReplay.fieldSize.X * scale;
    canvas.height = battleReplay.fieldSize.Y * scale;
    context = canvas.getContext("2d");
    PreloadImages(battleReplay.snakes);
    animate();
}

function PreloadImages(snakes) {
    //Preload field textures
    imageObjects[0] = new Image();
    imageObjects[0].src = 'Manager/GetTexture/Field';

    //Preload snakes textures
    for (var i = 0; i < snakes.length; i++) {
        imageObjects[snakes[i].ShortId] = new Image();
        imageObjects[snakes[i].ShortId].src = 'Manager/GetTexture/' + snakes[i].LongId;
    }
}

function animate() {
    // clear
    context.clearRect(0, 0, canvas.width, canvas.height);
    // move
    ApplyEvent();
    // draw
    DrawBattlefield();

    // request new frame
    requestAnimFrame(function () { animate(); });
}

function ApplyEvent() {
    if (currentStep < battleReplay.events.length) {
        var e = battleReplay.events[currentStep];
        battleReplay.field[e.Y * battleReplay.fieldSize.X + e.X] = e.T;
    }
    currentStep++;
}

function DrawBattlefield() {
    for (var y = 0; y < battleReplay.fieldSize.Y; y++) {
        for (var x = 0; x < battleReplay.fieldSize.X; x++) {
            var fieldCell = battleReplay.field[y * battleReplay.fieldSize.X + x];
            var textureNum = determTexture(fieldCell);
            var texturePos = determElement(fieldCell);
            drawElement(textureNum, texturePos, x, y);
        }
    }
}

function drawElement(textureNum, texturePos, x, y) {
    context.drawImage(imageObjects[textureNum], texturePos, 0, 10, 10, x * scale, y * scale, scale, scale);
}

function determTexture(cell) {
    if (cell.length > 1) {
        var c = cell[1];
        return c;
    }
    return 0;
}

function determElement(cell) {
    var e = 0;
    switch (cell[0]) {
        case "W":
            e = 0;
            break;
        case "E":
            e = 10;
            break;
        case "G":
            e = 20;
            break;
        case "H":
            e = 0;
            break;
        case "B":
            e = 10;
            break;
        case "T":
            e = 20;
            break;
    }
    return e;
}

window.requestAnimFrame = (function (callback) {
    return window.requestAnimationFrame ||
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame ||
                window.oRequestAnimationFrame ||
                window.msRequestAnimationFrame ||
                function (callback) {
                    window.setTimeout(callback, 1000 / 60);
                };
})();<|endoftext|>


<commit_before>//
// Backbone-associations.js 0.2.0
//
// (c) 2012 Dhruva Ray, Jaynti Kanani
//
// Backbone-associations may be freely distributed under the MIT license; see the accompanying LICENSE.txt.
//
// Depends on [Backbone](https://github.com/documentcloud/backbone) (and thus on [Underscore](https://github.com/documentcloud/underscore/) as well)
//
// A complete [Test & Benchmark Suite](../test/test-suite.html) is included for your perusal.

// Initial Setup
// --------------
(function () {
    // The top-level namespace. All public Backbone classes and modules will be attached to this.
    // Exported for the browser and CommonJS.
    var _, Backbone, BackboneModel;
    if (typeof window === 'undefined') {
        _ = require('underscore');
        Backbone = require('backbone');
        exports = module.exports = Backbone;
    } else {
        _ = window._;
        Backbone = window.Backbone;
        exports = window;
    }
    BackboneModel = Backbone.Model.prototype;

    // Backbone.AssociatedModel
    // --------------

    //Add `Many` and `One` relations to Backbone Object
    Backbone.Many  = "Many";
    Backbone.One  = "One";
    //Define `AssociatedModel` (Extends Backbone.Model)
    Backbone.AssociatedModel = Backbone.Model.extend({
        //Define relations with Associated Model
        relations: undefined,
        //Set a hash of model attributes on the object,
        //firing `"change"` unless you choose to silence it.
        //It maintains relations between models during the set operation. It also bubbles up child events to the parent.
        set: function (key, value, options) {
            var attributes, processedRelations, tbp, attr;
            // Duplicate backbone's behavior to allow separate key/value parameters, instead of a single 'attributes' object.
            if (_.isObject(key) || key == null) {
                attributes = key;
                options = value;
            } else {
                attributes = {};
                attributes[key] = value;
            }
            // Extract attributes and options.
            options || (options = {});
            if (!attributes) return this;
            if (options.unset) for (attr in attributes) attributes[attr] = void 0;
            //Check for existence of relations in this model
            if (this.relations) {
                //Iterate over `this.relations` and `set` model and collection values
                _.each(this.relations, function (relation) {
                    var relationKey = relation.key, relatedModel = relation.relatedModel, collectionType = relation.collectionType,
                        val, relationOptions, data, defaults;
                    if (attributes[relationKey]) {
                        //Get value of attribute with relation key in `val`
                        val = getValue(attributes, relationKey);
                        //Get class if relation is stored as a string
                        relatedModel && _.isString(relatedModel) && (relatedModel = eval(relatedModel));
                        collectionType && _.isString(collectionType) && (collectionType = eval(collectionType));
                        //Merge in options specific to this relation
                        relationOptions = relation.options ? _.extend({}, relation.options, options) : options;
                        //If `relation` defines model as associated collection...
                        if (relation.type === Backbone.Many) {
                            //`collectionType` should be instance of `Backbone.Collection`
                            if (collectionType && !collectionType.prototype instanceof Backbone.Collection) {
                                throw new Error('collectionType must inherit from Backbone.Collection');
                            }

                            if (val instanceof Backbone.Collection) {
                                BackboneModel.set.call(this, relationKey, val);
                            } else if (!this.attributes[relationKey]) {
                                data = collectionType ? new collectionType() : this._createCollection(relatedModel);
                                data.add(val, relationOptions);
                                BackboneModel.set.call(this, relationKey, data);
                            } else {
                                this.attributes[relationKey].reset(val, relationOptions);
                            }

                        //If `relation` defines model as associated model...
                        } else if (relation.type === Backbone.One && relatedModel) {
                            if (val instanceof Backbone.AssociatedModel) {
                                BackboneModel.set.call(this, relationKey, val);
                            } else if (!this.attributes[relationKey]) {
                                data = new relatedModel(val);
                                BackboneModel.set.call(this, relationKey, data);
                            } else {
                                data = {};
                                defaults = getValue(this.attributes[relationKey], 'defaults');
                                _.each(this.attributes[relationKey].attributes, function (value, key) {
                                    !_.has(val, key) && (data[key] = (defaults ? defaults[key] : void 0));
                                });
                                this.attributes[relationKey].set(data, {silent: true});
                                this.attributes[relationKey].set(val);
                            }
                        }

                        //Add proxy events to respective parents. Only add callback if not defined
                        if (!this.attributes[relationKey]._proxyCallback) {
                            this.attributes[relationKey]._proxyCallback = function () {
                                var args = arguments, events = args[0], opt;
                                //Change the event name to a fully qualified path
                                if (_.contains(["change", "add", "remove", "reset", "destroy", "sync", "error"], events)) {
                                    args[0] = events.replace(events, events + ":" + relationKey);
                                } else {
                                    opt = events.split(":");
                                    args[0] = opt[0] + ":" + relationKey + "." + opt[1];
                                }
                                return this.trigger.apply(this, args);
                            };
                            this.attributes[relationKey].on("all", this.attributes[relationKey]._proxyCallback, this);
                        }

                        //Create a local `processedRelations` array to store the relation key which has been processed.
                        //We cannot use `this.relations` because if there is no value defined for `relationKey`, it will not get processed by either Backbone `set` or the `AssociatedModel` set
                        !processedRelations && (processedRelations = []);
                        if (_.indexOf(processedRelations, relationKey) === -1) {
                            processedRelations.push(relationKey);
                        }
                    }
                }, this);
            }
            if (processedRelations) {
                //Find attributes yet to be processed - `tbp`
                tbp = {};
                for (attr in attributes) {
                    if (_.indexOf(processedRelations, attr) === -1) {
                        tbp[attr] = attributes[attr];
                    }
                }
            } else {
                //Set all `attributes` to `tbp`
                tbp = attributes;
            }
            //Returns results for `BackboneModel.set`
            return BackboneModel.set.call(this, tbp, options);
        },
        //Returns New `collection` of type `relation.relatedModel`
        _createCollection: function (type) {
            var collection, relatedModel = type;
            _.isString(relatedModel) && (relatedModel = eval(relatedModel));
            if (relatedModel && relatedModel.prototype instanceof Backbone.AssociatedModel) {
                //Creates new `Backbone.Collection` and defines model class
                collection = new Backbone.Collection();
                collection.model = relatedModel;
            } else {
                throw new Error('type must inherit from Backbone.AssociatedModel');
            }
            return collection;
        },
        // `trigger` the event for `Associated Model`
        trigger : function () {
            //Check & Add `visited` tag to prevent event of cycle
            if (!this.visitedTrigger) {
                // mark as `visited`
                this.visitedTrigger = true;
                BackboneModel.trigger.apply(this, arguments);
                //delete `visited` tag to allow trigger for next `set` operation
                delete this.visitedTrigger;
            }
            return this;
        },
        /*hasChanged : function(attr){

            if (!arguments.length) {
                var hasLLeafAMChanged = BackboneModel.hasChanged.call(this);
                //Go down the hierarchy to see if anything has changed
                if (!hasLeafAMChanged){
                    if(this.relations){
                        for(var relation in this.relations){
                            if (attributes[relation.key] != undefined ){
                                if(attributes[relationKey].hasChanged())
                                    return true;
                            }
                        };
                    }
                    return false;
                }else{
                    return hasLeafAMChanged;
                }
            }else{
                return this[attr] && (this[attr] instanceof Backbone.AssociatedModel) ? this[attr].hasChanged() : BackboneModel.hasChanged.call(this[attr]);
            }

        },
        changedAttributes:function(){
            var changed;
            changed = BackboneModel.changedAttributes.call(this);
            if(this.relations){
                for(var relation in this.relations){
                    if (attributes[relation.key] != undefined ){
                        if(attributes[relationKey].hasChanged())
                            changed.push(attributes[relationKey]);
                    }
                };
            }
            return changed;
        },
        previous:function(attr){

        },*/
        //The JSON representation of the model.
        toJSON : function () {
            var json, aJson;
            if (!this.visited) {
                this.visited = true;
                //Get json representation from `BackboneModel.toJSON`
                json = BackboneModel.toJSON.apply(this, arguments);
                //If `this.relations` is defined, iterate through each `relation` and added it's json representation to parents' json representation
                if (this.relations) {
                    _.each(this.relations, function (relation) {
                        var attr = this.attributes[relation.key];
                        if (attr) {
                            aJson = attr.toJSON();
                            json[relation.key] = _.isArray(aJson) ? _.compact(aJson) : aJson;
                        }
                    }, this);
                }
                delete this.visited;
            }
            return json;
        },
        //deep `clone` the model.
        clone : function () {
            var cloneObj, newCollection;
            if (!this.visited) {
                this.visited = true;
                //Get shallow clone from `BackboneModel.clone`
                cloneObj = BackboneModel.clone.apply(this, arguments);
                //If `this.relations` is defined, iterate through each `relation` and `clone`
                if (this.relations) {
                    _.each(this.relations, function (relation) {
                        if (this.attributes[relation.key]) {
                            var sourceObj = cloneObj.attributes[relation.key];
                            if (sourceObj instanceof Backbone.Collection) {
                                //Creates new `collection` using `relation`
                                newCollection = relation.collectionType ? new relation.collectionType() : this._createCollection(relation.relatedModel);
                                //Added each `clone` model to `newCollection`
                                sourceObj.each(function (model) {
                                    var mClone = model.clone();
                                    mClone && newCollection.add(mClone);
                                });
                                cloneObj.attributes[relation.key] = newCollection;
                            } else if (sourceObj instanceof Backbone.Model) {
                                cloneObj.attributes[relation.key] = sourceObj.clone();
                            }
                        }
                    }, this);
                }
                delete this.visited;
            }
            return cloneObj;
        }
    });
    // Duplicate Backbone's behavior. To get a value from a Backbone object as a property
    // or as a function.
    var getValue = function (object, prop) {
        if (!(object && object[prop])) return null;
        return _.isFunction(object[prop]) ? object[prop]() : object[prop];
    };
})();
<commit_msg>add root variable for browser and remove duplicate code<commit_after>//
// Backbone-associations.js 0.2.0
//
// (c) 2012 Dhruva Ray, Jaynti Kanani
//
// Backbone-associations may be freely distributed under the MIT license; see the accompanying LICENSE.txt.
//
// Depends on [Backbone](https://github.com/documentcloud/backbone) (and thus on [Underscore](https://github.com/documentcloud/underscore/) as well)
//
// A complete [Test & Benchmark Suite](../test/test-suite.html) is included for your perusal.

// Initial Setup
// --------------
(function () {
    // The top-level namespace. All public Backbone classes and modules will be attached to this.
    // Exported for the browser and CommonJS.
    var root = this, _ = root._, Backbone = root.Backbone, BackboneModel;
    if (!_ && typeof exports !== 'undefined') {
        _ = require('underscore');
        Backbone = require('backbone');
        exports = module.exports = Backbone;
    }
    BackboneModel = Backbone.Model.prototype;

    // Backbone.AssociatedModel
    // --------------

    //Add `Many` and `One` relations to Backbone Object
    Backbone.Many  = "Many";
    Backbone.One  = "One";
    //Define `AssociatedModel` (Extends Backbone.Model)
    Backbone.AssociatedModel = Backbone.Model.extend({
        //Define relations with Associated Model
        relations: undefined,
        //Set a hash of model attributes on the object,
        //firing `"change"` unless you choose to silence it.
        //It maintains relations between models during the set operation. It also bubbles up child events to the parent.
        set: function (key, value, options) {
            var attributes, processedRelations, tbp, attr;
            // Duplicate backbone's behavior to allow separate key/value parameters, instead of a single 'attributes' object.
            if (_.isObject(key) || key == null) {
                attributes = key;
                options = value;
            } else {
                attributes = {};
                attributes[key] = value;
            }
            // Extract attributes and options.
            options || (options = {});
            if (!attributes) return this;
            if (options.unset) for (attr in attributes) attributes[attr] = void 0;
            //Check for existence of relations in this model
            if (this.relations) {
                //Iterate over `this.relations` and `set` model and collection values
                _.each(this.relations, function (relation) {
                    var relationKey = relation.key, relatedModel = relation.relatedModel, collectionType = relation.collectionType,
                        val, relationOptions, data, defaults;
                    if (attributes[relationKey]) {
                        //Get value of attribute with relation key in `val`
                        val = getValue(attributes, relationKey);
                        //Get class if relation is stored as a string
                        relatedModel && _.isString(relatedModel) && (relatedModel = eval(relatedModel));
                        collectionType && _.isString(collectionType) && (collectionType = eval(collectionType));
                        //Merge in options specific to this relation
                        relationOptions = relation.options ? _.extend({}, relation.options, options) : options;
                        //If `relation` defines model as associated collection...
                        if (relation.type === Backbone.Many) {
                            //`collectionType` should be instance of `Backbone.Collection`
                            if (collectionType && !collectionType.prototype instanceof Backbone.Collection) {
                                throw new Error('collectionType must inherit from Backbone.Collection');
                            }

                            if (val instanceof Backbone.Collection) {
                                BackboneModel.set.call(this, relationKey, val);
                            } else if (!this.attributes[relationKey]) {
                                data = collectionType ? new collectionType() : this._createCollection(relatedModel);
                                data.add(val, relationOptions);
                                BackboneModel.set.call(this, relationKey, data);
                            } else {
                                this.attributes[relationKey].reset(val, relationOptions);
                            }

                        //If `relation` defines model as associated model...
                        } else if (relation.type === Backbone.One && relatedModel) {
                            if (val instanceof Backbone.AssociatedModel) {
                                BackboneModel.set.call(this, relationKey, val);
                            } else if (!this.attributes[relationKey]) {
                                data = new relatedModel(val);
                                BackboneModel.set.call(this, relationKey, data);
                            } else {
                                data = {};
                                defaults = getValue(this.attributes[relationKey], 'defaults');
                                _.each(this.attributes[relationKey].attributes, function (value, key) {
                                    !_.has(val, key) && (data[key] = (defaults ? defaults[key] : void 0));
                                });
                                this.attributes[relationKey].set(data, {silent: true});
                                this.attributes[relationKey].set(val);
                            }
                        }

                        //Add proxy events to respective parents. Only add callback if not defined
                        if (!this.attributes[relationKey]._proxyCallback) {
                            this.attributes[relationKey]._proxyCallback = function () {
                                var args = arguments, events = args[0], opt;
                                //Change the event name to a fully qualified path
                                if (_.contains(["change", "add", "remove", "reset", "destroy", "sync", "error"], events)) {
                                    args[0] = events.replace(events, events + ":" + relationKey);
                                } else {
                                    opt = events.split(":");
                                    args[0] = opt[0] + ":" + relationKey + "." + opt[1];
                                }
                                return this.trigger.apply(this, args);
                            };
                            this.attributes[relationKey].on("all", this.attributes[relationKey]._proxyCallback, this);
                        }

                        //Create a local `processedRelations` array to store the relation key which has been processed.
                        //We cannot use `this.relations` because if there is no value defined for `relationKey`, it will not get processed by either Backbone `set` or the `AssociatedModel` set
                        !processedRelations && (processedRelations = []);
                        if (_.indexOf(processedRelations, relationKey) === -1) {
                            processedRelations.push(relationKey);
                        }
                    }
                }, this);
            }
            if (processedRelations) {
                //Find attributes yet to be processed - `tbp`
                tbp = {};
                for (attr in attributes) {
                    if (_.indexOf(processedRelations, attr) === -1) {
                        tbp[attr] = attributes[attr];
                    }
                }
            } else {
                //Set all `attributes` to `tbp`
                tbp = attributes;
            }
            //Returns results for `BackboneModel.set`
            return BackboneModel.set.call(this, tbp, options);
        },
        //Returns New `collection` of type `relation.relatedModel`
        _createCollection: function (type) {
            var collection, relatedModel = type;
            _.isString(relatedModel) && (relatedModel = eval(relatedModel));
            if (relatedModel && relatedModel.prototype instanceof Backbone.AssociatedModel) {
                //Creates new `Backbone.Collection` and defines model class
                collection = new Backbone.Collection();
                collection.model = relatedModel;
            } else {
                throw new Error('type must inherit from Backbone.AssociatedModel');
            }
            return collection;
        },
        // `trigger` the event for `Associated Model`
        trigger : function () {
            //Check & Add `visited` tag to prevent event of cycle
            if (!this.visitedTrigger) {
                // mark as `visited`
                this.visitedTrigger = true;
                BackboneModel.trigger.apply(this, arguments);
                //delete `visited` tag to allow trigger for next `set` operation
                delete this.visitedTrigger;
            }
            return this;
        },
        /*hasChanged : function(attr){

            if (!arguments.length) {
                var hasLLeafAMChanged = BackboneModel.hasChanged.call(this);
                //Go down the hierarchy to see if anything has changed
                if (!hasLeafAMChanged){
                    if(this.relations){
                        for(var relation in this.relations){
                            if (attributes[relation.key] != undefined ){
                                if(attributes[relationKey].hasChanged())
                                    return true;
                            }
                        };
                    }
                    return false;
                }else{
                    return hasLeafAMChanged;
                }
            }else{
                return this[attr] && (this[attr] instanceof Backbone.AssociatedModel) ? this[attr].hasChanged() : BackboneModel.hasChanged.call(this[attr]);
            }

        },
        changedAttributes:function(){
            var changed;
            changed = BackboneModel.changedAttributes.call(this);
            if(this.relations){
                for(var relation in this.relations){
                    if (attributes[relation.key] != undefined ){
                        if(attributes[relationKey].hasChanged())
                            changed.push(attributes[relationKey]);
                    }
                };
            }
            return changed;
        },
        previous:function(attr){

        },*/
        //The JSON representation of the model.
        toJSON : function () {
            var json, aJson;
            if (!this.visited) {
                this.visited = true;
                //Get json representation from `BackboneModel.toJSON`
                json = BackboneModel.toJSON.apply(this, arguments);
                //If `this.relations` is defined, iterate through each `relation` and added it's json representation to parents' json representation
                if (this.relations) {
                    _.each(this.relations, function (relation) {
                        var attr = this.attributes[relation.key];
                        if (attr) {
                            aJson = attr.toJSON();
                            json[relation.key] = _.isArray(aJson) ? _.compact(aJson) : aJson;
                        }
                    }, this);
                }
                delete this.visited;
            }
            return json;
        },
        //deep `clone` the model.
        clone : function () {
            var cloneObj, newCollection;
            if (!this.visited) {
                this.visited = true;
                //Get shallow clone from `BackboneModel.clone`
                cloneObj = BackboneModel.clone.apply(this, arguments);
                //If `this.relations` is defined, iterate through each `relation` and `clone`
                if (this.relations) {
                    _.each(this.relations, function (relation) {
                        if (this.attributes[relation.key]) {
                            var sourceObj = cloneObj.attributes[relation.key];
                            if (sourceObj instanceof Backbone.Collection) {
                                //Creates new `collection` using `relation`
                                newCollection = relation.collectionType ? new relation.collectionType() : this._createCollection(relation.relatedModel);
                                //Added each `clone` model to `newCollection`
                                sourceObj.each(function (model) {
                                    var mClone = model.clone();
                                    mClone && newCollection.add(mClone);
                                });
                                cloneObj.attributes[relation.key] = newCollection;
                            } else if (sourceObj instanceof Backbone.Model) {
                                cloneObj.attributes[relation.key] = sourceObj.clone();
                            }
                        }
                    }, this);
                }
                delete this.visited;
            }
            return cloneObj;
        }
    });
    // Duplicate Backbone's behavior. To get a value from a Backbone object as a property
    // or as a function.
    var getValue = function (object, prop) {
        if (!(object && object[prop])) return null;
        return _.isFunction(object[prop]) ? object[prop]() : object[prop];
    };
})();
<|endoftext|>


<commit_before>/*
select '["'|| lower(id) || '","' || name || '"],' from stations WHERE network = 'WFO' ORDER by id
*/

Ext.namespace('chatdata');

chatdata.rooms = [
 ['botstalk','All Bots Talk'],
 ["abq","Albuquerque"],
 ["abr","Aberdeen"],
 ["afc","Anchorage"],
 ["afg","Fairbanks"],
 ["ajk","Juneau"],
 ["akq","Wakefield"],
 ["aly","Albany"],
 ["ama","Amarillo"],
 ["apx","Gaylord"],
 ["arx","La Crosse"],
 ["bgm","Binghamton"],
 ["bis","Bismarck"],
 ["bmx","Birmingham"],
 ["boi","Boise"],
 ["bou","Denver"],
 ["box","Taunton"],
 ["bro","Brownsville"],
 ["btv","Burlington"],
 ["buf","Buffalo"],
 ["byz","Billings"],
 ["cae","Columbia"],
 ["car","Caribou"],
 ["chs","Charleston"],
 ["cle","Cleveland"],
 ["crp","Corpus Christi"],
 ["ctp","State College"],
 ["cys","Cheyenne"],
 ["ddc","Dodge City"],
 ["dlh","Duluth"],
 ["dmx","Des Moines"],
 ["dtx","Detroit"],
 ["dvn","Quad Cities Ia"],
 ["eax","Kansas City/Pleasant Hill"],
 ["eka","Eureka"],
 ["epz","El Paso Tx/Santa Teresa"],
 ["ewx","Austin/San Antonio"],
 ["ffc","Peachtree City"],
 ["fgf","Eastern North Dakota"],
 ["fgz","Flagstaff"],
 ["fsd","Sioux Falls"],
 ["fwd","Dallas/Fort Worth"],
 ["ggw","Glasgow"],
 ["gid","Hastings"],
 ["gjt","Grand Junction"],
 ["gld","Goodland"],
 ["grb","Green Bay"],
 ["grr","Grand Rapids"],
 ["gsp","Greenville/Spartanburg"],
 ["gum","Guam"],
 ["gyx","Gray"],
 ["hfo","Honolulu"],
 ["hgx","Houston/Galveston"],
 ["hnx","San Joaquin Valley/Hanford"],
 ["hun","Huntsville"],
 ["ict","Wichita"],
 ["ilm","Wilmington"],
 ["iln","Wilmington"],
 ["ilx","Lincoln"],
 ["ind","Indianapolis"],
 ["iwx","Northern Indiana"],
 ["jan","Jackson"],
 ["jax","Jacksonville"],
 ["jkl","Jackson"],
 ["jsj","San Juan"],
 ["key","Key West"],
 ["lbf","North Platte"],
 ["lch","Lake Charles"],
 ["lix","New Orleans"],
 ["lkn","Elko"],
 ["lmk","Louisville"],
 ["lot","Chicago"],
 ["lox","Los Angeles/Oxnard"],
 ["lsx","St Louis"],
 ["lub","Lubbock"],
 ["lwx","Baltimore Md/ Washington Dc"],
 ["lzk","Little Rock"],
 ["maf","Midland/Odessa"],
 ["meg","Memphis"],
 ["mfl","Miami"],
 ["mfr","Medford"],
 ["mhx","Newport/Morehead City"],
 ["mkx","Milwaukee/Sullivan"],
 ["mlb","Melbourne"],
 ["mob","Mobile"],
 ["mpx","Twin Cities/Chanhassen"],
 ["mqt","Marquette"],
 ["mrx","Morristown"],
 ["mso","Missoula"],
 ["mtr","San Francisco"],
 ["oax","Omaha/Valley"],
 ["ohx","Nashville"],
 ["okx","New York"],
 ["otx","Spokane"],
 ["oun","Norman"],
 ["pah","Paducah"],
 ["pbz","Pittsburgh"],
 ["pdt","Pendleton"],
 ["phi","Mount Holly"],
 ["pih","Pocatello/Idaho Falls"],
 ["pqr","Portland"],
 ["psr","Phoenix"],
 ["pub","Pueblo"],
 ["rah","Raleigh"],
 ["rev","Reno"],
 ["riw","Riverton"],
 ["rlx","Charleston"],
 ["rnk","Blacksburg"],
 ["sew","Seattle"],
 ["sgf","Springfield"],
 ["sgx","San Diego"],
 ["shv","Shreveport"],
 ["sjt","San Angelo"],
 ["sju","San Juan"],
 ["slc","Salt Lake City"],
 ["sto","Sacramento"],
 ["tae","Tallahassee"],
 ["tbw","Tampa Bay Area/Ruskin"],
 ["tfx","Great Falls"],
 ["top","Topeka"],
 ["tsa","Tulsa"],
 ["twc","Tucson"],
 ["unr","Rapid City"],
 ["vef","Las Vegas"]
];
<commit_msg>back we go<commit_after>/*
select '["'|| lower(id) || 'chat","' || name || '"],' from stations WHERE network = 'WFO' ORDER by id
*/

Ext.namespace('chatdata');

chatdata.rooms = [
 ['botstalk','All Bots Talk'],
 ["abqchat","Albuquerque"],
 ["abrchat","Aberdeen"],
 ["afcchat","Anchorage"],
 ["afgchat","Fairbanks"],
 ["ajkchat","Juneau"],
 ["akqchat","Wakefield"],
 ["alychat","Albany"],
 ["amachat","Amarillo"],
 ["apxchat","Gaylord"],
 ["arxchat","La Crosse"],
 ["bgmchat","Binghamton"],
 ["bischat","Bismarck"],
 ["bmxchat","Birmingham"],
 ["boichat","Boise"],
 ["bouchat","Denver"],
 ["boxchat","Taunton"],
 ["brochat","Brownsville"],
 ["btvchat","Burlington"],
 ["bufchat","Buffalo"],
 ["byzchat","Billings"],
 ["caechat","Columbia"],
 ["carchat","Caribou"],
 ["chschat","Charleston"],
 ["clechat","Cleveland"],
 ["crpchat","Corpus Christi"],
 ["ctpchat","State College"],
 ["cyschat","Cheyenne"],
 ["ddcchat","Dodge City"],
 ["dlhchat","Duluth"],
 ["dmxchat","Des Moines"],
 ["dtxchat","Detroit"],
 ["dvnchat","Quad Cities Ia"],
 ["eaxchat","Kansas City/Pleasant Hill"],
 ["ekachat","Eureka"],
 ["epzchat","El Paso Tx/Santa Teresa"],
 ["ewxchat","Austin/San Antonio"],
 ["ffcchat","Peachtree City"],
 ["fgfchat","Eastern North Dakota"],
 ["fgzchat","Flagstaff"],
 ["fsdchat","Sioux Falls"],
 ["fwdchat","Dallas/Fort Worth"],
 ["ggwchat","Glasgow"],
 ["gidchat","Hastings"],
 ["gjtchat","Grand Junction"],
 ["gldchat","Goodland"],
 ["grbchat","Green Bay"],
 ["grrchat","Grand Rapids"],
 ["gspchat","Greenville/Spartanburg"],
 ["gumchat","Guam"],
 ["gyxchat","Gray"],
 ["hfochat","Honolulu"],
 ["hgxchat","Houston/Galveston"],
 ["hnxchat","San Joaquin Valley/Hanford"],
 ["hunchat","Huntsville"],
 ["ictchat","Wichita"],
 ["ilmchat","Wilmington"],
 ["ilnchat","Wilmington"],
 ["ilxchat","Lincoln"],
 ["indchat","Indianapolis"],
 ["iwxchat","Northern Indiana"],
 ["janchat","Jackson"],
 ["jaxchat","Jacksonville"],
 ["jklchat","Jackson"],
 ["jsjchat","San Juan"],
 ["keychat","Key West"],
 ["lbfchat","North Platte"],
 ["lchchat","Lake Charles"],
 ["lixchat","New Orleans"],
 ["lknchat","Elko"],
 ["lmkchat","Louisville"],
 ["lotchat","Chicago"],
 ["loxchat","Los Angeles/Oxnard"],
 ["lsxchat","St Louis"],
 ["lubchat","Lubbock"],
 ["lwxchat","Baltimore Md/ Washington Dc"],
 ["lzkchat","Little Rock"],
 ["mafchat","Midland/Odessa"],
 ["megchat","Memphis"],
 ["mflchat","Miami"],
 ["mfrchat","Medford"],
 ["mhxchat","Newport/Morehead City"],
 ["mkxchat","Milwaukee/Sullivan"],
 ["mlbchat","Melbourne"],
 ["mobchat","Mobile"],
 ["mpxchat","Twin Cities/Chanhassen"],
 ["mqtchat","Marquette"],
 ["mrxchat","Morristown"],
 ["msochat","Missoula"],
 ["mtrchat","San Francisco"],
 ["oaxchat","Omaha/Valley"],
 ["ohxchat","Nashville"],
 ["okxchat","New York"],
 ["otxchat","Spokane"],
 ["ounchat","Norman"],
 ["pahchat","Paducah"],
 ["pbzchat","Pittsburgh"],
 ["pdtchat","Pendleton"],
 ["phichat","Mount Holly"],
 ["pihchat","Pocatello/Idaho Falls"],
 ["pqrchat","Portland"],
 ["psrchat","Phoenix"],
 ["pubchat","Pueblo"],
 ["rahchat","Raleigh"],
 ["revchat","Reno"],
 ["riwchat","Riverton"],
 ["rlxchat","Charleston"],
 ["rnkchat","Blacksburg"],
 ["sewchat","Seattle"],
 ["sgfchat","Springfield"],
 ["sgxchat","San Diego"],
 ["shvchat","Shreveport"],
 ["sjtchat","San Angelo"],
 ["sjuchat","San Juan"],
 ["slcchat","Salt Lake City"],
 ["stochat","Sacramento"],
 ["taechat","Tallahassee"],
 ["tbwchat","Tampa Bay Area/Ruskin"],
 ["tfxchat","Great Falls"],
 ["topchat","Topeka"],
 ["tsachat","Tulsa"],
 ["twcchat","Tucson"],
 ["unrchat","Rapid City"],
 ["vefchat","Las Vegas"]
];
<|endoftext|>


<commit_before>// A simple module to replace `Backbone.sync` with *localStorage*-based
// persistence. Models are given GUIDS, and saved into a JSON object. Simple
// as that.

// Generate four random hex digits.
function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};

// Generate a pseudo-GUID by concatenating random hexadecimal.
function guid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};

// Our Store is represented by a single JS object in *localStorage*. Create it
// with a meaningful name, like the name you'd give a table.
window.Store = function(name) {
  this.name = name;
  var store = localStorage.getItem(this.name);
  this.records = (store && store.split(",")) || [];
};

_.extend(Store.prototype, {

  // Save the current state of the **Store** to *localStorage*.
  save: function() {
    localStorage.setItem(this.name, this.records.join(","));
  },

  // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
  // have an id of it's own.
  create: function(model) {
    if (!model.id) model.id = model.attributes.id = guid();
    localStorage.setItem(this.name+"-"+model.id, JSON.stringify(model));
    this.records.push(model.id.toString());
    this.save();
    return model;
  },

  // Update a model by replacing its copy in `this.data`.
  update: function(model) {
    localStorage.setItem(this.name+"-"+model.id, JSON.stringify(model));
    if (!_.include(this.records, model.id.toString())) this.records.push(model.id.toString()); this.save();
    return model;
  },

  // Retrieve a model from `this.data` by id.
  find: function(model) {
    return JSON.parse(localStorage.getItem(this.name+"-"+model.id));
  },

  // Return the array of all models currently in storage.
  findAll: function() {
    return _.map(this.records, function(id){return JSON.parse(localStorage.getItem(this.name+"-"+id))}, this);
  },

  // Delete a model from `this.data`, returning it.
  destroy: function(model) {
    localStorage.removeItem(this.name+"-"+model.id);
    this.records = _.reject(this.records, function(record_id){return record_id == model.id.toString();});
    this.save();
    return model;
  }

});

// Override `Backbone.sync` to use delegate to the model or collection's
// *localStorage* property, which should be an instance of `Store`.
Backbone.sync = function(method, model, options) {

  var resp;
  var store = model.localStorage || model.collection.localStorage;

  switch (method) {
    case "read":    resp = model.id ? store.find(model) : store.findAll(); break;
    case "create":  resp = store.create(model);                            break;
    case "update":  resp = store.update(model);                            break;
    case "delete":  resp = store.destroy(model);                           break;
  }

  if (resp) {
    options.success(resp);
  } else {
    options.error("Record not found");
  }
};<commit_msg>Added backwards-compatibility with Backbone.sync <= 0.3.3<commit_after>// A simple module to replace `Backbone.sync` with *localStorage*-based
// persistence. Models are given GUIDS, and saved into a JSON object. Simple
// as that.

// Generate four random hex digits.
function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};

// Generate a pseudo-GUID by concatenating random hexadecimal.
function guid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};

// Our Store is represented by a single JS object in *localStorage*. Create it
// with a meaningful name, like the name you'd give a table.
window.Store = function(name) {
  this.name = name;
  var store = localStorage.getItem(this.name);
  this.records = (store && store.split(",")) || [];
};

_.extend(Store.prototype, {

  // Save the current state of the **Store** to *localStorage*.
  save: function() {
    localStorage.setItem(this.name, this.records.join(","));
  },

  // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
  // have an id of it's own.
  create: function(model) {
    if (!model.id) model.id = model.attributes.id = guid();
    localStorage.setItem(this.name+"-"+model.id, JSON.stringify(model));
    this.records.push(model.id.toString());
    this.save();
    return model;
  },

  // Update a model by replacing its copy in `this.data`.
  update: function(model) {
    localStorage.setItem(this.name+"-"+model.id, JSON.stringify(model));
    if (!_.include(this.records, model.id.toString())) this.records.push(model.id.toString()); this.save();
    return model;
  },

  // Retrieve a model from `this.data` by id.
  find: function(model) {
    return JSON.parse(localStorage.getItem(this.name+"-"+model.id));
  },

  // Return the array of all models currently in storage.
  findAll: function() {
    return _.map(this.records, function(id){return JSON.parse(localStorage.getItem(this.name+"-"+id));}, this);
  },

  // Delete a model from `this.data`, returning it.
  destroy: function(model) {
    localStorage.removeItem(this.name+"-"+model.id);
    this.records = _.reject(this.records, function(record_id){return record_id == model.id.toString();});
    this.save();
    return model;
  }

});

// Override `Backbone.sync` to use delegate to the model or collection's
// *localStorage* property, which should be an instance of `Store`.
Backbone.sync = function(method, model, options, error) {

  // Backwards compatibility with Backbone <= 0.3.3
  if (typeof options == 'function') {
    options = {
      success: options,
      error: error
    };
  }

  var resp;
  var store = model.localStorage || model.collection.localStorage;

  switch (method) {
    case "read":    resp = model.id ? store.find(model) : store.findAll(); break;
    case "create":  resp = store.create(model);                            break;
    case "update":  resp = store.update(model);                            break;
    case "delete":  resp = store.destroy(model);                           break;
  }

  if (resp) {
    options.success(resp);
  } else {
    options.error("Record not found");
  }
};<|endoftext|>


<commit_before>/*!
 * Backbone Named Routes 0.1.2
 * http://github.com/drtangible/backbone-named-routes
 */

(function(){

  var PATTERNS = {};

  var addRoute = function(name, route) {
    // Create key to store path patterns for this route name.
    PATTERNS[name] = PATTERNS[name] || {};

    // Store the route pattern for the combination of this route name and the
    // number of path params defined in the pattern.
    var numberOfParams = route.match(/\:\w+/g) ? route.match(/\:\w+/g).length : 0;
    PATTERNS[name][numberOfParams] = route;

    // Create the named route helper method for this route name.
    Backbone.NamedRoutes[name + 'Path'] = function() {
      var args = Array.prototype.slice.call(arguments);
      var hasQueryParams = _(args[args.length-1]).isObject();
      var numberOfParams = hasQueryParams ? arguments.length - 1 : arguments.length;
      var routePattern = PATTERNS[name][numberOfParams];
      var queryParams = hasQueryParams ? args.pop() : null;

      return pathFor(routePattern, args, queryParams);
    };
  };

  var pathFor = function(pathPattern, urlParams, queryParams) {
    var path = pathPattern;
    if (path.charAt(0) !== "/") path = "/" + path;
    if (Backbone.history.options && Backbone.history.options.root !== "/") path = Backbone.history.options.root + path;

    for(var i = 0; i < urlParams.length; i++) {
      var param = urlParams[i];
      path = path.replace(/\:\w+/, param);
    }

    var filteredQueryParams = filterObject(queryParams);

    if (filteredQueryParams && !_.isEmpty(filteredQueryParams)) {
      path += "?" + $.param(filteredQueryParams);
    }
    return path;
  };

  // Filters out `undefined` and `null` values
  var filterObject = function(object) {
    var filteredObject = {}, key;

    for(key in object) {
      if (has(object, key)) {
        if (object[key] != null) {
          filteredObject[key] = object[key];
        }
      }
    }

    return filteredObject;
  };

  // cache reference to `Object.prototype.hasOwnProperty`
  var hasOwnProperty = Object.prototype.hasOwnProperty;

  var has = function(object, key) {
    return hasOwnProperty.call(object, key);
  };

  Backbone.NamedRoutes = {

    VERSION: '0.1.3',

    addRoute: addRoute
  };

  _(Backbone.View.prototype).extend({
    helper: Backbone.NamedRoutes
  });

  _(Backbone.Router.prototype).extend({
    helper: Backbone.NamedRoutes
  });

  _(Backbone.Router.prototype).extend({
    route: (function(original) {
      return function(route, name, callback) {
        addRoute(name, route);
        original.apply(this, arguments);
      };
    }(Backbone.Router.prototype.route))
  });

}).call(this);
<commit_msg>Forgot to version bump the comment.<commit_after>/*!
 * Backbone Named Routes 0.1.3
 * http://github.com/drtangible/backbone-named-routes
 */

(function(){

  var PATTERNS = {};

  var addRoute = function(name, route) {
    // Create key to store path patterns for this route name.
    PATTERNS[name] = PATTERNS[name] || {};

    // Store the route pattern for the combination of this route name and the
    // number of path params defined in the pattern.
    var numberOfParams = route.match(/\:\w+/g) ? route.match(/\:\w+/g).length : 0;
    PATTERNS[name][numberOfParams] = route;

    // Create the named route helper method for this route name.
    Backbone.NamedRoutes[name + 'Path'] = function() {
      var args = Array.prototype.slice.call(arguments);
      var hasQueryParams = _(args[args.length-1]).isObject();
      var numberOfParams = hasQueryParams ? arguments.length - 1 : arguments.length;
      var routePattern = PATTERNS[name][numberOfParams];
      var queryParams = hasQueryParams ? args.pop() : null;

      return pathFor(routePattern, args, queryParams);
    };
  };

  var pathFor = function(pathPattern, urlParams, queryParams) {
    var path = pathPattern;
    if (path.charAt(0) !== "/") path = "/" + path;
    if (Backbone.history.options && Backbone.history.options.root !== "/") path = Backbone.history.options.root + path;

    for(var i = 0; i < urlParams.length; i++) {
      var param = urlParams[i];
      path = path.replace(/\:\w+/, param);
    }

    var filteredQueryParams = filterObject(queryParams);

    if (filteredQueryParams && !_.isEmpty(filteredQueryParams)) {
      path += "?" + $.param(filteredQueryParams);
    }
    return path;
  };

  // Filters out `undefined` and `null` values
  var filterObject = function(object) {
    var filteredObject = {}, key;

    for(key in object) {
      if (has(object, key)) {
        if (object[key] != null) {
          filteredObject[key] = object[key];
        }
      }
    }

    return filteredObject;
  };

  // cache reference to `Object.prototype.hasOwnProperty`
  var hasOwnProperty = Object.prototype.hasOwnProperty;

  var has = function(object, key) {
    return hasOwnProperty.call(object, key);
  };

  Backbone.NamedRoutes = {

    VERSION: '0.1.3',

    addRoute: addRoute
  };

  _(Backbone.View.prototype).extend({
    helper: Backbone.NamedRoutes
  });

  _(Backbone.Router.prototype).extend({
    helper: Backbone.NamedRoutes
  });

  _(Backbone.Router.prototype).extend({
    route: (function(original) {
      return function(route, name, callback) {
        addRoute(name, route);
        original.apply(this, arguments);
      };
    }(Backbone.Router.prototype.route))
  });

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


<commit_before>/*
 * Configuration backend, used to save tokens and other sensetive data
 */

import express from 'express';
let router = express.Router();
import Config from 'models/config';

/**
 * @apiDefine DBError
 *
 * @apiError (500) {Object} DBError
 *
 * @apiErrorExample {json} Error-Response:
 *      HTTP/1.1 500 InternalServerError
 *      {
 *          "error": "DBError",
 *          "error_details": "some DBError description",
 *          "results": {}
 *      }
 */

/**
 * @apiDefine RequestSuccess
 * @apiSuccess (200) {Boolean} error Should always be false
 * @apiSuccess (200) {Object} results Contains the results of Request
 * @apiSuccess (200) {String} results.id Id of the created config entry in DB
 *
 * @apiSuccessExample {json} Success-Response:
 *      HTTP/1.1 200 OK
 *      {
 *          "error": false,
 *          "results": {
 *                  "id": "21fsdkg9342ijhgh9sf0234",
 *                  "name": "twitter-consumer-key",
 *                  "value": "2sad21f2fxzcv23rszdvcs8219vsfd"
 *              }
 *      }
 */

/**
 * @apiDefine EntryNotFound
 *
 * @apiError (404) {Object} EntryNotFound
 *
 * @apiErrorExample {json} Error-Response:
 *      HTTP/1.1 404 NotFound
 *      {
 *          "error": "EntryNotFound",
 *          "error_details": "Requested config is not found",
 *          "results": {}
 *      }
 */

/**
 * @api {get} /config/ List all configs
 * @apiName getConfigRoot
 * @apiGroup config
 *
 * @apiUse DBError
 *
 * @apiSuccess (200) {Boolean} error Should always be false
 * @apiSuccess (200) {Object} results Contains the results of Request
 * @apiSuccess (200) {Array} results.list List of entries
 *
 * @apiSuccessExample {json} Success-Response:
 *      HTTP/1.1 200 OK
 *      {
 *          "error": false,
 *          "results": {
 *                  "list": [
 *                      {
 *                          "id": "21fsdkg9342ijhgh9sf0234",
 *                          "name": "twitter-consumer-key",
 *                          "value": "2sad21f2fxzcv23rszdvcs8219vsfd"
 *                      }
 *                  ]
 *              }
 *      }
 */
router.get('/', (req, res) => {
    Config.find({}, (err, entries) => {
        if (err) {
            console.log(err);
            return res.status(500).send({
                'error': 'DBError',
                'error_details': 'Could not list entries',
                'results': {},
            });
        }
        return res.status(200).send({
            'error': false,
            'results': {
                'list': entries,
            },
        });
    });
});

/**
 * @api {post} /config/ Create config entry
 * @apiName postConfig
 * @apiGroup config
 *
 * @apiParam {String} name Config entry unique name
 * @apiParam {String} value Config entry value
 *
 * @apiParamExample {json} Request-Example:
 *      {
 *          "name": "twitter-consumer-key",
 *          "value": "2sad21f2fxzcv23rszdvcs8219vsfd"
 *      }
 *
 * @apiUse DBError
 * @apiUse RequestSuccess
 *
 * @apiError (400) {Object} EntryExists Config entry with provided name is already in DB, send back entry id for updates
 *
 * @apiErrorExample {json} Error-Response:
 *      HTTP/1.1 400 BadRequest
 *      {
 *          "error": "ExtryExists",
 *          "error_details": "This config entry already exists",
 *          "results": {"id": "21dsa2t234tdsfsr141"}
 *      }
 */
router.post('/', (req, res) => {
    // Check if we have that entry already
    Config.findOne({
        'name': req.body.name
    }, (err, entry) => {
        if (err) {
            console.log(err);
            return res.status(500).send({
                'error': 'DBError',
                'error_details': 'Could not check for entry',
                'results': {},
            });
        }
        if (entry) {
            // if exists return id for future requests
            return res.status(400).send({
                'error': 'EntryExists',
                'error_details': 'This config entry already exists',
                'results': {'id': entry._id},
            });
        }
        return new Config({
            'name': req.body.name,
            'value': req.body.value,
        }).save((err, entry) => {
            if (err) {
                console.log(err);
                return res.status(500).send({
                    'error': 'DBError',
                    'error_details': 'Could not save new entry',
                    'results': {},
                });
            }
            return res.status(200).send({
                'error': false,
                'results': {'id': entry._id, 'name': entry.name, 'value': entry.value},
            });
        });
    });
});

/**
 * @api {get} /config/:optionName Get config entry value
 * @apiVersion 0.0.1
 * @apiName getConfig
 * @apiGroup config
 *
 * @apiParam {String} optionName Config entry name to return
 *
 * @apiUse DBError
 * @apiUse RequestSuccess
 * @apiUse EntryNotFound
 */
router.get('/:optionName', (req, res) => {
    Config.findOne({
        'name': req.params.optionName,
    }, (err, entry) => {
        if (err) {
            console.log(err);
            return res.status(500).send({
                'error': 'DBError',
                'error_details': 'Could not check for entry',
                'results': {},
            });
        }
        if (!entry) {
            // if does not exist - return NotFound
            return res.status(400).send({
                'error': 'EntryNotFound',
                'error_details': 'There is no such config entry',
                'results': {},
            });
        }
        return res.status(200).send({
            'error': false,
            'results': {'id': entry._id, 'name': entry.name, 'value': entry.value},
        });
    });
});

/**
 * @api {put} /config/ Update config entry value
 * @apiVersion 0.0.1
 * @apiName putConfig
 * @apiGroup config
 *
 * @apiParam {String} optionName Config entry unique name
 * @apiParam {String} value Config entry value
 *
 * @apiParamExample {json} Request-Example:
 *      {
 *          "optionName": "twitter-consumer-key",
 *          "value": "2sad21f2fxzcv23rszdvcs8219vsfd"
 *      }
 *
 *
 * @apiUse DBError
 * @apiUse RequestSuccess
 * @apiUse EntryNotFound
 */
router.put('/', (req, res) => {
    // Check if we have that entry already
    Config.findOne({
        'name': req.body.optionName
    }, (err, entry) => {
        if (err) {
            console.log(err);
            return res.status(500).send({
                'error': 'DBError',
                'error_details': 'Could not check for entry',
                'results': {},
            });
        }
        if (!entry) {
            // if does not exist - return NotFound
            return res.status(400).send({
                'error': 'EntryNotFound',
                'error_details': 'There is no such config entry',
                'results': {},
            });
        }
        // update with the new values
        entry.value = req.body.value;
        return entry.save((err, entry) => {
            if (err) {
                console.log(err);
                return res.status(500).send({
                    'error': 'DBError',
                    'error_details': 'Could not save new entry',
                    'results': {},
                });
            }
            return res.status(200).send({
                'error': false,
                'results': {'id': entry._id, 'name': entry.name, 'value': entry.value},
            });
        });
    });
});

/**
 * @api {delete} /config/:id Delete config entry by id
 * @apiVersion 0.0.1
 * @apiName getConfig
 * @apiGroup config
 *
 * @apiParam {String} id Config entry id
 *
 * @apiUse DBError
 * @apiUse EntryNotFound
 *
 * @apiSuccess (200) {Boolean} error Should always be false
 * @apiSuccess (200) {Object} results Contains the results of Request
 *
 * @apiSuccessExample {json} Success-Response:
 *      HTTP/1.1 200 OK
 *      {
 *          "error": false,
 *          "results": {}
 *      }
 */
router.delete('/:id', (req, res) => {
    Config.findByIdAndRemove(req.params.id, (err, entry) => {
        if (err) {
            console.log(err);
            return res.status(500).send({
                'error': 'DBError',
                'error_details': 'Could not get entry',
                'results': {},
            });
        }
        if (!entry) {
            // if does not exist - return NotFound
            return res.status(400).send({
                'error': 'EntryNotFound',
                'error_details': 'There is no such config entry',
                'results': {},
            });
        }
        // successfully deleted entry
        return res.status(200).send({
            'error': false,
            'results': {},
        });
    })
})

export {router};
<commit_msg>comment fixes<commit_after>/**
 * Configuration backend, used to save tokens and other sensetive data
 */

import express from 'express';
let router = express.Router();
import Config from 'models/config';

/**
 * @apiDefine DBError
 *
 * @apiError (500) {Object} DBError
 *
 * @apiErrorExample {json} Error-Response:
 *      HTTP/1.1 500 InternalServerError
 *      {
 *          "error": "DBError",
 *          "error_details": "some DBError description",
 *          "results": {}
 *      }
 */

/**
 * @apiDefine RequestSuccess
 * @apiSuccess (200) {Boolean} error Should always be false
 * @apiSuccess (200) {Object} results Contains the results of Request
 * @apiSuccess (200) {String} results.id Id of the created config entry in DB
 *
 * @apiSuccessExample {json} Success-Response:
 *      HTTP/1.1 200 OK
 *      {
 *          "error": false,
 *          "results": {
 *                  "id": "21fsdkg9342ijhgh9sf0234",
 *                  "name": "twitter-consumer-key",
 *                  "value": "2sad21f2fxzcv23rszdvcs8219vsfd"
 *              }
 *      }
 */

/**
 * @apiDefine EntryNotFound
 *
 * @apiError (404) {Object} EntryNotFound
 *
 * @apiErrorExample {json} Error-Response:
 *      HTTP/1.1 404 NotFound
 *      {
 *          "error": "EntryNotFound",
 *          "error_details": "Requested config is not found",
 *          "results": {}
 *      }
 */

/**
 * @api {get} /config/ List all configs
 * @apiName getConfigRoot
 * @apiGroup config
 *
 * @apiUse DBError
 *
 * @apiSuccess (200) {Boolean} error Should always be false
 * @apiSuccess (200) {Object} results Contains the results of Request
 * @apiSuccess (200) {Array} results.list List of entries
 *
 * @apiSuccessExample {json} Success-Response:
 *      HTTP/1.1 200 OK
 *      {
 *          "error": false,
 *          "results": {
 *                  "list": [
 *                      {
 *                          "id": "21fsdkg9342ijhgh9sf0234",
 *                          "name": "twitter-consumer-key",
 *                          "value": "2sad21f2fxzcv23rszdvcs8219vsfd"
 *                      }
 *                  ]
 *              }
 *      }
 */
router.get('/', (req, res) => {
    Config.find({}, (err, entries) => {
        if (err) {
            console.log(err);
            return res.status(500).send({
                'error': 'DBError',
                'error_details': 'Could not list entries',
                'results': {},
            });
        }
        return res.status(200).send({
            'error': false,
            'results': {
                'list': entries,
            },
        });
    });
});

/**
 * @api {post} /config/ Create config entry
 * @apiName postConfig
 * @apiGroup config
 *
 * @apiParam {String} name Config entry unique name
 * @apiParam {String} value Config entry value
 *
 * @apiParamExample {json} Request-Example:
 *      {
 *          "name": "twitter-consumer-key",
 *          "value": "2sad21f2fxzcv23rszdvcs8219vsfd"
 *      }
 *
 * @apiUse DBError
 * @apiUse RequestSuccess
 *
 * @apiError (400) {Object} EntryExists Config entry with provided name is already in DB, send back entry id for updates
 *
 * @apiErrorExample {json} Error-Response:
 *      HTTP/1.1 400 BadRequest
 *      {
 *          "error": "ExtryExists",
 *          "error_details": "This config entry already exists",
 *          "results": {"id": "21dsa2t234tdsfsr141"}
 *      }
 */
router.post('/', (req, res) => {
    // Check if we have that entry already
    Config.findOne({
        'name': req.body.name
    }, (err, entry) => {
        if (err) {
            console.log(err);
            return res.status(500).send({
                'error': 'DBError',
                'error_details': 'Could not check for entry',
                'results': {},
            });
        }
        if (entry) {
            // if exists return id for future requests
            return res.status(400).send({
                'error': 'EntryExists',
                'error_details': 'This config entry already exists',
                'results': {'id': entry._id},
            });
        }
        return new Config({
            'name': req.body.name,
            'value': req.body.value,
        }).save((err, entry) => {
            if (err) {
                console.log(err);
                return res.status(500).send({
                    'error': 'DBError',
                    'error_details': 'Could not save new entry',
                    'results': {},
                });
            }
            return res.status(200).send({
                'error': false,
                'results': {'id': entry._id, 'name': entry.name, 'value': entry.value},
            });
        });
    });
});

/**
 * @api {get} /config/:optionName Get config entry value
 * @apiVersion 0.0.1
 * @apiName getConfig
 * @apiGroup config
 *
 * @apiParam {String} optionName Config entry name to return
 *
 * @apiUse DBError
 * @apiUse RequestSuccess
 * @apiUse EntryNotFound
 */
router.get('/:optionName', (req, res) => {
    Config.findOne({
        'name': req.params.optionName,
    }, (err, entry) => {
        if (err) {
            console.log(err);
            return res.status(500).send({
                'error': 'DBError',
                'error_details': 'Could not check for entry',
                'results': {},
            });
        }
        if (!entry) {
            // if does not exist - return NotFound
            return res.status(400).send({
                'error': 'EntryNotFound',
                'error_details': 'There is no such config entry',
                'results': {},
            });
        }
        return res.status(200).send({
            'error': false,
            'results': {'id': entry._id, 'name': entry.name, 'value': entry.value},
        });
    });
});

/**
 * @api {put} /config/ Update config entry value
 * @apiVersion 0.0.1
 * @apiName putConfig
 * @apiGroup config
 *
 * @apiParam {String} optionName Config entry unique name
 * @apiParam {String} value Config entry value
 *
 * @apiParamExample {json} Request-Example:
 *      {
 *          "optionName": "twitter-consumer-key",
 *          "value": "2sad21f2fxzcv23rszdvcs8219vsfd"
 *      }
 *
 *
 * @apiUse DBError
 * @apiUse RequestSuccess
 * @apiUse EntryNotFound
 */
router.put('/', (req, res) => {
    // Check if we have that entry already
    Config.findOne({
        'name': req.body.optionName
    }, (err, entry) => {
        if (err) {
            console.log(err);
            return res.status(500).send({
                'error': 'DBError',
                'error_details': 'Could not check for entry',
                'results': {},
            });
        }
        if (!entry) {
            // if does not exist - return NotFound
            return res.status(400).send({
                'error': 'EntryNotFound',
                'error_details': 'There is no such config entry',
                'results': {},
            });
        }
        // update with the new values
        entry.value = req.body.value;
        return entry.save((err, entry) => {
            if (err) {
                console.log(err);
                return res.status(500).send({
                    'error': 'DBError',
                    'error_details': 'Could not save new entry',
                    'results': {},
                });
            }
            return res.status(200).send({
                'error': false,
                'results': {'id': entry._id, 'name': entry.name, 'value': entry.value},
            });
        });
    });
});

/**
 * @api {delete} /config/:id Delete config entry by id
 * @apiVersion 0.0.1
 * @apiName getConfig
 * @apiGroup config
 *
 * @apiParam {String} id Config entry id
 *
 * @apiUse DBError
 * @apiUse EntryNotFound
 *
 * @apiSuccess (200) {Boolean} error Should always be false
 * @apiSuccess (200) {Object} results Contains the results of Request
 *
 * @apiSuccessExample {json} Success-Response:
 *      HTTP/1.1 200 OK
 *      {
 *          "error": false,
 *          "results": {}
 *      }
 */
router.delete('/:id', (req, res) => {
    Config.findByIdAndRemove(req.params.id, (err, entry) => {
        if (err) {
            console.log(err);
            return res.status(500).send({
                'error': 'DBError',
                'error_details': 'Could not get entry',
                'results': {},
            });
        }
        if (!entry) {
            // if does not exist - return NotFound
            return res.status(400).send({
                'error': 'EntryNotFound',
                'error_details': 'There is no such config entry',
                'results': {},
            });
        }
        // successfully deleted entry
        return res.status(200).send({
            'error': false,
            'results': {},
        });
    })
})

export {router};
<|endoftext|>