<commit_before>$(function(){

    setTimeout(function () {
        $('.splash').css('display','none');
    }, 4000);

    $('select').material_select();

    $('.tooltipped').tooltip({delay: 1});

    var site_url = $('body').attr('site-url');

    var wp; //water-point-id variable

    var season_var;

    var province_var;

    var funct_var;

    $('.modal').modal();

    $('.modal-trigger').modal();

    $('.button-collapse').sideNav({'edge': 'left'});

    var url = window.location.href;

    var url_length = url.split('/').length;

    funct_var = url.split('/')[url_length-1];

    season_var = url.split('/')[url_length-2];

    province_var = url.split('/')[url_length-3];

    //console.log(province_var+' '+season_var+' '+funct_var);

    count_waterpoints(province_var,season_var,funct_var);

    if(province_var == 'Northern'){
        $('#nth').addClass('active indigo lighten-1');
    }else if(province_var == 'Southern'){
        $('#sth').addClass('active indigo lighten-1');
    }else if(province_var == 'Eastern'){
        $('#est').addClass('active indigo lighten-1');
    }else if(province_var == 'Western'){
        $('#wst').addClass('active indigo lighten-1');
    }else if(province_var == 'all'){
        $('#allp').addClass('active indigo lighten-1');
    }

    if(season_var == 'Water'){
        $('#wyr').addClass('active indigo lighten-1');
    }else if(season_var == 'Seasonal'){
        $('#sea').addClass('active indigo lighten-1');
    }else if(season_var == 'Dry'){
        $('#dry').addClass('active indigo lighten-1');
    }else if(season_var == 'Unknown'){
        $('#unk').addClass('active indigo lighten-1');
    }else if(season_var == 'all'){
        $('#alls').addClass('active indigo lighten-1');
    }

    if(funct_var == 'functional'){
        $('#func').addClass('active indigo lighten-1');
    }else if(funct_var == 'bdown'){
        $('#bdown').addClass('active indigo lighten-1');
    }else if(funct_var == 'pdamaged'){
        $('#pdam').addClass('active indigo lighten-1');
    }else if(funct_var == 'sucon'){
        $('#sucon').addClass('active indigo lighten-1');
    }else if(funct_var == 'all'){
        $('#allf').addClass('active indigo lighten-1');
    }

    $.fn.digits = function(){
        return this.each(function(){
            $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
        })
    }

    function count_waterpoints(province,season,functionality){

        $.ajax({
            type: 'GET',
            url: site_url + 'index.php/fusion/count/'+province+'/'+season+'/'+functionality,
            dataType: 'json',
            beforeSend: function () {
                $('#wp-status').css({
                    'background-image':'url('+site_url+'/assets/img/floader.gif',
                    'background-position':'center',
                    'background-repeat':'no-repeat'});
            },
            success: function (data) {
                $('#wp-status').css({
                    'background-image':'',
                    'background-position':'',
                    'background-repeat':''});
                $('#wp-status span').show();
                if (data == null){
                    $('#wp-status h4').html('0');
                }else{
                    $('#wp-status h4').html(data[0].count).digits();
                }
                //console.log(data);
            }
        })
    }

    $(document).on('click', '#submit-wpu', function () {

        wp = $("#wpu").val();

        if(wp == null){
            Materialize.toast('You have not selected an attribute!', 4000);
        }else{
            $('#submit-wpu').attr('id', 'submit-wp-id');

            $("#wp_id").parent().parent().show();
            $("#wpu").parent().parent().hide();
        }

    });

    $(document).on('click', '#submit-wp-id', function () {

        var wpid = $("#wp_id").val();
        wp = $("#wpu").val();

        if (wpid.length > 0 && wp.length != null) {

            $.ajax({

                type: 'GET',
                url: site_url + 'index.php/fusion/get/'+wpid,
                dataType: 'json',
                beforeSend: function () {

                    $('div.modal-content div.row').css({'opacity':'0'});
                    $('.modal-content').css({
                        'background-color':'rgba(0, 0, 0, 0.37)',
                        'background-image':'url('+site_url+'/assets/img/loader.gif',
                        'background-position':'center',
                        'background-repeat':'no-repeat'});
                },
                success: function (data) {

                    $('div.modal-content div.row').css({'opacity':''});
                    $('.modal-content').css({
                        'background-color':'',
                        'background-image':'',
                        'background-position':'',
                        'background-repeat':''});
                    console.log(data);
                    //console.log(data[0].age);
                    console.log(wp);

                    $('#submit-wp-id').attr('id', 'submit-wp-update');
                    $('#submit-wp-update').html('Update');
                    $('.rowid').html(data[0].rowid);

                    $("#wp_id").parent().parent().hide();

                    if(wp == 'wsm'){

                        $("#wsm_update").parent().parent().show();
                        $('.wp_column_name').html('mechanic');
                        if(data[0].mechanic == 'No' || data[0].mechanic == null){
                            $('#init_msg').empty().append('The water point currently does not have a Mechanic. If you wish to update type the word Yes then click the update button');
                        }else if(data[0].mechanic == 'Yes'){
                            $('#init_msg').empty().append('The water point currently has a Mechanic. If you wish to update type the word No then click the update button');
                        }

                    }else if(wp == 'mngr'){

                        $("#mngr_update").parent().parent().show();
                        $('.wp_column_name').html('manager');
                        $('#init_msg').empty().append('The water point is managed by '+data[0].manager+'. If you wish to update type either (Community committee, Private Person, SALWACO, Religious Group, None Or Other)');

                    }else if(wp == 'chw'){

                        $("#chw_update").parent().parent().show();
                        $('.wp_column_name').html('chlorine');
                        if(data[0].chlorine == 'Yes'){
                            $('#init_msg').empty().append('The water point is chlorinated. If you wish to update type either (No Or Unknown)');
                        }else if(data[0].chlorine == 'No'){
                            $('#init_msg').empty().append('The water point is not chlorinated. If you wish to update type (Yes Or Unknown)');
                        }else if(data[0].chlorine == 'unknown' || data[0].chlorine == null || data[0].chlorine == undefined){
                            $('#init_msg').empty().append('Their is no sufficient info about the condition of the water. If you wish to update type either (Yes Or No)');
                        }

                    }else if(wp == 'wsq'){

                        $("#wsq_update").parent().parent().show();
                        $('.wp_column_name').html('qual');
                        if(data[0].qual == 'Clean (good smell- taste and color)' || data[0].qual == 'Clean'){
                            $('#init_msg').empty().append('The water quality is clean. If you wish to update type (Not Clean)');
                        }else if(data[0].qual == 'Not clean' || data[0].qual == 'Not Clean'){
                            $('#init_msg').empty().append('The water quality is not clean. If you wish to update type Clean');
                        }else if(data[0].qual == null || data[0].qual == undefined){
                            $('#init_msg').empty().append('The water quality is unknown. If you wish to update type either (Clean Or Not Clean)');
                        }
                    }

                }
            });

        } else {

            Materialize.toast('Please Provide Water Point ID!', 4000);

        }

    });

    $(document).on('click', '#submit-wp-update', function () {

        var rowid = $('.rowid').text();
        var colnm = $('.wp_column_name').text();
        var wp_update;

        wp = $("#wpu").val();

        if(wp == 'wsm'){
            wp_update = $('#wsm_update').val();
        }else if(wp == 'mngr'){
            var caps = capitalize_Words($('#mngr_update').val());
            wp_update = caps.replace(/ /g, '');
        }else if(wp == 'chw'){
            wp_update = $('#chw_update').val();
        }else if(wp == 'wsq'){
            wp_update = $('#wsq_update').val();
        }

        $.ajax({

            type: 'GET',
            url: site_url + 'index.php/fusion/update/'+colnm+'/'+rowid+'/'+wp_update,
            dataType: 'json',
            beforeSend: function () {

                $('div.modal-content div.row').css({'opacity':'0'});
                $('.modal-content').css({
                    'background-color':'rgba(0, 0, 0, 0.37)',
                    'background-image':'url('+site_url+'/assets/img/loader.gif',
                    'background-position':'center',
                    'background-repeat':'no-repeat'});
            },
            success: function (data) {
                $('div.modal-content div.row').css({'opacity':''});
                $('.modal-content').css({
                    'background-color':'',
                    'background-image':'',
                    'background-position':'',
                    'background-repeat':''});

                if(data[0].affected_rows == '1'){
                    $("#submit-wp-update").remove();
                    if(wp == 'wsm'){
                        $("#wsm_update").parent().parent().hide();
                    }else if(wp == 'mngr'){
                        $("#mngr_update").parent().parent().hide();
                    }else if(wp == 'chw'){
                        $("#chw_update").parent().parent().hide();
                    }else if(wp == 'wsq'){
                        $("#wsq_update").parent().parent().hide();
                    }
                    $('#init_msg').empty();
                    $('div.modal-content h4').css('text-align','center');
                    $('div.modal-content h4').html('Thank You For Your Contribution');
                    window.location.href = site_url+'index.php/explore/'+province_array+'/'+season_array;
                }
                console.log(data);
            }

        });

    });

    $('#sub1').on('click', function () {

        $('#submit-subscription').attr('id', 'submit-subscription-sub1').show();

        $(this).parent().parent().hide();
        $('#sub2').parent().parent().hide();
        $('#prov_id').parent().parent().show();
        $('#dist_id').parent().parent().show();
        $('#chief_id').parent().parent().show();
        $('#phone').parent().parent().show();

    });
    $('#sub2').on('click', function () {

        $('#submit-subscription').attr('id', 'submit-subscription-sub2').show();

        $(this).parent().parent().hide();
        $('#sub1').parent().parent().hide();
        $('#waterp_id').parent().parent().show();
        $('#phone').parent().parent().show();

    });

    $(document).on('click', '#submit-subscription-sub1', function () {

        var data = $("#subcription-form").serialize();

        var provid = $('#prov_id').val();
        var distid = $('#dist_id').val();
        var chiefid = $('#chief_id').val();
        var phone = $('#phone').val();

        if(provid.length > 0 && distid.length > 0 && chiefid.length > 0 && phone.length > 0){

            $.ajax({

                type : 'POST',
                url  : site_url+'index.php/subserv/add/one',
                data : data,
                dataType: 'json',
                beforeSend: function()
                {
                    $('div.modal-content div.row').css({'opacity':'0'});
                    $('.modal-content').css({
                        'background-color':'rgba(0, 0, 0, 0.37)',
                        'background-image':'url('+site_url+'/assets/img/loader.gif',
                        'background-position':'center',
                        'background-repeat':'no-repeat'});
                },
                success :  function(data)
                {
                    $('div.modal-content div.row').css({'opacity':''});
                    $('.modal-content').css({
                        'background-color':'',
                        'background-image':'',
                        'background-position':'',
                        'background-repeat':''});

                    $('#init_sub_msg').empty();
                    $('#prov_id').parent().parent().hide();
                    $('#dist_id').parent().parent().hide();
                    $('#chief_id').parent().parent().hide();
                    $('#phone').parent().parent().hide();
                    $('div.modal-content h4').css('text-align','center');
                    $('div.modal-content h4').html('Awesome, check your phone later for a confirmation message...');
                    window.setTimeout(function(){

                        window.location.href = site_url+'index.php/explore/'+province_array+'/'+season_array;

                    }, 3000);

                    console.log(data);
                }
            });

        }else{
            Materialize.toast('Please fill all inputs!', 4000);
        }
    });

    $(document).on('click', '#submit-subscription-sub2', function () {

        var data = $("#subcription-form").serialize();

        var waterpid = $('#waterp_id').val();
        var phone = $('#phone').val();

        if(waterpid.length > 0 && phone.length > 0){

            $.ajax({

                type : 'POST',
                url  : site_url+'index.php/subserv/add/two',
                data : data,
                dataType: 'json',
                beforeSend: function()
                {
                    $('div.modal-content div.row').css({'opacity':'0'});
                    $('.modal-content').css({
                        'background-color':'rgba(0, 0, 0, 0.37)',
                        'background-image':'url('+site_url+'/assets/img/loader.gif',
                        'background-position':'center',
                        'background-repeat':'no-repeat'});
                },
                success :  function(data)
                {
                    $('div.modal-content div.row').css({'opacity':''});
                    $('.modal-content').css({
                        'background-color':'',
                        'background-image':'',
                        'background-position':'',
                        'background-repeat':''});

                    $('#init_sub_msg').empty();
                    $('#waterp_id').parent().parent().hide();
                    $('#phone').parent().parent().hide();
                    $('div.modal-content h4').css('text-align','center');
                    $('div.modal-content h4').html('Awesome, check your phone later for a confirmation message...');
                    window.setTimeout(function(){

                        window.location.href = site_url+'index.php/explore/'+province_array+'/'+season_array;

                    }, 3000);

                    console.log(data);
                }
            });

        }else{
            Materialize.toast('Please fill all inputs!', 4000);
        }
    });
});

function capitalize_Words(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}<commit_msg>syntax transformed with Babel<commit_after>'use strict';

$(function () {

    setTimeout(function () {
        $('.splash').css('display', 'none');
    }, 4000);

    $('select').material_select();

    $('.tooltipped').tooltip({ delay: 1 });

    var site_url = $('body').attr('site-url');

    var wp; //water-point-id variable

    var season_var;

    var province_var;

    var funct_var;

    $('.modal').modal();

    $('.modal-trigger').modal();

    $('.button-collapse').sideNav({ 'edge': 'left' });

    var url = window.location.href;

    var url_length = url.split('/').length;

    funct_var = url.split('/')[url_length - 1];

    season_var = url.split('/')[url_length - 2];

    province_var = url.split('/')[url_length - 3];

    count_waterpoints(province_var, season_var, funct_var);

    if (province_var == 'Northern') {
        $('#nth').addClass('active indigo lighten-1');
    } else if (province_var == 'Southern') {
        $('#sth').addClass('active indigo lighten-1');
    } else if (province_var == 'Eastern') {
        $('#est').addClass('active indigo lighten-1');
    } else if (province_var == 'Western') {
        $('#wst').addClass('active indigo lighten-1');
    } else if (province_var == 'all') {
        $('#allp').addClass('active indigo lighten-1');
    }

    if (season_var == 'Water') {
        $('#wyr').addClass('active indigo lighten-1');
    } else if (season_var == 'Seasonal') {
        $('#sea').addClass('active indigo lighten-1');
    } else if (season_var == 'Dry') {
        $('#dry').addClass('active indigo lighten-1');
    } else if (season_var == 'Unknown') {
        $('#unk').addClass('active indigo lighten-1');
    } else if (season_var == 'all') {
        $('#alls').addClass('active indigo lighten-1');
    }

    if (funct_var == 'functional') {
        $('#func').addClass('active indigo lighten-1');
    } else if (funct_var == 'bdown') {
        $('#bdown').addClass('active indigo lighten-1');
    } else if (funct_var == 'pdamaged') {
        $('#pdam').addClass('active indigo lighten-1');
    } else if (funct_var == 'sucon') {
        $('#sucon').addClass('active indigo lighten-1');
    } else if (funct_var == 'all') {
        $('#allf').addClass('active indigo lighten-1');
    }

    $.fn.digits = function () {
        return this.each(function () {
            $(this).text($(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
        });
    };

    function count_waterpoints(province, season, functionality) {

        $.ajax({
            type: 'GET',
            url: site_url + 'index.php/fusion/count/' + province + '/' + season + '/' + functionality,
            dataType: 'json',
            beforeSend: function beforeSend() {
                $('#wp-status').css({
                    'background-image': 'url(' + site_url + '/assets/img/floader.gif',
                    'background-position': 'center',
                    'background-repeat': 'no-repeat' });
            },
            success: function success(data) {
                $('#wp-status').css({
                    'background-image': '',
                    'background-position': '',
                    'background-repeat': '' });
                $('#wp-status span').show();
                if (data == null) {
                    $('#wp-status h4').html('0');
                } else {
                    $('#wp-status h4').html(data[0].count).digits();
                }
                //console.log(data);
            }
        });
    }

    $(document).on('click', '#submit-wpu', function () {

        wp = $("#wpu").val();

        if (wp == null) {
            Materialize.toast('You have not selected an attribute!', 4000);
        } else {
            $('#submit-wpu').attr('id', 'submit-wp-id');

            $("#wp_id").parent().parent().show();
            $("#wpu").parent().parent().hide();
        }
    });

    $(document).on('click', '#submit-wp-id', function () {

        var wpid = $("#wp_id").val();
        wp = $("#wpu").val();

        if (wpid.length > 0 && wp.length != null) {

            $.ajax({

                type: 'GET',
                url: site_url + 'index.php/fusion/get/' + wpid,
                dataType: 'json',
                beforeSend: function beforeSend() {

                    $('div.modal-content div.row').css({ 'opacity': '0' });
                    $('.modal-content').css({
                        'background-color': 'rgba(0, 0, 0, 0.37)',
                        'background-image': 'url(' + site_url + '/assets/img/loader.gif',
                        'background-position': 'center',
                        'background-repeat': 'no-repeat' });
                },
                success: function success(data) {

                    $('div.modal-content div.row').css({ 'opacity': '' });
                    $('.modal-content').css({
                        'background-color': '',
                        'background-image': '',
                        'background-position': '',
                        'background-repeat': '' });
                    console.log(data);
                    //console.log(data[0].age);
                    console.log(wp);

                    $('#submit-wp-id').attr('id', 'submit-wp-update');
                    $('#submit-wp-update').html('Update');
                    $('.rowid').html(data[0].rowid);

                    $("#wp_id").parent().parent().hide();

                    if (wp == 'wsm') {

                        $("#wsm_update").parent().parent().show();
                        $('.wp_column_name').html('mechanic');
                        if (data[0].mechanic == 'No' || data[0].mechanic == null) {
                            $('#init_msg').empty().append('The water point currently does not have a Mechanic. If you wish to update type the word Yes then click the update button');
                        } else if (data[0].mechanic == 'Yes') {
                            $('#init_msg').empty().append('The water point currently has a Mechanic. If you wish to update type the word No then click the update button');
                        }
                    } else if (wp == 'mngr') {

                        $("#mngr_update").parent().parent().show();
                        $('.wp_column_name').html('manager');
                        $('#init_msg').empty().append('The water point is managed by ' + data[0].manager + '. If you wish to update type either (Community committee, Private Person, SALWACO, Religious Group, None Or Other)');
                    } else if (wp == 'chw') {

                        $("#chw_update").parent().parent().show();
                        $('.wp_column_name').html('chlorine');
                        if (data[0].chlorine == 'Yes') {
                            $('#init_msg').empty().append('The water point is chlorinated. If you wish to update type either (No Or Unknown)');
                        } else if (data[0].chlorine == 'No') {
                            $('#init_msg').empty().append('The water point is not chlorinated. If you wish to update type (Yes Or Unknown)');
                        } else if (data[0].chlorine == 'unknown' || data[0].chlorine == null || data[0].chlorine == undefined) {
                            $('#init_msg').empty().append('Their is no sufficient info about the condition of the water. If you wish to update type either (Yes Or No)');
                        }
                    } else if (wp == 'wsq') {

                        $("#wsq_update").parent().parent().show();
                        $('.wp_column_name').html('qual');
                        if (data[0].qual == 'Clean (good smell- taste and color)' || data[0].qual == 'Clean') {
                            $('#init_msg').empty().append('The water quality is clean. If you wish to update type (Not Clean)');
                        } else if (data[0].qual == 'Not clean' || data[0].qual == 'Not Clean') {
                            $('#init_msg').empty().append('The water quality is not clean. If you wish to update type Clean');
                        } else if (data[0].qual == null || data[0].qual == undefined) {
                            $('#init_msg').empty().append('The water quality is unknown. If you wish to update type either (Clean Or Not Clean)');
                        }
                    }
                }
            });
        } else {

            Materialize.toast('Please Provide Water Point ID!', 4000);
        }
    });

    $(document).on('click', '#submit-wp-update', function () {

        var rowid = $('.rowid').text();
        var colnm = $('.wp_column_name').text();
        var wp_update;

        wp = $("#wpu").val();

        if (wp == 'wsm') {
            wp_update = $('#wsm_update').val();
        } else if (wp == 'mngr') {
            var caps = capitalize_Words($('#mngr_update').val());
            wp_update = caps.replace(/ /g, '');
        } else if (wp == 'chw') {
            wp_update = $('#chw_update').val();
        } else if (wp == 'wsq') {
            wp_update = $('#wsq_update').val();
        }

        $.ajax({

            type: 'GET',
            url: site_url + 'index.php/fusion/update/' + colnm + '/' + rowid + '/' + wp_update,
            dataType: 'json',
            beforeSend: function beforeSend() {

                $('div.modal-content div.row').css({ 'opacity': '0' });
                $('.modal-content').css({
                    'background-color': 'rgba(0, 0, 0, 0.37)',
                    'background-image': 'url(' + site_url + '/assets/img/loader.gif',
                    'background-position': 'center',
                    'background-repeat': 'no-repeat' });
            },
            success: function success(data) {
                $('div.modal-content div.row').css({ 'opacity': '' });
                $('.modal-content').css({
                    'background-color': '',
                    'background-image': '',
                    'background-position': '',
                    'background-repeat': '' });

                if (data[0].affected_rows == '1') {
                    $("#submit-wp-update").remove();
                    if (wp == 'wsm') {
                        $("#wsm_update").parent().parent().hide();
                    } else if (wp == 'mngr') {
                        $("#mngr_update").parent().parent().hide();
                    } else if (wp == 'chw') {
                        $("#chw_update").parent().parent().hide();
                    } else if (wp == 'wsq') {
                        $("#wsq_update").parent().parent().hide();
                    }
                    $('#init_msg').empty();
                    $('div.modal-content h4').css('text-align', 'center');
                    $('div.modal-content h4').html('Thank You For Your Contribution');
                    window.location.href = site_url + 'index.php/explore/' + province_array + '/' + season_array;
                }
                console.log(data);
            }

        });
    });

    $('#sub1').on('click', function () {

        $('#submit-subscription').attr('id', 'submit-subscription-sub1').show();

        $(this).parent().parent().hide();
        $('#sub2').parent().parent().hide();
        $('#prov_id').parent().parent().show();
        $('#dist_id').parent().parent().show();
        $('#chief_id').parent().parent().show();
        $('#phone').parent().parent().show();
    });
    $('#sub2').on('click', function () {

        $('#submit-subscription').attr('id', 'submit-subscription-sub2').show();

        $(this).parent().parent().hide();
        $('#sub1').parent().parent().hide();
        $('#waterp_id').parent().parent().show();
        $('#phone').parent().parent().show();
    });

    $(document).on('click', '#submit-subscription-sub1', function () {

        var data = $("#subcription-form").serialize();

        var provid = $('#prov_id').val();
        var distid = $('#dist_id').val();
        var chiefid = $('#chief_id').val();
        var phone = $('#phone').val();

        if (provid.length > 0 && distid.length > 0 && chiefid.length > 0 && phone.length > 0) {

            $.ajax({

                type: 'POST',
                url: site_url + 'index.php/subserv/add/one',
                data: data,
                dataType: 'json',
                beforeSend: function beforeSend() {
                    $('div.modal-content div.row').css({ 'opacity': '0' });
                    $('.modal-content').css({
                        'background-color': 'rgba(0, 0, 0, 0.37)',
                        'background-image': 'url(' + site_url + '/assets/img/loader.gif',
                        'background-position': 'center',
                        'background-repeat': 'no-repeat' });
                },
                success: function success(data) {
                    $('div.modal-content div.row').css({ 'opacity': '' });
                    $('.modal-content').css({
                        'background-color': '',
                        'background-image': '',
                        'background-position': '',
                        'background-repeat': '' });

                    $('#init_sub_msg').empty();
                    $('#prov_id').parent().parent().hide();
                    $('#dist_id').parent().parent().hide();
                    $('#chief_id').parent().parent().hide();
                    $('#phone').parent().parent().hide();
                    $('div.modal-content h4').css('text-align', 'center');
                    $('div.modal-content h4').html('Awesome, check your phone later for a confirmation message...');
                    window.setTimeout(function () {

                        window.location.href = site_url + 'index.php/explore/' + province_array + '/' + season_array;
                    }, 3000);

                    console.log(data);
                }
            });
        } else {
            Materialize.toast('Please fill all inputs!', 4000);
        }
    });

    $(document).on('click', '#submit-subscription-sub2', function () {

        var data = $("#subcription-form").serialize();

        var waterpid = $('#waterp_id').val();
        var phone = $('#phone').val();

        if (waterpid.length > 0 && phone.length > 0) {

            $.ajax({

                type: 'POST',
                url: site_url + 'index.php/subserv/add/two',
                data: data,
                dataType: 'json',
                beforeSend: function beforeSend() {
                    $('div.modal-content div.row').css({ 'opacity': '0' });
                    $('.modal-content').css({
                        'background-color': 'rgba(0, 0, 0, 0.37)',
                        'background-image': 'url(' + site_url + '/assets/img/loader.gif',
                        'background-position': 'center',
                        'background-repeat': 'no-repeat' });
                },
                success: function success(data) {
                    $('div.modal-content div.row').css({ 'opacity': '' });
                    $('.modal-content').css({
                        'background-color': '',
                        'background-image': '',
                        'background-position': '',
                        'background-repeat': '' });

                    $('#init_sub_msg').empty();
                    $('#waterp_id').parent().parent().hide();
                    $('#phone').parent().parent().hide();
                    $('div.modal-content h4').css('text-align', 'center');
                    $('div.modal-content h4').html('Awesome, check your phone later for a confirmation message...');
                    window.setTimeout(function () {

                        window.location.href = site_url + 'index.php/explore/' + province_array + '/' + season_array;
                    }, 3000);

                    console.log(data);
                }
            });
        } else {
            Materialize.toast('Please fill all inputs!', 4000);
        }
    });
});

function capitalize_Words(str) {
    return str.replace(/\w\S*/g, function (txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}<|endoftext|>


<commit_before><commit_msg>set max queue time to 4hrs<commit_after><|endoftext|>


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

"use strict";

// Default repository entries
const MANAGER_GIT = "https://github.com/TheAppgineer/roon-extension-manager.git";
const MANAGER_NAME = "roon-extension-manager";

const REPOS_GIT = "https://github.com/TheAppgineer/roon-extension-repository.git";
const REPOS_NAME = 'roon-extension-repository';

// Start index of community extensions
const COMMUNITY_INDEX = 2;

const repos_base = [{
    repository: {
        type: "git",
        url: MANAGER_GIT
    }
},
{
    repository: {
        type: "git",
        url: REPOS_GIT
    }
}];

const ACTION_INSTALL = 1;
const ACTION_UPDATE = 2;
const ACTION_UNINSTALL = 3;
const ACTION_START = 4;
const ACTION_STOP = 5;

const config_dir = 'etc/'
const module_dir = 'lib/node_modules/'

var mkdirp = require('mkdirp');
var ApiExtensionRunner = require('node-api-extension-runner');

var runner;
var extension_root;
var repos = [];
var installed = {};
var updates_list = {};
var action_queue = {};
var stdio_inherit_mode;
var self_update_pending = false;

var repository_cb;
var installs_cb;
var updates_cb;
var status_cb;

function ApiExtensionInstaller(callbacks, inherit_mode) {
    if (callbacks) {
        if (callbacks.repository_changed) {
            repository_cb = callbacks.repository_changed;
        }
        if (callbacks.installs_changed) {
            installs_cb = callbacks.installs_changed;
        }
        if (callbacks.updates_changed) {
            updates_cb = callbacks.updates_changed;
        }
        if (callbacks.status_changed) {
            status_cb = callbacks.status_changed;
        }
    }

    if (inherit_mode) {
        stdio_inherit_mode = inherit_mode;
    } else {
        stdio_inherit_mode = 'ignore';
    }

    if (_check_prerequisites()) {
        _query_installs((installed) => {
            if (!installed[REPOS_NAME]) {
                // Install extension repository
                _queue_action(REPOS_NAME, { action: ACTION_INSTALL, url: REPOS_GIT });
            } else {
                _load_repository();
            }

            runner = new ApiExtensionRunner((running) => {
                for (let i = 0; i < running.length; i++) {
                    _start(running[i]);
                }
            });
        });

        _query_updates();
    }
}

ApiExtensionInstaller.prototype.install = function(repos_index) {
    const url = repos[repos_index].repository.url;

    _queue_action(_get_name_from_url(url), { action: ACTION_INSTALL, url: url });
}

ApiExtensionInstaller.prototype.uninstall = function(repos_index) {
    _queue_action(_get_name(repos_index), { action: ACTION_UNINSTALL });
}

ApiExtensionInstaller.prototype.update = function(repos_index) {
    _query_updates(_queue_updates, _get_name(repos_index));
}

ApiExtensionInstaller.prototype.update_all = function() {
    _query_updates(_queue_updates);
}

ApiExtensionInstaller.prototype.has_update = function(repos_index) {
    return updates_list[_get_name(repos_index)];
}

ApiExtensionInstaller.prototype.start = function(repos_index) {
    _start(_get_name(repos_index));
}

ApiExtensionInstaller.prototype.stop = function(repos_index) {
    _stop(_get_name(repos_index), true);
}

/**
 * Returns the status of an extension identified by name
 *
 * @param {String} name - The name of the extension according to its package.json file
 * @returns {('not_installed'|'installed'|'stopped'|'running')} - The current status of the extension
 */
ApiExtensionInstaller.prototype.get_status = function(repos_index) {
    const name = _get_name(repos_index);
    const version = installed[name];
    let state = (version ? 'installed' : 'not_installed');

    if (state == 'installed') {
        state = runner.get_status(name);
    }

    return {
        state: state,
        version: version
    };
}

ApiExtensionInstaller.prototype.get_details = function(repos_index) {
    return repos[repos_index];
}

function _check_prerequisites() {
    let execSync = require('child_process').execSync;
    let git_version = execSync('git --version').toString();
    let npm_version = execSync('npm --version').toString();

    if (git_version) {
        git_version = git_version.split(" ")[2];

        if (npm_version) {
            return true;
        }
    }

    _set_status("Please install git and npm", true);

    return false;
}

function _load_repository() {
    let fs = require('fs');
    let repos_path = extension_root + module_dir + REPOS_NAME + '/repository.json'

    fs.readFile(repos_path, 'utf8', function(err, data) {
        if (err) {
            _set_status("Extension Repository not found", true);
        } else {
            let values = [];

            repos = repos_base.concat(JSON.parse(data));

            // Collect extension names
            for (let i = COMMUNITY_INDEX; i < repos.length; i++) {
                values.push({
                    title: repos[i].display_name,
                    value: i
                });
            }

            _set_status("Extension Repository loaded", false);

            if (repository_cb) {
                repository_cb(values);
            }
        }
    });
}

function _get_name(repos_index) {
    return _get_name_from_url(repos[repos_index].repository.url);
}

function _get_name_from_url(url) {
    let substrings = url.split(':');

    if ((substrings[0]) == 'https') {
        substrings = substrings[1].split('.')
        if ((substrings[2]) == 'git') {
            substrings = substrings[1].split('/')
            return substrings[2];
        }
    }

    return null;
}

function _install(git, cb) {
    const name = _get_name_from_url(git);

    if (name) {
        _set_status("Installing: " + name + "...", false);

        let exec_file = require('child_process').execFile;
        exec_file('npm', ['install', '-g', git], (err, stdout, stderr) => {
            if (err) {
                _set_status("Installation failed: " + name, true);
                console.log(stderr);
            } else if (cb) {
                cb(name);
            }
        });
    }
}

function _register_installed_version(name) {
    _register_version(name, false);
}

function _register_updated_version(name) {
    _register_version(name, true);
}

function _register_version(name, update) {
    _query_installs((installed) => {
        const version = installed[name];
        _set_status((update ? "Updated: " : "Installed: ") + name + " (" + version + ")", false);

        if (name == REPOS_NAME) {
            _load_repository();
        } else if (update) {
            if (!self_update_pending && runner.get_status(name) != 'stopped') {
                _start(name);
            }
        } else {
            _start(name);
        }

        _remove_action(name);
    }, name);   // Query installed extension to obtain version number

    _query_updates(null, name);
}

function _update(name, cb) {
    if (name) {
        _set_status("Updating: " + name + "...", false);
        _stop(name, false, () => {
            let exec_file = require('child_process').execFile;
            exec_file('npm', ['update', '-g', name], (err, stdout, stderr) => {
                if (err) {
                    _set_status("Update failed: " + name, true);
                    console.log(stderr);
                } else if (cb) {
                    cb(name);
                }
            });
        });
    }
}

function _uninstall(name, cb) {
    if (name) {
        _set_status("Uninstalling: " + name + "...", false);
        _stop(name, true);

        let exec_file = require('child_process').execFile;
        exec_file('npm', ['uninstall', '-g', name], (err, stdout, stderr) => {
            // Internal callback
            if (cb) {
                cb(name);
            }
            // User callback
            if (installs_cb) {
                installs_cb(installed);
            }
        });
    }
}

function _unregister_version(name) {
    delete installed[name];
    delete updates_list[name];

    _set_status("Uninstalled: " + name, false);
    _remove_action(name);
}

function _start(name) {
    const config_path = extension_root + config_dir + name;
    const module_path = extension_root + module_dir + name;

    mkdirp(config_path, (err, made) => {
        if (err) {
            _set_status("Failed to create directory: " + config_path, true);
        } else {
            let inherit_mode = 'ignore';

            if (name == MANAGER_NAME) {
                // Pass the inherit mode to the new instance
                inherit_mode = stdio_inherit_mode;
            } else if (stdio_inherit_mode == 'inherit_all') {
                // Let the child inherit stdio streams
                inherit_mode = 'inherit';
            }

            runner.start(name, config_path, module_path, inherit_mode, (code) => {
                if (code) {
                    _set_status(name + " terminated unexpectedly", true);
                }
            });

            if (name == MANAGER_NAME) {
                process.exit();     // Let new instance take over
            } else {
                _set_status("Started: " + name, false);
            }
        }
    });
}

function _stop(name, user, cb) {
    const running = (runner.get_status(name) == 'running');

    if (name == MANAGER_NAME) {
        runner.prepare_exit(cb);
    } else {
        if (name != REPOS_NAME && running) {
            if (user) {
                runner.stop(name);
                _set_status("Stopped: " + name, false);
            } else {
                runner.terminate(name);
            }
        }

        if (cb) {
            cb();
        }
    }
}

function _queue_action(name, action_props) {
    action_queue[name] = action_props;

    if (Object.keys(action_queue).length == 1) {
        _perform_action();
    }
}

function _remove_action(name) {
    delete action_queue[name];

    _perform_action();      // Anything pending?
}

function _perform_action() {
    const length = Object.keys(action_queue).length;

    if (length) {
        let name;
        let index = 0;

        // Perform manager actions last
        do {
            name = Object.keys(action_queue)[index];
            index++;
        } while (name == MANAGER_NAME && index < length)

        switch (action_queue[name].action) {
            case ACTION_INSTALL:
                _install(action_queue[name].url, _register_installed_version);
                break;
            case ACTION_UPDATE:
                if (name == MANAGER_NAME) {
                    _update(name, _start);
                } else {
                    _update(name, _register_updated_version);
                }
                break;
            case ACTION_UNINSTALL:
                _uninstall(name, _unregister_version);
                break;
        }
    }
}

function _queue_updates(updates) {
    for (let name in updates) {
        if (name == MANAGER_NAME) {
            self_update_pending = true;     // Prevent extension restarts
        }
        _queue_action(name, { action: ACTION_UPDATE });
    }
}

function _query_installs(cb, name) {
    let args = ['list', '-g'];

    if (name) {
        args.push(name);
    }
    args.push('--depth=0');

    let exec_file = require('child_process').execFile;
    exec_file('npm', args, (err, stdout, stderr) => {
        if (err) {
            _set_status("Extension query failed", true);
            console.log(stderr);
        } else {
            let lines = stdout.split('\n');
            extension_root = lines[0].split('lib')[0];

            if (!name) {
                installed = {};
            }

            for (let i = 1; i < lines.length; i++) {
                let name_version = lines[i].split(' ')[1];
                if (name_version) {
                    name_version = name_version.split('@');
                    installed[name_version[0]] = name_version[1];
                }
            }

            // Internal callback
            if (cb) {
                cb(installed);
            }
            // User callback
            if (installs_cb) {
                installs_cb(installed);
            }
        }
    });
}

function _query_updates(cb, name) {
    let args = ['outdated', '-g'];

    if (name) {
        args.push(name);
    }
    args.push('--depth=0');

    let exec_file = require('child_process').execFile;
    exec_file('npm', args, (err, stdout, stderr) => {
        /* In npm 4.x the 'outdated' command has an exit code of 1 in case of outdated packages
         * still the output is in stdout (stderr is empty), hence the check for stderr instead of err.
         * Although old behavior (exit code of 0) may be selectable in future npm releases:
         * https://github.com/npm/npm/pull/16703
         * for compatibility it seems best to keep the stderr check.
         */
        if (stderr) {
            _set_status("Updates query failed", true);
            console.log(stderr);
        } else {
            const lines = stdout.split('\n');
            let updates = {};

            for (let i = 1; i < lines.length && lines[i]; i++) {
                const fields = lines[i].split(/[ ]+/);    // Split by space(s)
                const update_name = fields[0];
                const update_wanted = fields[2];

                updates[update_name] = update_wanted;
                updates_list[update_name] = update_wanted;
            }

            // User callback
            if (updates_cb) {
                // Supply full update list
                updates_cb(updates_list);
            }
            // Internal callback
            if (cb) {
                cb(updates);
            }
        }
    });
}

function _set_status(message, is_error) {
    if (status_cb) {
        status_cb(message, is_error);
    }

    console.log(is_error ? 'Err:' : 'Inf:', message);
}

exports = module.exports = ApiExtensionInstaller;
<commit_msg>Implemented 'restart_manager' interface<commit_after>// Copyright 2017 The Appgineer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

"use strict";

// Default repository entries
const MANAGER_GIT = "https://github.com/TheAppgineer/roon-extension-manager.git";
const MANAGER_NAME = "roon-extension-manager";

const REPOS_GIT = "https://github.com/TheAppgineer/roon-extension-repository.git";
const REPOS_NAME = 'roon-extension-repository';

// Start index of community extensions
const COMMUNITY_INDEX = 2;

const repos_base = [{
    repository: {
        type: "git",
        url: MANAGER_GIT
    }
},
{
    repository: {
        type: "git",
        url: REPOS_GIT
    }
}];

const ACTION_INSTALL = 1;
const ACTION_UPDATE = 2;
const ACTION_UNINSTALL = 3;
const ACTION_START = 4;
const ACTION_STOP = 5;

const config_dir = 'etc/'
const module_dir = 'lib/node_modules/'

var mkdirp = require('mkdirp');
var ApiExtensionRunner = require('node-api-extension-runner');

var runner;
var extension_root;
var repos = [];
var installed = {};
var updates_list = {};
var action_queue = {};
var stdio_inherit_mode;
var self_update_pending = false;

var repository_cb;
var installs_cb;
var updates_cb;
var status_cb;

function ApiExtensionInstaller(callbacks, inherit_mode) {
    if (callbacks) {
        if (callbacks.repository_changed) {
            repository_cb = callbacks.repository_changed;
        }
        if (callbacks.installs_changed) {
            installs_cb = callbacks.installs_changed;
        }
        if (callbacks.updates_changed) {
            updates_cb = callbacks.updates_changed;
        }
        if (callbacks.status_changed) {
            status_cb = callbacks.status_changed;
        }
    }

    if (inherit_mode) {
        stdio_inherit_mode = inherit_mode;
    } else {
        stdio_inherit_mode = 'ignore';
    }

    if (_check_prerequisites()) {
        _query_installs((installed) => {
            if (!installed[REPOS_NAME]) {
                // Install extension repository
                _queue_action(REPOS_NAME, { action: ACTION_INSTALL, url: REPOS_GIT });
            } else {
                _load_repository();
            }

            runner = new ApiExtensionRunner((running) => {
                for (let i = 0; i < running.length; i++) {
                    _start(running[i]);
                }
            });
        });

        _query_updates();
    }
}

ApiExtensionInstaller.prototype.install = function(repos_index) {
    const url = repos[repos_index].repository.url;

    _queue_action(_get_name_from_url(url), { action: ACTION_INSTALL, url: url });
}

ApiExtensionInstaller.prototype.uninstall = function(repos_index) {
    _queue_action(_get_name(repos_index), { action: ACTION_UNINSTALL });
}

ApiExtensionInstaller.prototype.update = function(repos_index) {
    _query_updates(_queue_updates, _get_name(repos_index));
}

ApiExtensionInstaller.prototype.update_all = function() {
    _query_updates(_queue_updates);
}

ApiExtensionInstaller.prototype.has_update = function(repos_index) {
    return updates_list[_get_name(repos_index)];
}

ApiExtensionInstaller.prototype.start = function(repos_index) {
    _start(_get_name(repos_index));
}

ApiExtensionInstaller.prototype.stop = function(repos_index) {
    _stop(_get_name(repos_index), true);
}

ApiExtensionInstaller.prototype.restart_manager = function() {
    _stop(MANAGER_NAME, false, () => {
        _start(MANAGER_NAME);
    });
}

/**
 * Returns the status of an extension identified by name
 *
 * @param {String} name - The name of the extension according to its package.json file
 * @returns {('not_installed'|'installed'|'stopped'|'running')} - The current status of the extension
 */
ApiExtensionInstaller.prototype.get_status = function(repos_index) {
    const name = _get_name(repos_index);
    const version = installed[name];
    let state = (version ? 'installed' : 'not_installed');

    if (state == 'installed') {
        state = runner.get_status(name);
    }

    return {
        state: state,
        version: version
    };
}

ApiExtensionInstaller.prototype.get_details = function(repos_index) {
    return repos[repos_index];
}

function _check_prerequisites() {
    let execSync = require('child_process').execSync;
    let git_version = execSync('git --version').toString();
    let npm_version = execSync('npm --version').toString();

    if (git_version) {
        git_version = git_version.split(" ")[2];

        if (npm_version) {
            return true;
        }
    }

    _set_status("Please install git and npm", true);

    return false;
}

function _load_repository() {
    let fs = require('fs');
    let repos_path = extension_root + module_dir + REPOS_NAME + '/repository.json'

    fs.readFile(repos_path, 'utf8', function(err, data) {
        if (err) {
            _set_status("Extension Repository not found", true);
        } else {
            let values = [];

            repos = repos_base.concat(JSON.parse(data));

            // Collect extension names
            for (let i = COMMUNITY_INDEX; i < repos.length; i++) {
                values.push({
                    title: repos[i].display_name,
                    value: i
                });
            }

            _set_status("Extension Repository loaded", false);

            if (repository_cb) {
                repository_cb(values);
            }
        }
    });
}

function _get_name(repos_index) {
    return _get_name_from_url(repos[repos_index].repository.url);
}

function _get_name_from_url(url) {
    let substrings = url.split(':');

    if ((substrings[0]) == 'https') {
        substrings = substrings[1].split('.')
        if ((substrings[2]) == 'git') {
            substrings = substrings[1].split('/')
            return substrings[2];
        }
    }

    return null;
}

function _install(git, cb) {
    const name = _get_name_from_url(git);

    if (name) {
        _set_status("Installing: " + name + "...", false);

        let exec_file = require('child_process').execFile;
        exec_file('npm', ['install', '-g', git], (err, stdout, stderr) => {
            if (err) {
                _set_status("Installation failed: " + name, true);
                console.log(stderr);
            } else if (cb) {
                cb(name);
            }
        });
    }
}

function _register_installed_version(name) {
    _register_version(name, false);
}

function _register_updated_version(name) {
    _register_version(name, true);
}

function _register_version(name, update) {
    _query_installs((installed) => {
        const version = installed[name];
        _set_status((update ? "Updated: " : "Installed: ") + name + " (" + version + ")", false);

        if (name == REPOS_NAME) {
            _load_repository();
        } else if (update) {
            if (!self_update_pending && runner.get_status(name) != 'stopped') {
                _start(name);
            }
        } else {
            _start(name);
        }

        _remove_action(name);
    }, name);   // Query installed extension to obtain version number

    _query_updates(null, name);
}

function _update(name, cb) {
    if (name) {
        _set_status("Updating: " + name + "...", false);
        _stop(name, false, () => {
            let exec_file = require('child_process').execFile;
            exec_file('npm', ['update', '-g', name], (err, stdout, stderr) => {
                if (err) {
                    _set_status("Update failed: " + name, true);
                    console.log(stderr);
                } else if (cb) {
                    cb(name);
                }
            });
        });
    }
}

function _uninstall(name, cb) {
    if (name) {
        _set_status("Uninstalling: " + name + "...", false);
        _stop(name, true);

        let exec_file = require('child_process').execFile;
        exec_file('npm', ['uninstall', '-g', name], (err, stdout, stderr) => {
            // Internal callback
            if (cb) {
                cb(name);
            }
            // User callback
            if (installs_cb) {
                installs_cb(installed);
            }
        });
    }
}

function _unregister_version(name) {
    delete installed[name];
    delete updates_list[name];

    _set_status("Uninstalled: " + name, false);
    _remove_action(name);
}

function _start(name) {
    const config_path = extension_root + config_dir + name;
    const module_path = extension_root + module_dir + name;

    mkdirp(config_path, (err, made) => {
        if (err) {
            _set_status("Failed to create directory: " + config_path, true);
        } else {
            let inherit_mode = 'ignore';

            if (name == MANAGER_NAME) {
                // Pass the inherit mode to the new instance
                inherit_mode = stdio_inherit_mode;
            } else if (stdio_inherit_mode == 'inherit_all') {
                // Let the child inherit stdio streams
                inherit_mode = 'inherit';
            }

            runner.start(name, config_path, module_path, inherit_mode, (code) => {
                if (code) {
                    _set_status(name + " terminated unexpectedly", true);
                }
            });

            if (name == MANAGER_NAME) {
                process.exit();     // Let new instance take over
            } else {
                _set_status("Started: " + name, false);
            }
        }
    });
}

function _stop(name, user, cb) {
    if (name == MANAGER_NAME) {
        runner.prepare_exit(cb);
    } else {
        const running = (runner.get_status(name) == 'running');

        if (name != REPOS_NAME && running) {
            if (user) {
                runner.stop(name);
                _set_status("Stopped: " + name, false);
            } else {
                runner.terminate(name);
            }
        }

        if (cb) {
            cb();
        }
    }
}

function _queue_action(name, action_props) {
    action_queue[name] = action_props;

    if (Object.keys(action_queue).length == 1) {
        _perform_action();
    }
}

function _remove_action(name) {
    delete action_queue[name];

    _perform_action();      // Anything pending?
}

function _perform_action() {
    const length = Object.keys(action_queue).length;

    if (length) {
        let name;
        let index = 0;

        // Perform manager actions last
        do {
            name = Object.keys(action_queue)[index];
            index++;
        } while (name == MANAGER_NAME && index < length)

        switch (action_queue[name].action) {
            case ACTION_INSTALL:
                _install(action_queue[name].url, _register_installed_version);
                break;
            case ACTION_UPDATE:
                if (name == MANAGER_NAME) {
                    _update(name, _start);
                } else {
                    _update(name, _register_updated_version);
                }
                break;
            case ACTION_UNINSTALL:
                _uninstall(name, _unregister_version);
                break;
        }
    }
}

function _queue_updates(updates) {
    for (let name in updates) {
        if (name == MANAGER_NAME) {
            self_update_pending = true;     // Prevent extension restarts
        }
        _queue_action(name, { action: ACTION_UPDATE });
    }
}

function _query_installs(cb, name) {
    let args = ['list', '-g'];

    if (name) {
        args.push(name);
    }
    args.push('--depth=0');

    let exec_file = require('child_process').execFile;
    exec_file('npm', args, (err, stdout, stderr) => {
        if (err) {
            _set_status("Extension query failed", true);
            console.log(stderr);
        } else {
            let lines = stdout.split('\n');
            extension_root = lines[0].split('lib')[0];

            if (!name) {
                installed = {};
            }

            for (let i = 1; i < lines.length; i++) {
                let name_version = lines[i].split(' ')[1];
                if (name_version) {
                    name_version = name_version.split('@');
                    installed[name_version[0]] = name_version[1];
                }
            }

            // Internal callback
            if (cb) {
                cb(installed);
            }
            // User callback
            if (installs_cb) {
                installs_cb(installed);
            }
        }
    });
}

function _query_updates(cb, name) {
    let args = ['outdated', '-g'];

    if (name) {
        args.push(name);
    }
    args.push('--depth=0');

    let exec_file = require('child_process').execFile;
    exec_file('npm', args, (err, stdout, stderr) => {
        /* In npm 4.x the 'outdated' command has an exit code of 1 in case of outdated packages
         * still the output is in stdout (stderr is empty), hence the check for stderr instead of err.
         * Although old behavior (exit code of 0) may be selectable in future npm releases:
         * https://github.com/npm/npm/pull/16703
         * for compatibility it seems best to keep the stderr check.
         */
        if (stderr) {
            _set_status("Updates query failed", true);
            console.log(stderr);
        } else {
            const lines = stdout.split('\n');
            let updates = {};

            for (let i = 1; i < lines.length && lines[i]; i++) {
                const fields = lines[i].split(/[ ]+/);    // Split by space(s)
                const update_name = fields[0];
                const update_wanted = fields[2];

                updates[update_name] = update_wanted;
                updates_list[update_name] = update_wanted;
            }

            // User callback
            if (updates_cb) {
                // Supply full update list
                updates_cb(updates_list);
            }
            // Internal callback
            if (cb) {
                cb(updates);
            }
        }
    });
}

function _set_status(message, is_error) {
    if (status_cb) {
        status_cb(message, is_error);
    }

    console.log(is_error ? 'Err:' : 'Inf:', message);
}

exports = module.exports = ApiExtensionInstaller;
<|endoftext|>


<commit_before>
import findPortSync from 'find-port-sync';
import { mergeWith, isNull, isArray, uniq } from 'lodash';

const { NODE_ENV = 'development' } = process.env;

export const isProd = NODE_ENV === 'production';
export const isDev = NODE_ENV === 'development';

const config = {
	port: findPortSync(),
	ssl: {
		enable: false,
		port: findPortSync() + 1,
	},
	staticDir: 'static',
	maxRestarts: isDev ? 0 : -1,
	middlewares: [
		'responseTime',
		'logger',
		'error',
		isProd && 'helmet',
		isProd && 'compress',
		'favicon',
		'plugins',
		'rewriteIndex',
		'static',
		'notFound',
	].filter(Boolean),
	plugins: [],
	redis: {
		enable: false,
		port: 6379,
		host: '127.0.0.1',

		// prefix: `${potConfig.name}:`,
		prefix: 'claypot',

		defaultExpiresIn: 60,
	},
	watch: {
		enable: isDev,
	},
};

export default config;

export const init = function init(newConfig) {
	return mergeWith(config, newConfig, (input, output) => {
		if (isArray(output)) {
			return uniq(isArray(input) ? input.concat(output) : output);
		}
		if (isNull(output) || Object.is(NaN, output)) {
			return input;
		}
		return output;
	});
};
<commit_msg>update default config<commit_after>
import findPortSync from 'find-port-sync';
import { mergeWith, isNull, isArray, uniq } from 'lodash';

const {
	NODE_ENV = 'development',

	PORT = findPortSync(),

	REDIS_PORT = 6379,
	REDIS_HOST = '127.0.0.1',
	REDIS_PREFIX = 'claypot', // TODO
} = process.env;

export const isProd = NODE_ENV === 'production';
export const isDev = NODE_ENV === 'development';

const config = {
	port: PORT,
	ssl: {
		enable: false,
		port: findPortSync() + 1,
	},
	staticDir: 'static',
	maxRestarts: isDev ? 0 : -1,
	middlewares: [
		'responseTime',
		'logger',
		'error',
		isProd && 'helmet',
		isProd && 'compress',
		'favicon',
		'plugins',
		'rewriteIndex',
		'static',
		'notFound',
	].filter(Boolean),
	plugins: [],
	redis: {
		enable: false,
		port: REDIS_PORT,
		host: REDIS_HOST,

		// prefix: `${potConfig.name}:`,
		prefix: REDIS_PREFIX,

		defaultExpiresIn: 60,
	},
	watch: {
		enable: isDev,
	},
};

export default config;

export const init = function init(newConfig) {
	return mergeWith(config, newConfig, (input, output) => {
		if (isArray(output)) {
			return uniq(isArray(input) ? input.concat(output) : output);
		}
		if (isNull(output) || Object.is(NaN, output)) {
			return input;
		}
		return output;
	});
};
<|endoftext|>


<commit_before>hashTrack.controller('TweetsController', ['$scope', '$sce', '$window', '$routeParams', 'geo', 'searchgeo', function($scope, $sce, $window, $routeParams, geo, searchgeo) {
$scope.hashtag = $routeParams.h;
$scope.since = $routeParams.s;

$scope.apps = [];
$scope.markerData = [];
$scope.hideNoTweets = true;
$scope.hideTweetPanel = true;

var mapDigest = function (callback) {
	console.log('before digest');
	$scope.$digest();
	console.log('after digest');
	callback();
}

var generateLinks = function(tweet) {
	var links = tweet.match(/https?:\/\/\S+/g);
	var newTweet;
	links.forEach(function(item) {
		newTweet = tweet.replace(item, '' + item + '');
	});
	return newTweet;
}

var mapRender = function (callback){
	geo.getUserGeo(function(error, geolocation) {
		if (error) {
			geolocation.latitude = 74;
			geolocation.longitude = -111;
			$scope.mapOptions = { center: { latitude: 74, longitude: -111 }, zoom: 6 }
		} else {
			$scope.mapOptions = { center: { latitude: geolocation.latitude, longitude: geolocation.longitude }, zoom: 9 };
		}
		console.log('latitude: ' + geolocation.latitude + ' longitude: ' + geolocation.longitude);
		callback ($scope.mapOptions);
	});
};

	var doGetLocalTweets = function(since) {
		searchgeo.getGeoTweets($scope.hashtag, 300, function(error, data) {
			if (error) return error;
			var i = 1;
			var newData = data.tweets.map(function(tweet) {
				var ret = {};
				if (tweet.coordinates != null) {
					ret.geolocation = {
						latitude: tweet.coordinates.coordinates[1],
						longitude: tweet.coordinates.coordinates[0]
					};
					ret.created_at = Date.parse(tweet.created_at);
					ret.text = tweet.text;
					ret.id = i;
					i++;
					console.log(ret);
					return ret;
				}
			});
			var j = 1;
			var markerData = data.tweets.map(function(marker) {
				var ret = {};
				if (marker.coordinates != null) {
					ret.user = {};
					ret.title = $sce.trustAsHtml(generateLinks(marker.text));
					ret.date = Date.parse(marker.created_at);
					ret.coords = {};
					ret.coords.latitude = marker.coordinates.coordinates[1];
					ret.coords.longitude = marker.coordinates.coordinates[0];
					ret.user.profile_image = marker.user.profile_image_url;
					ret.user.screen_name = marker.user.screen_name
					ret.id = j;
					j++;
					return ret;
				}
			});
			newData = searchgeo.clean(newData, undefined);
			$scope.markerOptions = { icon: '/images/tweet_icon.png' };
			$scope.markerEvents = {
				click: function(marker, eventName, model, args) {
					console.log('---------------tweet clicked----------------');
					console.log(model.title);
					$scope.tweet = {};
					$scope.tweet.user = {};
					$scope.tweet.user.profile_image = model.user.profile_image;
					$scope.tweet.user.screen_name = model.user.screen_name;
					console.log($scope.tweet.user.profile_image);
					$scope.tweet.text = model.title;
					$scope.tweet.date = model.date;
					$scope.hideTweetPanel = false;

				}
			}
			markerData = searchgeo.clean(markerData, undefined);

			$scope.apps = $scope.apps.concat(newData);
			$scope.markerData = $scope.markerData.concat(markerData);

			if ($scope.apps.length === 0) $scope.hideNoTweets = false;
			if (data.tweets.length === 100) {
				console.log('running additional api calls to twitter for more recent markers');
				doGetLocalTweets(data.highest_id);
			}
		}, since);
		return true;
	};
	doGetLocalTweets();
	mapRender(function (mapOptions) {
		$scope.map = mapOptions;
		mapDigest(function() {
			$scope.clearPanel('loading-alert');
		});
	});

	$scope.clearPanel = function(panelClass) {
		console.log('the x was clicked');
		$window.document.getElementsByClassName(panelClass)[0].className = panelClass + ' hidden';
	}

	$scope.showPanel = function(panelClass) {
		console.log('the x was clicked');
		$window.document.getElementsByClassName(panelClass)[0].className = panelClass;
	}

	$scope.toggleTweetPanel = function() {
		$scope.hideTweetPanel = !$scope.hideTweetPanel;
	}

}]);
<commit_msg>fixed bug where non linked tweets didnt work<commit_after>hashTrack.controller('TweetsController', ['$scope', '$sce', '$window', '$routeParams', 'geo', 'searchgeo', function($scope, $sce, $window, $routeParams, geo, searchgeo) {
$scope.hashtag = $routeParams.h;
$scope.since = $routeParams.s;

$scope.apps = [];
$scope.markerData = [];
$scope.hideNoTweets = true;
$scope.hideTweetPanel = true;

var mapDigest = function (callback) {
	console.log('before digest');
	$scope.$digest();
	console.log('after digest');
	callback();
}

var generateLinks = function(tweet) {
	var links = tweet.match(/https?:\/\/\S+/g);
	var newTweet;
	if (links) {
		links.forEach(function(item) {
			newTweet = tweet.replace(item, '' + item + '');
		});
	} else {
		newTweet = tweet;
	}
	return newTweet;
}

var mapRender = function (callback){
	geo.getUserGeo(function(error, geolocation) {
		if (error) {
			geolocation.latitude = 74;
			geolocation.longitude = -111;
			$scope.mapOptions = { center: { latitude: 74, longitude: -111 }, zoom: 6 }
		} else {
			$scope.mapOptions = { center: { latitude: geolocation.latitude, longitude: geolocation.longitude }, zoom: 9 };
		}
		console.log('latitude: ' + geolocation.latitude + ' longitude: ' + geolocation.longitude);
		callback ($scope.mapOptions);
	});
};

	var doGetLocalTweets = function(since) {
		searchgeo.getGeoTweets($scope.hashtag, 300, function(error, data) {
			if (error) return error;
			var i = 1;
			var newData = data.tweets.map(function(tweet) {
				var ret = {};
				if (tweet.coordinates != null) {
					ret.geolocation = {
						latitude: tweet.coordinates.coordinates[1],
						longitude: tweet.coordinates.coordinates[0]
					};
					ret.created_at = Date.parse(tweet.created_at);
					ret.text = tweet.text;
					ret.id = i;
					i++;
					console.log(ret);
					return ret;
				}
			});
			var j = 1;
			var markerData = data.tweets.map(function(marker) {
				var ret = {};
				if (marker.coordinates != null) {
					ret.user = {};
					ret.title = $sce.trustAsHtml(generateLinks(marker.text));
					ret.date = Date.parse(marker.created_at);
					ret.coords = {};
					ret.coords.latitude = marker.coordinates.coordinates[1];
					ret.coords.longitude = marker.coordinates.coordinates[0];
					ret.user.profile_image = marker.user.profile_image_url;
					ret.user.screen_name = marker.user.screen_name
					ret.id = j;
					j++;
					return ret;
				}
			});
			newData = searchgeo.clean(newData, undefined);
			$scope.markerOptions = { icon: '/images/tweet_icon.png' };
			$scope.markerEvents = {
				click: function(marker, eventName, model, args) {
					console.log('---------------tweet clicked----------------');
					console.log(model.title);
					$scope.tweet = {};
					$scope.tweet.user = {};
					$scope.tweet.user.profile_image = model.user.profile_image;
					$scope.tweet.user.screen_name = model.user.screen_name;
					console.log($scope.tweet.user.profile_image);
					$scope.tweet.text = model.title;
					$scope.tweet.date = model.date;
					$scope.hideTweetPanel = false;

				}
			}
			markerData = searchgeo.clean(markerData, undefined);

			$scope.apps = $scope.apps.concat(newData);
			$scope.markerData = $scope.markerData.concat(markerData);

			if ($scope.apps.length === 0) $scope.hideNoTweets = false;
			if (data.tweets.length === 100) {
				console.log('running additional api calls to twitter for more recent markers');
				doGetLocalTweets(data.highest_id);
			}
		}, since);
		return true;
	};
	doGetLocalTweets();
	mapRender(function (mapOptions) {
		$scope.map = mapOptions;
		mapDigest(function() {
			$scope.clearPanel('loading-alert');
		});
	});

	$scope.clearPanel = function(panelClass) {
		console.log('the x was clicked');
		$window.document.getElementsByClassName(panelClass)[0].className = panelClass + ' hidden';
	}

	$scope.showPanel = function(panelClass) {
		console.log('the x was clicked');
		$window.document.getElementsByClassName(panelClass)[0].className = panelClass;
	}

	$scope.toggleTweetPanel = function() {
		$scope.hideTweetPanel = !$scope.hideTweetPanel;
	}

}]);
<|endoftext|>


<commit_before>/* The MIT License (MIT)
 *
 * Copyright (c) 2015 Robert Hildebrandt
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

function exists(selector)
{
  wasFound = false;

  $(selector).each(function(){wasFound=true;});

  return wasFound;
}

function adaptBreadcrums()
{
  $(".content-root>li").remove();
}

function removeTitle()
{
  $(".content-root>h1.title").remove(); // Remove the title

 automatically added by QDoc
  $(".content-root>span.subtitle").remove(); // Remove the title  automatically added by QDoc
  $(".content-root>span.small-subtitle").remove(); // Remove the title  automatically added by QDoc
}

function adaptBrief()
{
  var p = $(".content-root > h1.title + p");

  if(p && p.html())
  {
    p.addClass("lead");
  }
}

function adaptTitle()
{
  var title = $(".content-root>h1.title");
  var subtitle = $(".content-root>span.subtitle");
  var smallSubtitle = $(".content-root>span.small-subtitle");

  var subtitleHtml = subtitle.html();
  var smallSubtitleHtml = smallSubtitle.html();

  subtitle.remove();
  smallSubtitle.remove();

  if(!subtitleHtml)
	  subtitleHtml = smallSubtitleHtml;
  else if(smallSubtitleHtml)
	  subtitleHtml = subtitleHtml + smallSubtitleHtml;

  if(subtitleHtml)
  {
    var titleHtml = title.html();
    title.html(titleHtml + " " + subtitleHtml + "");
  }

  title.addClass("page-header");
}

function adaptSidebar()
{
  var oldSidebar = $(".content-root > div.sidebar");
  var newSidebar = $(".sidebar-root");

  newSidebar.html(oldSidebar.html());

  oldSidebar.remove();

  $("div.toc > h3 > a").each(function(){
    tocHeader = $(this);
    tocHeader.replaceWith(tocHeader.html());
  });

  $(".toc > ul").addClass("list-unstyled");

  var toc = $("div.toc");
  toc.addClass("panel panel-default");
  toc.html("
" + toc.html() +  "
");
}

function getFilename()
{
  var fullUrl = window.location.pathname;
  fullUrl = fullUrl.replace('\\', '/');
  filename = fullUrl.split('/').pop();
  return filename;
}

function isFile(filename)
{
  return getFilename() == filename;
}

function adaptWarningOrNote(element, panelClass, docStyleClass)
{
  $("p > b:contains('"+element+":')").each(function() {
    var element = $(this);

    p = element.parent();

    element.addClass(docStyleClass + "-label");

    p.replaceWith("

"+p.html()+"

");
  });
}

function adaptWarning()
{
  adaptWarningOrNote("Warning", "panel-warning", "doc-style-warning");
}

function adaptNote()
{
  adaptWarningOrNote("Note", "panel-info", "doc-style-note");
}

function _addPager(naviArea)
{
  var prevPageElement = $(naviArea+" > .prevPage");
  var nextPageElement = $(naviArea+" > .nextPage");
  var navi = $(naviArea);

  if(navi && (prevPageElement || nextPageElement))
  {
    var prev = "";
    var next = "";

    var prevText = prevPageElement.text();
    var nextText = nextPageElement.text();

    if(prevText)
    {
      var text = prevText;
      var href = prevPageElement.attr("href");
      prev = "
← "+text+"
";
    }
    if(nextText)
    {
      var text = nextText;
      var href = nextPageElement.attr("href");
      next = "
"+text+" →
";
    }

    navi.replaceWith("
"+prev+next+"
");
  }
}

function addPager()
{
  _addPager(".footerNavi");
  //_addPager(".headerNavi");
  $(".headerNavi").remove();
}

function _adaptOverviewTables(selector)
{
  $("div.table > " + selector).each(function(){
    var table = $(this);
    var div = table.parent();

    div.attr("class", "panel panel-default");
    table.attr("class", "table table-bordered");
  });
}

function adaptOverviewTables()
{
  _adaptOverviewTables("table.annotated");
  _adaptOverviewTables("table.alignedsummary");
}

function _adaptOverviewLists(selector)
{
  var ul = $(selector);
  ul.wrap("

");
  ul.addClass("list-group");
  ul.children().addClass("list-group-item");
}

function adaptOverviewLists()
{
  _adaptOverviewLists("h2#properties + ul");
}

function adaptLinkToMemberPage(text)
{
  var linkToAllMembers = $(".content-root > ul > li > a:contains('"+text+"')");
  linkToAllMembers.parent().parent().addClass("list-unstyled");
  linkToAllMembers.html("» "+linkToAllMembers.html());
}

function adaptLinkToMembers()
{
  adaptLinkToMemberPage("List of all members");
}

function makeLiUnstyled(text)
{
  var li = $(".content-root > ul > li:contains('"+text+"')");
  li.parent().addClass("list-unstyled");
}

function adaptTablesInPanel(parentClass, tableclass)
{
  $("div."+parentClass+" > div.panel > div.panel-body > div.table > table"+tableclass).each(function(){
    var table = $(this);
    table.addClass("table");
    var div_table = table.parent();
    div_table.parent().after(div_table.html());
    div_table.remove();
  });
}

function adaptNamespaceTypeMemberDetails(parentClass)
{
  // Make it a panel
  $("div."+parentClass).each(function(){
    var root = $(this);

    var oldHtml = root.html();
    var newHtml = "";

    var prevIndex = 0;
    var newIndex = -1;

    while((newIndex = oldHtml.indexOf("<h3", prevIndex+1)) != -1)
    {
      newHtml = newHtml + oldHtml.substring(prevIndex, newIndex)
      if(prevIndex != 0)
        newHtml = newHtml + "
\n
\n";
      newHtml = newHtml + "
\n";
      newHtml = newHtml + "
\n";

      prevIndex = newIndex;
    }

    newHtml = newHtml + oldHtml.substring(prevIndex, oldHtml.length);
    if(prevIndex != 0)
      newHtml = newHtml + "
\n
\n";

    prevIndex = 0;
    newIndex = -1;

    oldHtml = newHtml;
    newHtml = "";

    while((newIndex = oldHtml.indexOf("
", prevIndex+1)) != -1)
    {
      newIndex += 5;
      newHtml = newHtml + oldHtml.substring(prevIndex, newIndex)
      newHtml = newHtml + "\n
\n";
      newHtml = newHtml + "
\n";

      prevIndex = newIndex;
    }

    newHtml = newHtml + oldHtml.substring(prevIndex, oldHtml.length);

    root.html(newHtml);
  });

  // Make the panel heading small by removing the h3 tag
  $("div."+parentClass + " > div.panel > div.panel-heading > h3").each(function(){
    $(this).replaceWith($(this).html());
  });
}

function adaptMemberDetails()
{
  adaptNamespaceTypeMemberDetails("classes");
  adaptNamespaceTypeMemberDetails("types");
  adaptNamespaceTypeMemberDetails("func");
  adaptNamespaceTypeMemberDetails("vars");
  adaptNamespaceTypeMemberDetails("prop");
  adaptNamespaceTypeMemberDetails("macros");
  adaptNamespaceTypeMemberDetails("relnonmem");

  if(exists("div.content-root > h1.title:contains(Obsolete)"))
    adaptNamespaceTypeMemberDetails("content-root");

  adaptTablesInPanel("types", ".valuelist");
}

function adaptLabel(label)
{
  $("code:contains('["+label+"]')").each(function(){
    var code = $(this);
    var parent = code.parent();
    code.remove();

    var rightAligned = "style='float:right'";
    var labelHtml = ""+label+"";
    parent.html(parent.html() + labelHtml);
  });
}

function adaptLabels()
{
  adaptLabel("protected");
  adaptLabel("static");
  adaptLabel("static protected");
  adaptLabel("signal");
  adaptLabel("slot");
  adaptLabel("protected slot");
  adaptLabel("virtual");
  adaptLabel("virtual protected");
  adaptLabel("pure virtual");
  adaptLabel("pure virtual protected");
  adaptLabel("override");
  adaptLabel("final");
}

function adaptVersion()
{
  var version = $("div.content-root > p.lead + div.panel.panel-default > table.table > tbody > tr >  td.memItemLeft:contains('Since:') + td.memItemRight:contains('Qt')");

  version.each(function(){
    var v = $(this);
    var t = v.text();
    t = t.replace('Qt', '');
    t = t.trim();

    v.text(t);
    v.addClass("SinceVersion");
  });

  version = $("div.panel-body >  p:contains('This function was introduced in  Qt')");

  version.each(function(){
    var v = $(this);
    var t = v.text();
    t = t.replace('Qt', '');
    t = t.trim();

    v.text(t);
    v.addClass("SinceVersion");
  });

}

function adaptChapterAndPart()
{
  var h0 = $('h0');

  h0.replaceWith('
' + h0.text() + '
');
}

function adaptGenericTables()
{
  var tables = $('table.generic');

  tables.addClass('table');
  tables.addClass('table-striped');
}

$(document).ready(function() {
  adaptBreadcrums();
  if(isFile("index.html"))
  {
    removeTitle();
  }else
  {
    adaptTitle();
    adaptBrief();
    adaptSidebar();
  }

  adaptWarning();
  adaptNote();
  addPager();

  adaptOverviewTables();
  adaptOverviewLists();
  adaptLinkToMembers();
  makeLiUnstyled("functions inherited from");
  makeLiUnstyled("member inherited from");

  adaptMemberDetails();
  adaptLabels();

  adaptVersion();

  adaptChapterAndPart();

  adaptGenericTables();
});
<commit_msg>improved style of list of all memebers<commit_after>/* The MIT License (MIT)
 *
 * Copyright (c) 2015 Robert Hildebrandt
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

function exists(selector)
{
  wasFound = false;

  $(selector).each(function(){wasFound=true;});

  return wasFound;
}

function adaptBreadcrums()
{
  $(".content-root>li").remove();
}

function removeTitle()
{
  $(".content-root>h1.title").remove(); // Remove the title

 automatically added by QDoc
  $(".content-root>span.subtitle").remove(); // Remove the title  automatically added by QDoc
  $(".content-root>span.small-subtitle").remove(); // Remove the title  automatically added by QDoc
}

function adaptBrief()
{
  var p = $(".content-root > h1.title + p");

  if(p && p.html())
  {
    p.addClass("lead");
  }
}

function adaptTitle()
{
  var title = $(".content-root>h1.title");
  var subtitle = $(".content-root>span.subtitle");
  var smallSubtitle = $(".content-root>span.small-subtitle");

  var subtitleHtml = subtitle.html();
  var smallSubtitleHtml = smallSubtitle.html();

  subtitle.remove();
  smallSubtitle.remove();

  if(!subtitleHtml)
	  subtitleHtml = smallSubtitleHtml;
  else if(smallSubtitleHtml)
	  subtitleHtml = subtitleHtml + smallSubtitleHtml;

  if(subtitleHtml)
  {
    var titleHtml = title.html();
    title.html(titleHtml + " " + subtitleHtml + "");
  }

  title.addClass("page-header");
}

function adaptSidebar()
{
  var oldSidebar = $(".content-root > div.sidebar");
  var newSidebar = $(".sidebar-root");

  newSidebar.html(oldSidebar.html());

  oldSidebar.remove();

  $("div.toc > h3 > a").each(function(){
    tocHeader = $(this);
    tocHeader.replaceWith(tocHeader.html());
  });

  $(".toc > ul").addClass("list-unstyled");

  var toc = $("div.toc");
  toc.addClass("panel panel-default");
  toc.html("
" + toc.html() +  "
");
}

function getFilename()
{
  var fullUrl = window.location.pathname;
  fullUrl = fullUrl.replace('\\', '/');
  filename = fullUrl.split('/').pop();
  return filename;
}

function isFile(filename)
{
  return getFilename() == filename;
}

function adaptWarningOrNote(element, panelClass, docStyleClass)
{
  $("p > b:contains('"+element+":')").each(function() {
    var element = $(this);

    p = element.parent();

    element.addClass(docStyleClass + "-label");

    p.replaceWith("

"+p.html()+"

");
  });
}

function adaptWarning()
{
  adaptWarningOrNote("Warning", "panel-warning", "doc-style-warning");
}

function adaptNote()
{
  adaptWarningOrNote("Note", "panel-info", "doc-style-note");
}

function _addPager(naviArea)
{
  var prevPageElement = $(naviArea+" > .prevPage");
  var nextPageElement = $(naviArea+" > .nextPage");
  var navi = $(naviArea);

  if(navi && (prevPageElement || nextPageElement))
  {
    var prev = "";
    var next = "";

    var prevText = prevPageElement.text();
    var nextText = nextPageElement.text();

    if(prevText)
    {
      var text = prevText;
      var href = prevPageElement.attr("href");
      prev = "
← "+text+"
";
    }
    if(nextText)
    {
      var text = nextText;
      var href = nextPageElement.attr("href");
      next = "
"+text+" →
";
    }

    navi.replaceWith("
"+prev+next+"
");
  }
}

function addPager()
{
  _addPager(".footerNavi");
  //_addPager(".headerNavi");
  $(".headerNavi").remove();
}

function _adaptOverviewTables(selector)
{
  $("div.table > " + selector).each(function(){
    var table = $(this);
    var div = table.parent();

    div.attr("class", "panel panel-default");
    table.attr("class", "table table-bordered");
  });
}

function adaptOverviewTables()
{
  _adaptOverviewTables("table.annotated");
  _adaptOverviewTables("table.alignedsummary");
}

function _adaptOverviewLists(selector)
{
  var ul = $(selector);
  ul.wrap("

");
  ul.addClass("list-group");
  ul.children().addClass("list-group-item");
}

function adaptOverviewLists()
{
  _adaptOverviewLists("h2#properties + ul");
}

function adaptLinkToMemberPage(text)
{
  var linkToAllMembers = $(".content-root > ul > li > a:contains('"+text+"')");
  linkToAllMembers.parent().parent().addClass("list-unstyled");
  linkToAllMembers.html("» "+linkToAllMembers.html());
}

function adaptLinkToMembers()
{
  adaptLinkToMemberPage("List of all members");
}

function makeLiUnstyled(text)
{
  var li = $(".content-root > ul > li:contains('"+text+"')");
  li.parent().addClass("list-unstyled");
}

function adaptTablesInPanel(parentClass, tableclass)
{
  $("div."+parentClass+" > div.panel > div.panel-body > div.table > table"+tableclass).each(function(){
    var table = $(this);
    table.addClass("table");
    var div_table = table.parent();
    div_table.parent().after(div_table.html());
    div_table.remove();
  });
}

function adaptNamespaceTypeMemberDetails(parentClass)
{
  // Make it a panel
  $("div."+parentClass).each(function(){
    var root = $(this);

    var oldHtml = root.html();
    var newHtml = "";

    var prevIndex = 0;
    var newIndex = -1;

    while((newIndex = oldHtml.indexOf("<h3", prevIndex+1)) != -1)
    {
      newHtml = newHtml + oldHtml.substring(prevIndex, newIndex)
      if(prevIndex != 0)
        newHtml = newHtml + "
\n
\n";
      newHtml = newHtml + "
\n";
      newHtml = newHtml + "
\n";

      prevIndex = newIndex;
    }

    newHtml = newHtml + oldHtml.substring(prevIndex, oldHtml.length);
    if(prevIndex != 0)
      newHtml = newHtml + "
\n
\n";

    prevIndex = 0;
    newIndex = -1;

    oldHtml = newHtml;
    newHtml = "";

    while((newIndex = oldHtml.indexOf("
", prevIndex+1)) != -1)
    {
      newIndex += 5;
      newHtml = newHtml + oldHtml.substring(prevIndex, newIndex)
      newHtml = newHtml + "\n
\n";
      newHtml = newHtml + "
\n";

      prevIndex = newIndex;
    }

    newHtml = newHtml + oldHtml.substring(prevIndex, oldHtml.length);

    root.html(newHtml);
  });

  // Make the panel heading small by removing the h3 tag
  $("div."+parentClass + " > div.panel > div.panel-heading > h3").each(function(){
    $(this).replaceWith($(this).html());
  });
}

function adaptMemberDetails()
{
  adaptNamespaceTypeMemberDetails("classes");
  adaptNamespaceTypeMemberDetails("types");
  adaptNamespaceTypeMemberDetails("func");
  adaptNamespaceTypeMemberDetails("vars");
  adaptNamespaceTypeMemberDetails("prop");
  adaptNamespaceTypeMemberDetails("macros");
  adaptNamespaceTypeMemberDetails("relnonmem");

  if(exists("div.content-root > h1.title:contains(Obsolete)"))
    adaptNamespaceTypeMemberDetails("content-root");

  adaptTablesInPanel("types", ".valuelist");
}

function adaptLabel(label)
{
  $("code:contains('["+label+"]')").each(function(){
    var code = $(this);
    var parent = code.parent();
    code.remove();

    var rightAligned = "style='float:right'";
    var labelHtml = ""+label+"";
    parent.html(parent.html() + labelHtml);
  });
}

function adaptLabels()
{
  adaptLabel("protected");
  adaptLabel("static");
  adaptLabel("static protected");
  adaptLabel("signal");
  adaptLabel("slot");
  adaptLabel("protected slot");
  adaptLabel("virtual");
  adaptLabel("virtual protected");
  adaptLabel("pure virtual");
  adaptLabel("pure virtual protected");
  adaptLabel("override");
  adaptLabel("final");
}

function adaptVersion()
{
  var version = $("div.content-root > p.lead + div.panel.panel-default > table.table > tbody > tr >  td.memItemLeft:contains('Since:') + td.memItemRight:contains('Qt')");

  version.each(function(){
    var v = $(this);
    var t = v.text();
    t = t.replace('Qt', '');
    t = t.trim();

    v.text(t);
    v.addClass("SinceVersion");
  });

  version = $("div.panel-body >  p:contains('This function was introduced in  Qt')");

  version.each(function(){
    var v = $(this);
    var t = v.text();
    t = t.replace('Qt', '');
    t = t.trim();

    v.text(t);
    v.addClass("SinceVersion");
  });

}

function adaptChapterAndPart()
{
  var h0 = $('h0');

  h0.replaceWith('
' + h0.text() + '
');
}

function adaptGenericTables()
{
  var tables = $('table.generic');

  tables.addClass('table');
  tables.addClass('table-striped');
}

function adaptListOfAllMembersTables()
{
  table = $("div.content-root > h1.title + p.lead + div.table > table.propsummary");

  table.addClass("table");
  table.addClass("table-bordered");
}

$(document).ready(function() {
  adaptBreadcrums();
  if(isFile("index.html"))
  {
    removeTitle();
  }else
  {
    adaptTitle();
    adaptBrief();
    adaptSidebar();
  }

  adaptWarning();
  adaptNote();
  addPager();

  adaptOverviewTables();
  adaptOverviewLists();
  adaptLinkToMembers();
  makeLiUnstyled("functions inherited from");
  makeLiUnstyled("member inherited from");

  adaptMemberDetails();
  adaptLabels();

  adaptVersion();

  adaptChapterAndPart();

  adaptGenericTables();
  adaptListOfAllMembersTables();
});
<|endoftext|>