<commit_before>/*
 * This class is used to retrive data from webservice, mutaton and cna servlets
 * including all date and date attributes
 */

var StudyViewProxy = (function() {

    var parObject = {},
        sampleIdStr = '',
        patientIdStr = '',
        samplePatientMapping = {},
        ajaxParameters = {},
        obtainDataObject = [];

    obtainDataObject['attr'] = [];
    obtainDataObject['arr'] = [];

    function initLocalParameters(callBack){
        parObject = jQuery.extend(true, {}, StudyViewParams.params);
        patientIdStr = parObject.caseIds.join(' ');
        $.ajax({
            type: "POST",
            url: "webservice.do",
            data: {
                cmd: "getPatientSampleMapping",
                format: "json",
                cancer_study_id: parObject.studyId,
                case_set_id: parObject.caseSetId}
        }).done(function(d){
            var sampleIds = [],
                patientIds = [];
            parObject.samplePatientMapping = d;

            for(var key in d) {
                patientIds.push(key);
                for(var i = 0; i< d[key].length; i++){
                    if(sampleIds.indexOf(d[key][i]) === -1) {
                        sampleIds.push(d[key][i]);
                        samplePatientMapping[d[key][i]] = key;
                    }
                }
            }
            StudyViewParams.params.sampleIds = sampleIds;
            StudyViewParams.params.patientIds = patientIds;
            sampleIdStr = sampleIds.join(' ');
            callBack();
        });
    }

    function initAjaxParameters(){
        ajaxParameters = {
            webserviceData: {
                cmd: "getClinicalData",
                format: "json",
                cancer_study_id: parObject.studyId,
                case_set_id: parObject.caseSetId
            },
            clinicalAttributesData: {
                cancer_study_id: parObject.studyId,
                case_list: sampleIdStr
            },
            mutationsData: {
                cmd: "count_mutations",
                cases_ids: sampleIdStr,
                mutation_profile: parObject.mutationProfileId
            },
            cnaData: {
                cmd: "get_cna_fraction",
                case_ids: patientIdStr,
                cancer_study_id: parObject.studyId
            },
            mutatedGenesData: {
                cmd: 'get_smg',
                mutation_profile: parObject.mutationProfileId
            },
            gisticData: {
                selected_cancer_type: parObject.studyId
            }
        };
    }

    function getDataFunc(callbackFunc){
         $.when(
                $.ajax({type: "POST", url: "webservice.do", data: ajaxParameters.webserviceData}),
                $.ajax({type: "POST", url: "mutations.json", data: ajaxParameters.mutationsData}),
                $.ajax({type: "POST", url: "cna.json", data: ajaxParameters.cnaData}),
                $.ajax({type: "POST", url: "mutations.json", data: ajaxParameters.mutatedGenesData}),
                $.ajax({type: "POST", url: "Gistic.json", data: ajaxParameters.gisticData}))
            .done(function(a1, a2, a3, a4, a5){
                var _dataAttrMapArr = {}, //Map attrbute value with attribute name for each datum
                    _keyNumMapping = {},
                    _data = a1[0]['data'],
                    _dataAttrOfa1 = a1[0]['attributes'],
                    _dataLength = _data.length,
                    _sampleIds = Object.keys(samplePatientMapping);

                //Reorganize data into wanted format datum[ caseID ][ Attribute Name ] = Attribute Value
                //The original data structure is { attr_id: , attr_va: , sample}
                for(var i = 0; i < _dataLength; i++){
                    if(_data[i]["sample"] in _dataAttrMapArr){
                        _dataAttrMapArr[_data[i]["sample"]][_data[i]["attr_id"].toString().toUpperCase()] = _data[i]["attr_val"];
                    }else{
                        _dataAttrMapArr[_data[i]["sample"]] = [];
                        _dataAttrMapArr[_data[i]["sample"]][_data[i]["attr_id"].toString().toUpperCase()] = _data[i]["attr_val"];
                    }
                    if(_sampleIds.indexOf(_data[i]["sample"]) === -1) {
                        console.log('Unknown sample exists in clincial data.');
                    }
                }

                //Initial data array, not all of cases has MUTAION COUND OR COPY NUMBER ALTERATIONS.
                for(var j = 0; j <  _sampleIds.length; j++){
                    var _caseDatum = {};
                    _caseDatum["CASE_ID"] = _sampleIds[j];
                    _caseDatum["PATIENT_ID"] = samplePatientMapping[_sampleIds[j]];
                    _caseDatum["MUTATION_COUNT"] = "NA";
                    _caseDatum["COPY_NUMBER_ALTERATIONS"] = "NA";
                    _keyNumMapping[_sampleIds[j]] = j;
                    $.each(_dataAttrOfa1,function(key,value){
                        value['attr_id'] = value['attr_id'].toUpperCase();
                        _dataAttrOfa1[key]['attr_id'] = value['attr_id'];
                        if(value['attr_id'] !== 'CASE_ID'){
                            _caseDatum[value['attr_id']] = "NA";
                        }
                    });
                    obtainDataObject['arr'].push(_caseDatum);
                }

                $.each(_dataAttrOfa1,function(key,value){
                    if(!value['display_name']){
                        value['display_name'] = value['attr_id'];
                    }

                    value['display_name'] = toPascalCase(value['display_name']);
                });

                for(var key in _dataAttrMapArr){
                    for (var i = 0 ; i < _dataAttrOfa1.length ; i++){
                        var tmpValue = _dataAttrMapArr[key][_dataAttrOfa1[i]['attr_id']];
                        if(tmpValue === '' || tmpValue === undefined || tmpValue === 'na' || tmpValue === 'NA'){
                            tmpValue = 'NA';
                        }
                        obtainDataObject['arr'][_keyNumMapping[key]][_dataAttrOfa1[i]['attr_id']] = tmpValue;
                    }

                }

                obtainDataObject['attr'] = _dataAttrOfa1;

                //Filter extra data
                var filteredA2 = removeExtraData(_sampleIds,a2[0]);
                var filteredA3 = removeExtraData(_sampleIds,a3[0]);

                //Add new attribute MUTATIOIN COUNT for each case if have any
                if(Object.keys(filteredA2).length !== 0){
                    var _newAttr = {};
                    _newAttr.attr_id = 'MUTATION_COUNT';
                    _newAttr.display_name = 'Mutation Count';
                    _newAttr.description = 'Mutation Count';
                    _newAttr.datatype = 'NUMBER';

                    jQuery.each(filteredA2, function(i,val){
                        if(val === undefined)
                            val = 'NA';
                        obtainDataObject['arr'][_keyNumMapping[i]]['MUTATION_COUNT'] = val;
                    });
                    obtainDataObject['attr'].push(_newAttr);
                }else {
                    var cnaLength = obtainDataObject['arr'].length;
                    for(var i = 0; i < cnaLength; i++) {
                        if(obtainDataObject['arr'][i].hasOwnProperty('MUTATION_COUNT')) {
                            delete obtainDataObject['arr'][i]['MUTATION_COUNT'];
                        }
                    }
                }

                //Add new attribute COPY NUMBER ALTERATIONS for each case if have any
                if(Object.keys(filteredA3).length !== 0){
                    var _newAttri = {};
                    _newAttri.attr_id = 'COPY_NUMBER_ALTERATIONS';
                    _newAttri.display_name = 'Copy Number Alterations';
                    _newAttri.description = 'Copy Number Alterations';
                    _newAttri.datatype = 'NUMBER';

                    jQuery.each(filteredA3, function(i,val){
                        if(val === undefined){
                            val = 'NA';
                        }
                        obtainDataObject['arr'][_keyNumMapping[i]]['COPY_NUMBER_ALTERATIONS'] = val;
                    });
                    obtainDataObject['attr'].push(_newAttri);
                }else {
                    var cnaLength = obtainDataObject['arr'].length;
                    for(var i = 0; i < cnaLength; i++) {
                        if(obtainDataObject['arr'][i].hasOwnProperty('COPY_NUMBER_ALTERATIONS')) {
                            delete obtainDataObject['arr'][i]['COPY_NUMBER_ALTERATIONS'];
                        }
                    }
                }

                //Attribute CASE_ID will be treated as identifier in Study View
                //If the case data does not have CASE_ID column, new CASE_ID attribute
                //should be created.d
                var caseidExist = false;
                var patientidExist = false;
                for(var i=0 ; i<obtainDataObject['attr'].length; i++){
                    if(obtainDataObject['attr'][i].attr_id === 'CASE_ID'){
                        caseidExist = true;
                    }
                    if(obtainDataObject['attr'][i].attr_id === 'PATIENT_ID'){
                        patientidExist = true;
                    }
                }
                if(!caseidExist){
                    obtainDataObject['attr'].push({
                        attr_id: 'CASE_ID',
                        display_name: 'SAMPLE ID',
                        description: 'Sample Identifier',
                        datatype: 'STRING'
                    });
                }
                obtainDataObject['mutatedGenes'] = a4[0];
                obtainDataObject['cna'] = a5[0];

                if (!patientidExist) {
                    obtainDataObject['attr'].push({
                        attr_id: 'PATIENT_ID',
                        display_name: 'PATIENT ID',
                        description: 'Patient Identifier',
                        datatype: 'STRING'
                    });
               }

                callbackFunc(obtainDataObject);
            });
    };

    function getPatientIdsBySampleIds(_sampleIds) {
        var _patientIds = [];

        for(var i = 0, _sampleIdsL = _sampleIds.length; i < _sampleIdsL; i++) {
            if(_patientIds.indexOf(_sampleIds[i]) === -1) {
                _patientIds.push(samplePatientMapping[_sampleIds[i]]);
            }
        }
        return _patientIds;
    }

    //Webservice may retrun extra cases including there data
    //This function is designed to elimate data based on case id
    //which not inlcuded in globle caseIds Array
    function removeExtraData(_caseIds,_data){
        var _newData = {},
            _hasValue = false;
        for(var i=0; i< _caseIds.length ; i++){
            _newData[_caseIds[i]] = _data[_caseIds[i]];
            if(_data[_caseIds[i]] !== undefined){
                _hasValue = true;
            }
        }
        if(_hasValue) {
            return _newData;
        }else {
            return [];
        }
    }

    function toPascalCase(str) {
        var arr = str.split(/\s|_/);
//        for(var i=0,l=arr.length; i<l; i++) {
//            arr[i] = arr[i].substr(0,1).toUpperCase() +
//                     (arr[i].length > 1 ? arr[i].substr(1).toLowerCase() : "");
//        }
        return arr.join(" ");
    }

    return {
        init: function(callbackFunc){
            initLocalParameters(function(){
                initAjaxParameters();
                getDataFunc(callbackFunc);
            });
        },

        getArrData: function(){ return obtainDataObject['arr'];},
        getAttrData: function(){ return obtainDataObject['attr'];},
        getMutatedGenesData: function(){ return obtainDataObject['mutatedGenes'];},
        getCNAData: function(){return obtainDataObject['cna'];},
        getSampleidToPatientidMap: function(){return obtainDataObject['sampleidToPatientidMap'];},
        getPatientIdsBySampleIds: getPatientIdsBySampleIds
    };
}());<commit_msg>uniq patient id<commit_after>/*
 * This class is used to retrive data from webservice, mutaton and cna servlets
 * including all date and date attributes
 */

var StudyViewProxy = (function() {

    var parObject = {},
        sampleIdStr = '',
        patientIdStr = '',
        samplePatientMapping = {},
        ajaxParameters = {},
        obtainDataObject = [];

    obtainDataObject['attr'] = [];
    obtainDataObject['arr'] = [];

    function initLocalParameters(callBack){
        parObject = jQuery.extend(true, {}, StudyViewParams.params);
        patientIdStr = parObject.caseIds.join(' ');
        $.ajax({
            type: "POST",
            url: "webservice.do",
            data: {
                cmd: "getPatientSampleMapping",
                format: "json",
                cancer_study_id: parObject.studyId,
                case_set_id: parObject.caseSetId}
        }).done(function(d){
            var sampleIds = [],
                patientIds = [];
            parObject.samplePatientMapping = d;

            for(var key in d) {
                patientIds.push(key);
                for(var i = 0; i< d[key].length; i++){
                    if(sampleIds.indexOf(d[key][i]) === -1) {
                        sampleIds.push(d[key][i]);
                        samplePatientMapping[d[key][i]] = key;
                    }
                }
            }
            StudyViewParams.params.sampleIds = sampleIds;
            StudyViewParams.params.patientIds = patientIds;
            sampleIdStr = sampleIds.join(' ');
            callBack();
        });
    }

    function initAjaxParameters(){
        ajaxParameters = {
            webserviceData: {
                cmd: "getClinicalData",
                format: "json",
                cancer_study_id: parObject.studyId,
                case_set_id: parObject.caseSetId
            },
            clinicalAttributesData: {
                cancer_study_id: parObject.studyId,
                case_list: sampleIdStr
            },
            mutationsData: {
                cmd: "count_mutations",
                cases_ids: sampleIdStr,
                mutation_profile: parObject.mutationProfileId
            },
            cnaData: {
                cmd: "get_cna_fraction",
                case_ids: patientIdStr,
                cancer_study_id: parObject.studyId
            },
            mutatedGenesData: {
                cmd: 'get_smg',
                mutation_profile: parObject.mutationProfileId
            },
            gisticData: {
                selected_cancer_type: parObject.studyId
            }
        };
    }

    function getDataFunc(callbackFunc){
         $.when(
                $.ajax({type: "POST", url: "webservice.do", data: ajaxParameters.webserviceData}),
                $.ajax({type: "POST", url: "mutations.json", data: ajaxParameters.mutationsData}),
                $.ajax({type: "POST", url: "cna.json", data: ajaxParameters.cnaData}),
                $.ajax({type: "POST", url: "mutations.json", data: ajaxParameters.mutatedGenesData}),
                $.ajax({type: "POST", url: "Gistic.json", data: ajaxParameters.gisticData}))
            .done(function(a1, a2, a3, a4, a5){
                var _dataAttrMapArr = {}, //Map attrbute value with attribute name for each datum
                    _keyNumMapping = {},
                    _data = a1[0]['data'],
                    _dataAttrOfa1 = a1[0]['attributes'],
                    _dataLength = _data.length,
                    _sampleIds = Object.keys(samplePatientMapping);

                //Reorganize data into wanted format datum[ caseID ][ Attribute Name ] = Attribute Value
                //The original data structure is { attr_id: , attr_va: , sample}
                for(var i = 0; i < _dataLength; i++){
                    if(_data[i]["sample"] in _dataAttrMapArr){
                        _dataAttrMapArr[_data[i]["sample"]][_data[i]["attr_id"].toString().toUpperCase()] = _data[i]["attr_val"];
                    }else{
                        _dataAttrMapArr[_data[i]["sample"]] = [];
                        _dataAttrMapArr[_data[i]["sample"]][_data[i]["attr_id"].toString().toUpperCase()] = _data[i]["attr_val"];
                    }
                    if(_sampleIds.indexOf(_data[i]["sample"]) === -1) {
                        console.log('Unknown sample exists in clincial data.');
                    }
                }

                //Initial data array, not all of cases has MUTAION COUND OR COPY NUMBER ALTERATIONS.
                for(var j = 0; j <  _sampleIds.length; j++){
                    var _caseDatum = {};
                    _caseDatum["CASE_ID"] = _sampleIds[j];
                    _caseDatum["PATIENT_ID"] = samplePatientMapping[_sampleIds[j]];
                    _caseDatum["MUTATION_COUNT"] = "NA";
                    _caseDatum["COPY_NUMBER_ALTERATIONS"] = "NA";
                    _keyNumMapping[_sampleIds[j]] = j;
                    $.each(_dataAttrOfa1,function(key,value){
                        value['attr_id'] = value['attr_id'].toUpperCase();
                        _dataAttrOfa1[key]['attr_id'] = value['attr_id'];
                        if(value['attr_id'] !== 'CASE_ID'){
                            _caseDatum[value['attr_id']] = "NA";
                        }
                    });
                    obtainDataObject['arr'].push(_caseDatum);
                }

                $.each(_dataAttrOfa1,function(key,value){
                    if(!value['display_name']){
                        value['display_name'] = value['attr_id'];
                    }

                    value['display_name'] = toPascalCase(value['display_name']);
                });

                for(var key in _dataAttrMapArr){
                    for (var i = 0 ; i < _dataAttrOfa1.length ; i++){
                        var tmpValue = _dataAttrMapArr[key][_dataAttrOfa1[i]['attr_id']];
                        if(tmpValue === '' || tmpValue === undefined || tmpValue === 'na' || tmpValue === 'NA'){
                            tmpValue = 'NA';
                        }
                        obtainDataObject['arr'][_keyNumMapping[key]][_dataAttrOfa1[i]['attr_id']] = tmpValue;
                    }

                }

                obtainDataObject['attr'] = _dataAttrOfa1;

                //Filter extra data
                var filteredA2 = removeExtraData(_sampleIds,a2[0]);
                var filteredA3 = removeExtraData(_sampleIds,a3[0]);

                //Add new attribute MUTATIOIN COUNT for each case if have any
                if(Object.keys(filteredA2).length !== 0){
                    var _newAttr = {};
                    _newAttr.attr_id = 'MUTATION_COUNT';
                    _newAttr.display_name = 'Mutation Count';
                    _newAttr.description = 'Mutation Count';
                    _newAttr.datatype = 'NUMBER';

                    jQuery.each(filteredA2, function(i,val){
                        if(val === undefined)
                            val = 'NA';
                        obtainDataObject['arr'][_keyNumMapping[i]]['MUTATION_COUNT'] = val;
                    });
                    obtainDataObject['attr'].push(_newAttr);
                }else {
                    var cnaLength = obtainDataObject['arr'].length;
                    for(var i = 0; i < cnaLength; i++) {
                        if(obtainDataObject['arr'][i].hasOwnProperty('MUTATION_COUNT')) {
                            delete obtainDataObject['arr'][i]['MUTATION_COUNT'];
                        }
                    }
                }

                //Add new attribute COPY NUMBER ALTERATIONS for each case if have any
                if(Object.keys(filteredA3).length !== 0){
                    var _newAttri = {};
                    _newAttri.attr_id = 'COPY_NUMBER_ALTERATIONS';
                    _newAttri.display_name = 'Copy Number Alterations';
                    _newAttri.description = 'Copy Number Alterations';
                    _newAttri.datatype = 'NUMBER';

                    jQuery.each(filteredA3, function(i,val){
                        if(val === undefined){
                            val = 'NA';
                        }
                        obtainDataObject['arr'][_keyNumMapping[i]]['COPY_NUMBER_ALTERATIONS'] = val;
                    });
                    obtainDataObject['attr'].push(_newAttri);
                }else {
                    var cnaLength = obtainDataObject['arr'].length;
                    for(var i = 0; i < cnaLength; i++) {
                        if(obtainDataObject['arr'][i].hasOwnProperty('COPY_NUMBER_ALTERATIONS')) {
                            delete obtainDataObject['arr'][i]['COPY_NUMBER_ALTERATIONS'];
                        }
                    }
                }

                //Attribute CASE_ID will be treated as identifier in Study View
                //If the case data does not have CASE_ID column, new CASE_ID attribute
                //should be created.d
                var caseidExist = false;
                var patientidExist = false;
                for(var i=0 ; i<obtainDataObject['attr'].length; i++){
                    if(obtainDataObject['attr'][i].attr_id === 'CASE_ID'){
                        caseidExist = true;
                    }
                    if(obtainDataObject['attr'][i].attr_id === 'PATIENT_ID'){
                        patientidExist = true;
                    }
                }
                if(!caseidExist){
                    obtainDataObject['attr'].push({
                        attr_id: 'CASE_ID',
                        display_name: 'SAMPLE ID',
                        description: 'Sample Identifier',
                        datatype: 'STRING'
                    });
                }
                obtainDataObject['mutatedGenes'] = a4[0];
                obtainDataObject['cna'] = a5[0];

                if (!patientidExist) {
                    obtainDataObject['attr'].push({
                        attr_id: 'PATIENT_ID',
                        display_name: 'PATIENT ID',
                        description: 'Patient Identifier',
                        datatype: 'STRING'
                    });
               }

                callbackFunc(obtainDataObject);
            });
    };

    function getPatientIdsBySampleIds(_sampleIds) {
        var _patientIds = [];

        for(var i = 0, _sampleIdsL = _sampleIds.length; i < _sampleIdsL; i++) {
            if(_patientIds.indexOf(_sampleIds[i]) === -1) {
                _patientIds.push(samplePatientMapping[_sampleIds[i]]);
            }
        }
        return _.uniq(_patientIds);
    }

    //Webservice may retrun extra cases including there data
    //This function is designed to elimate data based on case id
    //which not inlcuded in globle caseIds Array
    function removeExtraData(_caseIds,_data){
        var _newData = {},
            _hasValue = false;
        for(var i=0; i< _caseIds.length ; i++){
            _newData[_caseIds[i]] = _data[_caseIds[i]];
            if(_data[_caseIds[i]] !== undefined){
                _hasValue = true;
            }
        }
        if(_hasValue) {
            return _newData;
        }else {
            return [];
        }
    }

    function toPascalCase(str) {
        var arr = str.split(/\s|_/);
//        for(var i=0,l=arr.length; i<l; i++) {
//            arr[i] = arr[i].substr(0,1).toUpperCase() +
//                     (arr[i].length > 1 ? arr[i].substr(1).toLowerCase() : "");
//        }
        return arr.join(" ");
    }

    return {
        init: function(callbackFunc){
            initLocalParameters(function(){
                initAjaxParameters();
                getDataFunc(callbackFunc);
            });
        },

        getArrData: function(){ return obtainDataObject['arr'];},
        getAttrData: function(){ return obtainDataObject['attr'];},
        getMutatedGenesData: function(){ return obtainDataObject['mutatedGenes'];},
        getCNAData: function(){return obtainDataObject['cna'];},
        getSampleidToPatientidMap: function(){return obtainDataObject['sampleidToPatientidMap'];},
        getPatientIdsBySampleIds: getPatientIdsBySampleIds
    };
}());<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Austin Markiewicz. All rights reserved.
 *
 * 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.
 */

define(function (require, exports, module) {
    'use strict';

    module.exports = {
        NAME: 'brackets-macromanager',
        defaultPreferences: {
            enabled: true
        }
    };
});<commit_msg>Delete config.js<commit_after><|endoftext|>


<commit_before>define("ace/snippets/abc",["require","exports","module"],function(e,t,n){"use strict";t.snippetText='\nsnippet zupfnoter.print\n	%%%%hn.print {"startpos": ${1:pos_y}, "t":"${2:title}", "v":[${3:voices}], "s":[[${4:syncvoices}1,2]], "f":[${5:flowlines}],  "sf":[${6:subflowlines}], "j":[${7:jumplines}]}\n\nsnippet zupfnoter.note\n	%%%%hn.note {"pos": [${1:pos_x},${2:pos_y}], "text": "${3:text}", "style": "${4:style}"}\n\nsnippet zupfnoter.annotation\n	%%%%hn.annotation {"id": "${1:id}", "pos": [${2:pos}], "text": "${3:text}"}\n\nsnippet zupfnoter.lyrics\n	%%%%hn.lyrics {"pos": [${1:x_pos},${2:y_pos}]}\n\nsnippet zupfnoter.legend\n	%%%%hn.legend {"pos": [${1:x_pos},${2:y_pos}]}\n\n\n\nsnippet zupfnoter.target\n	"^:${1:target}"\n\nsnippet zupfnoter.goto\n	"^@${1:target}@${2:distance}"\n\nsnippet zupfnoter.annotationref\n	"^#${1:target}"\n\nsnippet zupfnoter.annotation\n	"^!${1:text}@${2:x_offset},${3:y_offset}"\n\n\n',t.scope="abc"})<commit_msg>Update public/libs/bower_components/ace-builds/src-min/snippets/abc.js<commit_after><|endoftext|>


<commit_before>'use strict';

// Members controller
angular.module('members').controller('MembersController', ['$scope', '$stateParams', '$location', 'Authentication', 'Members', 'Participants',
	function($scope, $stateParams, $location, Authentication, Members, Participants) {
		$scope.authentication = Authentication;

		// Create new Member
		$scope.create = function() {

			var clearFields = function(Participant) {
				$scope.member.firstName = '';
				$scope.member.lastName = '';
				$scope.member.phone = '';
				$scope.member.email = '';
				$scope.member.identity = '';
				$scope.member.affiliation = '';
				$scope.member.address = '';
				$scope.member.shirtSize = '';
				$scope.member.shirtReceived = '';
				$scope.member.talent = '';
				$scope.member.placeOfWorship = '';
				$scope.member.recruitment = '';
				$scope.member.communityNetworks[0] = '';
				$scope.member.communityNetworks[1] = '';
				$scope.member.communityNetworks[2] = '';
				$scope.member.extraGroups[0] = '';
				$scope.member.extraGroups[1] = '';
				$scope.member.extraGroups[2] = '';
				$scope.member.otherNetworks[0] = '';
				$scope.member.otherNetworks[1] = '';
				$scope.member.otherNetworks[2] = '';
			};

			// Create new Member
			var member = $scope.member;

			if(member && member._id) {
				member.$update(function(response) {
					$location.path('members/' + response._id);
					clearFields(response);
				}, function(errorResponse) {
				    $scope.error = errorResponse.data.message;
				});

			} else {
				// Redirect after save
				member.$save(function(response) {
					clearFields(response);
				}, function(errorResponse) {
					$scope.error = errorResponse.data.message;
				});

			}
		};

		// Remove existing Member
		$scope.remove = function(member) {
			if ( member ) {
				member.$remove();

				for (var i in $scope.members) {
					if ($scope .members [i] === member) {
						$scope.members.splice(i, 1);
					}
				}
			} else {
				$scope.member.$remove(function() {
					$location.path('members');
				});
			}
		};

		// Update existing Member
		$scope.update = function() {
			var member = $scope.member;

			member.$update(function() {
				$location.path('members/' + member._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Members
		$scope.find = function() {
			$scope.members = Members.query();
		};

		// Find existing participants
		$scope.findParticipants = function(name) {
			return Participants.query({name: name}).$promise;
		};

		// Find existing Member
		$scope.findOne = function() {
			$scope.member = Members.get({
				memberId: $stateParams.memberId
			});
		};

		// Initialize a new Member
		$scope.newMember = function() {
			$scope.member = new Members({
				communityNetworks: [],
				extraGroups: [],
				otherNetworks: []
			});
		};

		// A member is selected from the typehead search
		$scope.selectMember = function(participant) {
			$scope.member = new Members(participant);
			$scope.member.communityNetworks = [];
			$scope.member.extraGroups = [];
			$scope.member.otherNetworks = [];
		};
	}
]);<commit_msg>Readded redirect after new member is saved<commit_after>'use strict';

// Members controller
angular.module('members').controller('MembersController', ['$scope', '$stateParams', '$location', 'Authentication', 'Members', 'Participants',
	function($scope, $stateParams, $location, Authentication, Members, Participants) {
		$scope.authentication = Authentication;

		// Create new Member
		$scope.create = function() {

			var clearFields = function(Participant) {
				$scope.member.firstName = '';
				$scope.member.lastName = '';
				$scope.member.phone = '';
				$scope.member.email = '';
				$scope.member.identity = '';
				$scope.member.affiliation = '';
				$scope.member.address = '';
				$scope.member.shirtSize = '';
				$scope.member.shirtReceived = '';
				$scope.member.talent = '';
				$scope.member.placeOfWorship = '';
				$scope.member.recruitment = '';
				$scope.member.communityNetworks[0] = '';
				$scope.member.communityNetworks[1] = '';
				$scope.member.communityNetworks[2] = '';
				$scope.member.extraGroups[0] = '';
				$scope.member.extraGroups[1] = '';
				$scope.member.extraGroups[2] = '';
				$scope.member.otherNetworks[0] = '';
				$scope.member.otherNetworks[1] = '';
				$scope.member.otherNetworks[2] = '';
			};

			// Create new Member
			var member = $scope.member;

			if(member && member._id) {
				member.$update(function(response) {
					$location.path('members/' + response._id);
					clearFields(response);
				}, function(errorResponse) {
				    $scope.error = errorResponse.data.message;
				});

			} else {
				// Redirect after save
				member.$save(function(response) {
					$location.path('members/' + response._id);
					clearFields(response);
				}, function(errorResponse) {
					$scope.error = errorResponse.data.message;
				});

			}
		};

		// Remove existing Member
		$scope.remove = function(member) {
			if ( member ) {
				member.$remove();

				for (var i in $scope.members) {
					if ($scope .members [i] === member) {
						$scope.members.splice(i, 1);
					}
				}
			} else {
				$scope.member.$remove(function() {
					$location.path('members');
				});
			}
		};

		// Update existing Member
		$scope.update = function() {
			var member = $scope.member;

			member.$update(function() {
				$location.path('members/' + member._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Members
		$scope.find = function() {
			$scope.members = Members.query();
		};

		// Find existing participants
		$scope.findParticipants = function(name) {
			return Participants.query({name: name}).$promise;
		};

		// Find existing Member
		$scope.findOne = function() {
			$scope.member = Members.get({
				memberId: $stateParams.memberId
			});
		};

		// Initialize a new Member
		$scope.newMember = function() {
			$scope.member = new Members({
				communityNetworks: [],
				extraGroups: [],
				otherNetworks: []
			});
		};

		// A member is selected from the typehead search
		$scope.selectMember = function(participant) {
			$scope.member = new Members(participant);
			$scope.member.communityNetworks = [];
			$scope.member.extraGroups = [];
			$scope.member.otherNetworks = [];
		};
	}
]);<|endoftext|>


<commit_before>'use strict';

// Widgets controller
var app = angular.module('widgets');
app.controller('WidgetsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Widgets','$http',
	function($scope, $stateParams, $location, Authentication, Widgets, $http ) {
		$scope.authentication = Authentication;
        $scope.urlList = 'modules/widgets/views/list-widgets.client.view.html';
        $scope.urlView = 'modules/widgets/views/view-widget.client.view.html';
        $scope.urlEdit = 'modules/widgets/views/edit-widget.client.view.html';

		// Create new Widget
		$scope.create = function() {
			// Create new Widget object
			var widget = new Widgets ({
				name: this.name,
				title: this.title,
				seccion: this.seccion.nombre,
                attrs:{
                    value: this.title,
                    topico: this.topico,
                    idinfo: this.idinfo,
                    controlador: this.dispositivo.controlador
                }

			});

			// Redirect after save
			widget.$save(function(response) {
                $scope.cambiarPagina($scope.urlList);
				//$location.path('widgets/' + response._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

			// Clear form fields
			this.name = '';
			this.title = '';
			this.seccion = '';
            this.attrs= '';
            this.dispositivo= '';
		};

		// Remove existing Widget
		$scope.remove = function( widget ) {
			if ( widget ) { widget.$remove();

				for (var i in $scope.widgets ) {
					if ($scope.widgets [i] === widget ) {
						$scope.widgets.splice(i, 1);
					}
				}
			} else {
				$scope.widget.$remove(function() {
                    $scope.cambiarPagina($scope.urlList);
				});
			}
		};

		// Update existing Widget
		$scope.update = function() {
			var widget = $scope.widget ;

			widget.$update(function() {
                $scope.idView = widget._id;
                $scope.cambiarPagina($scope.urlView);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Widgets
		$scope.find = function() {
			$scope.widgets = Widgets.query();
		};

		// Find existing Widget
		$scope.findOne = function() {
			$scope.widget = Widgets.get({
				widgetId: $stateParams.widgetId
			});
		};
        //Cargar Widget Por ID
        $scope.cargarUno = function() {
            $scope.widget = Widgets.get({
                widgetId: $scope.idView
            });
        };

        //Creacion de un widgets
        $scope.topico = 'ard1/living/temp';
        $scope.idinfo = 'idloco';
        this.tipos = ['Hora', 'Temperatura', 'Sensor'];
        $scope.secciones = [];
        $http.get('/seccions').success(function(data){
            $scope.seccion = data[0];
            $scope.secciones = data;
        });
        $scope.dispositivos = [];
        $http.get('/dispositivos').success(function(data){
            $scope.dispositivo = data[0];
            $scope.dispositivos = data;
        });
	}
]);
app.controller('WidgetsInicioController',function ($scope, $interval, $http) {
    var widgetDefinitions = [
        {
            name: 'Hora',
            directive: 'wt-time',
            style: {
                width: '33%'
            }
        },
        {
            name: 'Numero Random',
            directive: 'wt-random',
            style: {
                width: '33%'
            }
        },
        {
            name: 'Temperatura',
            directive: 'widget-temperatura',
            attrs: {
                value: 'temperatura',
                topico: 'topico',
                idinfo: 'tempId',
                controlador: 'ard#'
            },
            style: {
                width: '34%'
            }
        }
    ];
    $http.get('/widgets/seccion/inicio').success(function(data){
        $scope.dashboardOptions.widgetDefinitions =data ;
        $scope.dashboardOptions.loadWidgets(data);
    });
    var defaultWidgets = [];

    $scope.dashboardOptions = {
        widgetButtons: true,
        widgetDefinitions: widgetDefinitions,
        defaultWidgets: defaultWidgets,
        hideWidgetClose: true,
        hideWidgetSettings: true
    };
});

<commit_msg>Pequeño fix de estilo<commit_after>'use strict';

// Widgets controller
var app = angular.module('widgets');
app.controller('WidgetsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Widgets','$http',
	function($scope, $stateParams, $location, Authentication, Widgets, $http ) {
		$scope.authentication = Authentication;
        $scope.urlList = 'modules/widgets/views/list-widgets.client.view.html';
        $scope.urlView = 'modules/widgets/views/view-widget.client.view.html';
        $scope.urlEdit = 'modules/widgets/views/edit-widget.client.view.html';

		// Create new Widget
		$scope.create = function() {
			// Create new Widget object
			var widget = new Widgets ({
				name: this.name,
				title: this.title,
				seccion: this.seccion.nombre,
                attrs:{
                    value: this.title,
                    topico: this.topico,
                    idinfo: this.idinfo,
                    controlador: this.dispositivo.controlador
                }

			});

			// Redirect after save
			widget.$save(function(response) {
                $scope.cambiarPagina($scope.urlList);
				//$location.path('widgets/' + response._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

			// Clear form fields
			this.name = '';
			this.title = '';
			this.seccion = '';
            this.attrs= '';
            this.dispositivo= '';
		};

		// Remove existing Widget
		$scope.remove = function( widget ) {
			if ( widget ) { widget.$remove();

				for (var i in $scope.widgets ) {
					if ($scope.widgets [i] === widget ) {
						$scope.widgets.splice(i, 1);
					}
				}
			} else {
				$scope.widget.$remove(function() {
                    $scope.cambiarPagina($scope.urlList);
				});
			}
		};

		// Update existing Widget
		$scope.update = function() {
			var widget = $scope.widget ;

			widget.$update(function() {
                $scope.idView = widget._id;
                $scope.cambiarPagina($scope.urlView);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Widgets
		$scope.find = function() {
			$scope.widgets = Widgets.query();
		};

		// Find existing Widget
		$scope.findOne = function() {
			$scope.widget = Widgets.get({
				widgetId: $stateParams.widgetId
			});
		};
        //Cargar Widget Por ID
        $scope.cargarUno = function() {
            $scope.widget = Widgets.get({
                widgetId: $scope.idView
            });
        };

        //Creacion de un widgets
        $scope.topico = 'ard1/living/temp';
        $scope.idinfo = 'idloco';
        this.tipos = ['Hora', 'Temperatura', 'Sensor'];
        $scope.secciones = [];
        $http.get('/seccions').success(function(data){
            $scope.seccion = data[0];
            $scope.secciones = data;
        });
        $scope.dispositivos = [];
        $http.get('/dispositivos').success(function(data){
            $scope.dispositivo = data[0];
            $scope.dispositivos = data;
        });
	}
]);
app.controller('WidgetsInicioController',function ($scope, $interval, $http) {
    var widgetDefinitions = [
        {
            name: 'Hora',
            directive: 'wt-time',
            style: {
                width: '32%'
            }
        },
        {
            name: 'Numero Random',
            directive: 'wt-random',
            style: {
                width: '32%'
            }
        },
        {
            name: 'Temperatura',
            directive: 'widget-temperatura',
            attrs: {
                value: 'temperatura',
                topico: 'topico',
                idinfo: 'tempId',
                controlador: 'ard#'
            },
            style: {
                width: '32%'
            }
        }
    ];
    $http.get('/widgets/seccion/inicio').success(function(data){
        $scope.dashboardOptions.widgetDefinitions =data ;
        $scope.dashboardOptions.loadWidgets(data);
    });
    var defaultWidgets = [];

    $scope.dashboardOptions = {
        widgetButtons: true,
        widgetDefinitions: widgetDefinitions,
        defaultWidgets: defaultWidgets,
        hideWidgetClose: true,
        hideWidgetSettings: true
    };
});

<|endoftext|>


<commit_before>console.log('Loading CAP event notifications');

var http = require('http');
var aws = require('aws-sdk');
var s3 = new aws.S3({ apiVersion: '2006-03-01' });

/**
 * See https://nodejs.org/api/http.html#http_http_request_options_callback
 *
 * This handler accepts an event containing a GeoJson shape definition. Normally [tho not constrained so] this will
 * be a polygon or a circle. The handler will return a list of all subscriptions intersecting that alert profile.
 * Example events include
 *
 *  "polygonCoordinates": [
 *    [-109.5297,40.4554], [-109.5298,40.4556], [-109.5299,40.4556], [-109.5299,40.4554], [-109.5297,40.4554]
 *  ]
 *
 *
 *  "circleCenterRadius": [ -109.5288, 40.4555, 1000]
 *
 */
exports.handler = function(event, context) {

    console.log("Event %o",event);

    var shape = null;
    var send_sns = 1;
    var alerts = [];
    var num_alerts = 1;

    var sns = send_sns ? new aws.SNS() : null;

    if ( event.Records ) {
      num_alerts = event.Records.length;

      for (var i = 0; i < num_alerts; i++) {
        alerts.push(event.Records[i].Sns);
      }
    }
    else {
      // Direct event from http interface or test
      alerts.push(event);
    }

    for (var i = 0; i < num_alerts; i++) {

      var alert = alerts[i];

      if ( alert.polygonCoordinates ) {
        shape = {
          "type": "polygon",
          "coordinates" : [ alert.polygonCoordinates ]
        }
      }
      else if ( alert.circleCenterRadius ) {
         shape = {
          "type": "circle",
          "coordinates" : [alert.circleCenterRadius[0],event.circleCenterRadius[1]],
          "radius" : ""+alert.circleCenterRadius[2]+"m"
        }
      }
      else {
        console.log("Unable to handle event");
      }

      if ( shape ) {

        var postData = JSON.stringify({
                         "from":0,
                         "size":1000,
                         "query":{
                           "bool": {
                             "must": {
                               "match_all": {}
                             },
                             "filter": {
                                 "geo_shape": {
                                   "subshape": {
                                     "shape": shape,
                                     "relation":'intersects'
                                   }
                                 }
                               }
                             }
                           },
                           "sort":{
                             "recid":{order:'asc'}
                           }

        });

        console.log("Send query %s",postData);

        var options = {
          hostname: 'ce.semweb.co',
          port: 80,
          json: true,
          body: postData,
          path: '/es/alertssubscriptions/_search',
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Content-Length': postData.length
          }
        };

        var req = http.request(options, function(res) {
            var body = '';
            var lambda_response = 'OK';
            // console.log('Status:', res.statusCode);
            // console.log('Headers:', JSON.stringify(res.headers));
            res.setEncoding('utf8');
            res.on('data', function(chunk) {
                body += chunk;
            });

            res.on('end', function() {
                // console.log('Successfully processed HTTP response');
                // If we know it's JSON, parse it
                if (res.headers['content-type'].lastIndexOf('application/json',0) === 0 ) {
                  body = JSON.parse(body);
                  var num_profiles = body.hits.hits.length;

                  // console.log("Processing %d profiles",num_profiles);
                  for (var i = 0; i < num_profiles; i++) {
                    var profile_entry = body.hits.hits[i]
                    console.log("Processing hit %d %s %s %s %s",i,profile_entry._source.name,profile_entry._source.recid,profile_entry._source.shortcode);
                    // Shape is in profile_entry._source.subshape

                    if ( send_sns ) {
                      // Send sns for each matching sub
                      var pubResult = sns.publish({
                          Message: 'CAP Alert Profile Notification '+profile_entry._source.recid,
                          TopicArn: 'arn:aws:sns:eu-west-1:603029492791:CAPProfileNotification'
                          // TopicArn: 'arn:aws:sns:us-east-1:381798314226:alert-hub-area-match'
                      }, function(err, data) {
                          if (err) {
                              console.log(err.stack);
                              return;
                          }
                          // console.log('push sent');
                          // console.log(data);
                      });
                    }
                  }
                }
                else {
                  console.log("Unable to process response type %s",res.headers['content-type']);
                }

            });
        });

        req.on('error', context.fail);
        req.write(postData);
        req.end();
      }
      else {
        // No shape to search against
        console.log("No shape to search against");
      }
    }
    context.succeed(lambda_response);
};
<commit_msg>Extended handler to be multipurpose - sns and direct<commit_after>console.log('Loading CAP event notifications');

var http = require('http');
var aws = require('aws-sdk');
var s3 = new aws.S3({ apiVersion: '2006-03-01' });

/**
 * See https://nodejs.org/api/http.html#http_http_request_options_callback
 *
 * This handler accepts an event containing a GeoJson shape definition. Normally [tho not constrained so] this will
 * be a polygon or a circle. The handler will return a list of all subscriptions intersecting that alert profile.
 * Example events include
 *
 *  "polygonCoordinates": [
 *    [-109.5297,40.4554], [-109.5298,40.4556], [-109.5299,40.4556], [-109.5299,40.4554], [-109.5297,40.4554]
 *  ]
 *
 *
 *  "circleCenterRadius": [ -109.5288, 40.4555, 1000]
 *
 */
exports.handler = function(event, context) {

    console.log("Event %o",event);

    var shape = null;
    var send_sns = 1;
    var alerts = [];
    var num_alerts = 1;
    var lambda_response = 'OK';
    var sns = send_sns ? new aws.SNS() : null;

    if ( event.Records ) {
      num_alerts = event.Records.length;

      for (var i = 0; i < num_alerts; i++) {
        alerts.push(event.Records[i].Sns);
      }
    }
    else {
      // Direct event from http interface or test
      alerts.push(event);
    }

    for (var i = 0; i < num_alerts; i++) {

      var alert = alerts[i];

      if ( alert.polygonCoordinates ) {
        shape = {
          "type": "polygon",
          "coordinates" : [ alert.polygonCoordinates ]
        }
      }
      else if ( alert.circleCenterRadius ) {
         shape = {
          "type": "circle",
          "coordinates" : [alert.circleCenterRadius[0],event.circleCenterRadius[1]],
          "radius" : ""+alert.circleCenterRadius[2]+"m"
        }
      }
      else {
        console.log("Unable to handle event");
      }

      if ( shape ) {

        var postData = JSON.stringify({
                         "from":0,
                         "size":1000,
                         "query":{
                           "bool": {
                             "must": {
                               "match_all": {}
                             },
                             "filter": {
                                 "geo_shape": {
                                   "subshape": {
                                     "shape": shape,
                                     "relation":'intersects'
                                   }
                                 }
                               }
                             }
                           },
                           "sort":{
                             "recid":{order:'asc'}
                           }

        });

        console.log("Send query %s",postData);

        var options = {
          hostname: 'ce.semweb.co',
          port: 80,
          json: true,
          body: postData,
          path: '/es/alertssubscriptions/_search',
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Content-Length': postData.length
          }
        };

        var req = http.request(options, function(res) {
            var body = '';
            // console.log('Status:', res.statusCode);
            // console.log('Headers:', JSON.stringify(res.headers));
            res.setEncoding('utf8');
            res.on('data', function(chunk) {
                body += chunk;
            });

            res.on('end', function() {
                // console.log('Successfully processed HTTP response');
                // If we know it's JSON, parse it
                if (res.headers['content-type'].lastIndexOf('application/json',0) === 0 ) {
                  body = JSON.parse(body);
                  var num_profiles = body.hits.hits.length;

                  // console.log("Processing %d profiles",num_profiles);
                  for (var i = 0; i < num_profiles; i++) {
                    var profile_entry = body.hits.hits[i]
                    console.log("Processing hit %d %s %s %s %s",i,profile_entry._source.name,profile_entry._source.recid,profile_entry._source.shortcode);
                    // Shape is in profile_entry._source.subshape

                    if ( send_sns ) {
                      // Send sns for each matching sub
                      var pubResult = sns.publish({
                          Message: 'CAP Alert Profile Notification '+profile_entry._source.recid,
                          TopicArn: 'arn:aws:sns:eu-west-1:603029492791:CAPProfileNotification'
                          // TopicArn: 'arn:aws:sns:us-east-1:381798314226:alert-hub-area-match'
                      }, function(err, data) {
                          if (err) {
                              console.log(err.stack);
                              return;
                          }
                          // console.log('push sent');
                          // console.log(data);
                      });
                    }
                  }
                }
                else {
                  console.log("Unable to process response type %s",res.headers['content-type']);
                }

            });
        });

        req.on('error', context.fail);
        req.write(postData);
        req.end();
      }
      else {
        // No shape to search against
        console.log("No shape to search against");
      }
    }
    context.succeed(lambda_response);
};
<|endoftext|>


<commit_before>/*
 Map browser based on OpenLayers 4.
 Misc. common functions and mithril modules for UI via DOM.

 Copyright (C) 2017 Øyvind Hanssen, LA7ECA, ohanssen@acm.org

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published
 by the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

/**
 * Autojump between two fields.
 * @param {string} fieldId - Id of DOM field elelent to jump from.
 * @param {string} nextFieldId - Id of DOM field element to jump to.
 */

polaric.autojump = function(fieldId, nextFieldId)
{
   if (fieldId==null || nextFieldId==null) {
       console.error("Field id is null");
       return;
   }
   var downStrokeField;
   var myField=document.getElementById(fieldId);
   myField.nextField=document.getElementById(nextFieldId);
   myField.onkeydown=autojump_keyDown;
   myField.onkeyup=autojump_keyUp;

   function autojump_keyDown()
   {
      this.beforeLength=this.value.length;
      downStrokeField=this;
   }

   function autojump_keyUp()
   {
      if (
       (this == downStrokeField) &&
       (this.value.length > this.beforeLength) &&
       (this.value.length >= this.maxLength)
      )
         this.nextField.focus();
      downStrokeField=null;
   }
}
/* End of autojump stuff */

/* Some simple DOM elements */
var br = m("br");
var hr = m("hr");
var nbsp = m.trust(" ");

/**
 * Input field with default values and syntax checking.
 * @param {string} id - DOM element identifier.
 * @param {number} size - size of field.
 * @param {number} maxlength - max length of field.
 * @param {boolean} contentEditable - true if field can be edited by user.
 * @param {regex} regex - Regular expression that defines what input is valid.
 */
var textInput = {

    view: function(vn) {
       return m("input#"+vn.attrs.id,
        { type: "text", size: vn.attrs.size, maxlength: vn.attrs.maxlength,
          contentEditable: (vn.attrs.contentEditable ? vn.attrs.contentEditable : true),
            oninput: function() {
                if (!vn.attrs.regex)
                    return;
                vn.state.data=vn.dom.value;
                if (vn.attrs.regex.test(vn.dom.value)) {
                    vn.state.cssclass = "valid";
                    vn.dom.title = "Input OK";
                }
                else {
                    vn.state.cssclass = "invalid";
                    vn.dom.title = "Invalid input!";
                }
            },
            onchange: function() {
                if (!vn.attrs.regex.test(vn.dom.value) && vn.attrs.value)
                    setTimeout(function() {
                        vn.state.cssclass = "";
                        vn.dom.title = "Default from center of map";
                        vn.state.data = NaN;
                        m.redraw();
                    }, 4000);
            },

            value: (vn.state.data || vn.state.data == "" ? vn.state.data : vn.attrs.value),
            cssclass: (vn.state.cssclass ? vn.state.cssclass : "")
        });
   }
}

/**
 * MGRS input fields.
 */
var mgrsInput = {
    view: function() {
        var center = CONFIG.mb.getCenter();
        return m("span",
               {onclick: function() { polaric.autojump("locx", "locy"); }},
            m(textInput, {id:"mgrsprefix", size: 5, maxlength: 5,
                regex: /^[0-9]{2}[C-X][A-Z][A-V]$/i, value: polaric.MGRSprefix(center)}), nbsp,
            m(textInput, {id:"locx", size: 3, maxlength: 3, regex: /^[0-9]{3}$/ }),
            m(textInput, {id:"locy", size: "3", maxlength: "3", regex: /^[0-9]{3}$/ }), nbsp )
    }
 }

/**
 * UTM input fields.
 */
var utmInput = {
    view: function() {
        var uref = CONFIG.mb.getCenterUTM();
        return m("span",
                 { onclick: function() {
                     polaric.autojump('utmz', 'utmnz');
                     polaric.autojump('utmnz', 'utmx');
                     polaric.autojump('utmx', 'utmy');
                 }},
            m(textInput, {id:"utmz", size: "2", maxlength: "2", value: uref.lngZone, regex:/^[0-9]{2}$/}),
            m(textInput, {id:"utmnz", size: "1", maxlength: "1", value: uref.latZone,
                 contentEditable: false}), nbsp, nbsp,
            m(textInput, {id:"utmx", size: "6", maxlength: "6", regex:/^[0-9]{6}$/}),
            m(textInput, {id:"utmy", size: "7", maxlength: "7", regex:/^[0-9]{7}$/}), nbsp)
    }
 }

 /**
  * Lat long input fields.
  */
var reg_MIN =  /^(([0-5]?[0-9])|60)(\.([0-9]{1,4}))?$/;

var latLngInput = {
    view: function() {
        var center = CONFIG.mb.getCenter();
        return m("span",
                 { onclick: function() {
                     polaric.autojump('ll_Nd', 'll_Nm');
                     polaric.autojump('ll_Nm', 'll_Ed');
                     polaric.autojump('ll_Ed', 'll_Em');
                 }},
            m(textInput, {id:"ll_Nd", size: "2", maxlength: "2", regex:/^(([0-8]?[0-9])|90)$/}), "°", nbsp,nbsp,
            m(textInput, {id:"ll_Nm", size: "6", maxlength: "6", regex: reg_MIN }), "\'", nbsp,
            m("span#ll_NS",   {onclick:this.clickNS}, (center[1] < 0 ? "S":"N")), nbsp, nbsp,
            m(textInput, {id:"ll_Ed", size: "3", maxlength: "3", regex:/^[0-9]{1,3}$/}), "°", nbsp,nbsp,
            m(textInput, {id:"ll_Em", size: "6", maxlength: "6", regex: reg_MIN }), "\'", nbsp,
            m("span#ll_EW",   {onclick:this.clickEW}, (center[0] < 0 ? "W":"E")), nbsp, nbsp)
    },

    /* Change betwen E and W by clicking on the letter */
    clickNS: function() {
       var val = $("#ll_NS").html();
          $("#ll_NS").html( (val=="N" ? "S" : "N"));
    },

    /* Change between N and S by clicking on the letter */
    clickEW: function() {
       var val = $("#ll_EW").html();
          $("#ll_EW").html( (val=="E" ? "W" : "E"));
    }
 }

<commit_msg>Small fix..<commit_after>/*
 Map browser based on OpenLayers 4.
 Misc. common functions and mithril modules for UI via DOM.

 Copyright (C) 2017 Øyvind Hanssen, LA7ECA, ohanssen@acm.org

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published
 by the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

/**
 * Autojump between two fields.
 * @param {string} fieldId - Id of DOM field elelent to jump from.
 * @param {string} nextFieldId - Id of DOM field element to jump to.
 */

polaric.autojump = function(fieldId, nextFieldId)
{
   if (fieldId==null || nextFieldId==null) {
       console.error("Field id is null");
       return;
   }
   var downStrokeField;
   var myField=document.getElementById(fieldId);
   myField.nextField=document.getElementById(nextFieldId);
   myField.onkeydown=autojump_keyDown;
   myField.onkeyup=autojump_keyUp;

   function autojump_keyDown()
   {
      this.beforeLength=this.value.length;
      downStrokeField=this;
   }

   function autojump_keyUp()
   {
      if (
       (this == downStrokeField) &&
       (this.value.length > this.beforeLength) &&
       (this.value.length >= this.maxLength)
      )
         this.nextField.focus();
      downStrokeField=null;
   }
}
/* End of autojump stuff */

/* Some simple DOM elements */
var br = m("br");
var hr = m("hr");
var nbsp = m.trust(" ");

/**
 * Input field with default values and syntax checking.
 * @param {string} id - DOM element identifier.
 * @param {number} size - size of field.
 * @param {number} maxlength - max length of field.
 * @param {boolean} contentEditable - true if field can be edited by user.
 * @param {regex} regex - Regular expression that defines what input is valid.
 */
var textInput = {

    view: function(vn) {
       return m("input#"+vn.attrs.id,
        { type: "text", size: vn.attrs.size, maxlength: vn.attrs.maxlength,
          contentEditable: (vn.attrs.contentEditable ? vn.attrs.contentEditable : true),
            oninput: function() {
                if (!vn.attrs.regex)
                    return;
                vn.state.data=vn.dom.value;
                if (vn.attrs.regex.test(vn.dom.value)) {
                    vn.state.cssclass = "valid";
                    vn.dom.title = "Input OK";
                }
                else {
                    vn.state.cssclass = "invalid";
                    vn.dom.title = "Invalid input!";
                }
            },
            onchange: function() {
                if (!vn.attrs.regex.test(vn.dom.value) && vn.attrs.value)
                    setTimeout(function() {
                        vn.state.cssclass = "";
                        vn.dom.title = "Default from center of map";
                        vn.state.data = NaN;
                        m.redraw();
                    }, 4000);
            },

            value: (vn.state.data || vn.state.data == "" ? vn.state.data : vn.attrs.value),
            className: (vn.state.cssclass ? vn.state.cssclass : "")
        });
   }
}

/**
 * MGRS input fields.
 */
var mgrsInput = {
    view: function() {
        var center = CONFIG.mb.getCenter();
        return m("span",
               {onclick: function() { polaric.autojump("locx", "locy"); }},
            m(textInput, {id:"mgrsprefix", size: 5, maxlength: 5,
                regex: /^[0-9]{2}[C-X][A-Z][A-V]$/i, value: polaric.MGRSprefix(center)}), nbsp,
            m(textInput, {id:"locx", size: 3, maxlength: 3, regex: /^[0-9]{3}$/ }),
            m(textInput, {id:"locy", size: "3", maxlength: "3", regex: /^[0-9]{3}$/ }), nbsp )
    }
 }

/**
 * UTM input fields.
 */
var utmInput = {
    view: function() {
        var uref = CONFIG.mb.getCenterUTM();
        return m("span",
                 { onclick: function() {
                     polaric.autojump('utmz', 'utmnz');
                     polaric.autojump('utmnz', 'utmx');
                     polaric.autojump('utmx', 'utmy');
                 }},
            m(textInput, {id:"utmz", size: "2", maxlength: "2", value: uref.lngZone, regex:/^[0-9]{2}$/}),
            m(textInput, {id:"utmnz", size: "1", maxlength: "1", value: uref.latZone,
                 contentEditable: false}), nbsp, nbsp,
            m(textInput, {id:"utmx", size: "6", maxlength: "6", regex:/^[0-9]{6}$/}),
            m(textInput, {id:"utmy", size: "7", maxlength: "7", regex:/^[0-9]{7}$/}), nbsp)
    }
 }

 /**
  * Lat long input fields.
  */
var reg_MIN =  /^(([0-5]?[0-9])|60)(\.([0-9]{1,4}))?$/;

var latLngInput = {
    view: function() {
        var center = CONFIG.mb.getCenter();
        return m("span",
                 { onclick: function() {
                     polaric.autojump('ll_Nd', 'll_Nm');
                     polaric.autojump('ll_Nm', 'll_Ed');
                     polaric.autojump('ll_Ed', 'll_Em');
                 }},
            m(textInput, {id:"ll_Nd", size: "2", maxlength: "2", regex:/^(([0-8]?[0-9])|90)$/}), "°", nbsp,nbsp,
            m(textInput, {id:"ll_Nm", size: "6", maxlength: "6", regex: reg_MIN }), "\'", nbsp,
            m("span#ll_NS",   {onclick:this.clickNS}, (center[1] < 0 ? "S":"N")), nbsp, nbsp,
            m(textInput, {id:"ll_Ed", size: "3", maxlength: "3", regex:/^[0-9]{1,3}$/}), "°", nbsp,nbsp,
            m(textInput, {id:"ll_Em", size: "6", maxlength: "6", regex: reg_MIN }), "\'", nbsp,
            m("span#ll_EW",   {onclick:this.clickEW}, (center[0] < 0 ? "W":"E")), nbsp, nbsp)
    },

    /* Change betwen E and W by clicking on the letter */
    clickNS: function() {
       var val = $("#ll_NS").html();
          $("#ll_NS").html( (val=="N" ? "S" : "N"));
    },

    /* Change between N and S by clicking on the letter */
    clickEW: function() {
       var val = $("#ll_EW").html();
          $("#ll_EW").html( (val=="E" ? "W" : "E"));
    }
 }

<|endoftext|>


<commit_before>$(document).ready(function () {
    if (!isTouchDevice) {
        $('#mara-navigation').mouseover(expandNavigation);
        $('#mara-navigation').mouseleave(collapseNavigation);
    }

    $.ajax({
        url: '/admin/navigation-bar',
        success: function (navigationEntries) {
            $('#mara-navigation').empty().append(navigationEntries).fadeIn(500);

            // enable tooltips
            $('[data-toggle="tooltip"]').tooltip();

            // highlight navigation entry for current uri
            highlightNavigationEntry(window.location.pathname + window.location.search + window.location.hash);

            localStorage.setItem('navigation-bar', navigationEntries);
        }
    });

    // float headers of all tables with class `.mara-table`
    floatMaraTableHeaders();
});

// the nav entry that matches the current page uri best
var currentNavigationEntry;

// expands and highlights the navigation entry that matches an uri best
function highlightNavigationEntry(uri) {

    // find all navigation entries that match the request uri, take the longest (most specific) match
    var matchingUris = $('#mara-navigation .mara-nav-entry > a')
        .map(function () {
            return $(this).attr('href');
        })
        .filter(function (x) {
            return uri.startsWith(this);
        });

    if (matchingUris) {
        var longestUri = matchingUris.sort(function (a, b) {
            return b.length - a.length
        })[0];

        currentNavigationEntry = $('#mara-navigation .mara-nav-entry > a[href="' + longestUri + '"]').parent();

        currentNavigationEntry.siblings().removeClass('highlighted');
        currentNavigationEntry.addClass('highlighted');
        currentNavigationEntry.addClass('visible');
        currentNavigationEntry.addClass('expanded');
        currentNavigationEntry.parentsUntil('#mara-navigation').addClass('expanded');
        currentNavigationEntry.parentsUntil('#mara-navigation').addClass('highlighted');
        currentNavigationEntry.parentsUntil('#mara-navigation').addClass('visible');
        currentNavigationEntry.parentsUntil('#mara-navigation').children('div').addClass('visible');
    }
}

// expands or collapses a navigation entry
function toggleNavigationEntry(a) {
    if ($(a).parent().hasClass('expanded')) {
        $(a).parent().removeClass('expanded');
        $(a).siblings().removeClass('visible')
            .css('height', '') // reset height if it was left over from a previous slide action
            .slideUp({queue: true});
    } else {
        $(a).parent().addClass('expanded');
        $(a).siblings().addClass('visible')
            .css('height', '') // reset height if it was left over from a previous slide action
            .slideDown({queue: true});
    }
}

// expands the navigation sidebar
function expandNavigation() {
    if ($('body').hasClass('navigation-collapsed')) {
        $('body').removeClass('navigation-collapsed');
        $('#mara-navigation .mara-nav-entry.visible:not(.level-1)')
            .css('height', '') // reset height if it was left over from a previous slide action
            .show(0);
        if (currentNavigationEntry) {
            currentNavigationEntry[0].scrollIntoView();
        }
    }
}

// collapses the navigation side bar
function collapseNavigation() {
    $('body').addClass('navigation-collapsed');
    $('#mara-navigation .mara-nav-entry.level-2.visible').slideUp({queue: true});
}

// expands or collapses the navigation side bar
function toggleNavigation() {
    if ($('body').hasClass('navigation-collapsed')) {
        expandNavigation();
    } else {
        collapseNavigation();
    }
}

// adds an alert to the bottom of the page
function showAlert(message, category) {
    alert = $('
' +
        '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
        '×' +
        '</button>' + message + '
');
    $('#alerts').append(alert);
    alert.fadeIn(2000);
}

// floats all mara table headers
function floatMaraTableHeaders() {
    $('.mara-table-float-header').floatThead({
        top: 60,
        position: 'absolute'
    });
}

// when the page layout drastically changes,
// then the floating headers need to be re-positioned
function reflowMaraTableHeaders() {
    $('.mara-table-float-header').floatThead('reflow');
}

// Replaces the content of the element with id `containerId` with the result of calling url
// When the requests succeeds, the content of the onSuccess variable is evaluated
function loadContentAsynchronously(containerId, url, divHeightKey, onSuccess) {
    $.ajax({
        url: url,
        error: function (xhr, textStatus, errorThrown) {
            var icon = '  ';
            showAlert(icon + textStatus + ' while fetching "' + url + '": ' + errorThrown,
                'danger');
            $('#' + containerId).empty().append(icon);
        },
        success: function (data) {
            $('#' + containerId).css('height', '');
            $('#' + containerId).empty().hide().append(data).fadeIn(300);
            eval(onSuccess);
            reflowMaraTableHeaders();
            localStorage.setItem(divHeightKey, $('#' + containerId).height());
        }
    });
}

<commit_msg>add error handling for asynchronous loading of navigation<commit_after>$(document).ready(function () {
    if (!isTouchDevice) {
        $('#mara-navigation').mouseover(expandNavigation);
        $('#mara-navigation').mouseleave(collapseNavigation);
    }

    var navigationUrl = '/admin/navigation-bar';
    $.ajax({
        url: navigationUrl,
        success: function (navigationEntries) {
            $('#mara-navigation').empty().append(navigationEntries).fadeIn(500);

            // enable tooltips
            $('[data-toggle="tooltip"]').tooltip();

            // highlight navigation entry for current uri
            highlightNavigationEntry(window.location.pathname + window.location.search + window.location.hash);

            localStorage.setItem('navigation-bar', navigationEntries);
        },
        error: function (xhr, textStatus, errorThrown) {
            showAlert(icon + textStatus + ' while fetching "' + navigationUrl + '": ' + errorThrown,
                'danger');
            $('#mara-navigation').empty().append('

');
        },
    });

    // float headers of all tables with class `.mara-table`
    floatMaraTableHeaders();
});

// the nav entry that matches the current page uri best
var currentNavigationEntry;

// expands and highlights the navigation entry that matches an uri best
function highlightNavigationEntry(uri) {

    // find all navigation entries that match the request uri, take the longest (most specific) match
    var matchingUris = $('#mara-navigation .mara-nav-entry > a')
        .map(function () {
            return $(this).attr('href');
        })
        .filter(function (x) {
            return uri.startsWith(this);
        });

    if (matchingUris) {
        var longestUri = matchingUris.sort(function (a, b) {
            return b.length - a.length
        })[0];

        currentNavigationEntry = $('#mara-navigation .mara-nav-entry > a[href="' + longestUri + '"]').parent();

        currentNavigationEntry.siblings().removeClass('highlighted');
        currentNavigationEntry.addClass('highlighted');
        currentNavigationEntry.addClass('visible');
        currentNavigationEntry.addClass('expanded');
        currentNavigationEntry.parentsUntil('#mara-navigation').addClass('expanded');
        currentNavigationEntry.parentsUntil('#mara-navigation').addClass('highlighted');
        currentNavigationEntry.parentsUntil('#mara-navigation').addClass('visible');
        currentNavigationEntry.parentsUntil('#mara-navigation').children('div').addClass('visible');
    }
}

// expands or collapses a navigation entry
function toggleNavigationEntry(a) {
    if ($(a).parent().hasClass('expanded')) {
        $(a).parent().removeClass('expanded');
        $(a).siblings().removeClass('visible')
            .css('height', '') // reset height if it was left over from a previous slide action
            .slideUp({queue: true});
    } else {
        $(a).parent().addClass('expanded');
        $(a).siblings().addClass('visible')
            .css('height', '') // reset height if it was left over from a previous slide action
            .slideDown({queue: true});
    }
}

// expands the navigation sidebar
function expandNavigation() {
    if ($('body').hasClass('navigation-collapsed')) {
        $('body').removeClass('navigation-collapsed');
        $('#mara-navigation .mara-nav-entry.visible:not(.level-1)')
            .css('height', '') // reset height if it was left over from a previous slide action
            .show(0);
        if (currentNavigationEntry) {
            currentNavigationEntry[0].scrollIntoView();
        }
    }
}

// collapses the navigation side bar
function collapseNavigation() {
    $('body').addClass('navigation-collapsed');
    $('#mara-navigation .mara-nav-entry.level-2.visible').slideUp({queue: true});
}

// expands or collapses the navigation side bar
function toggleNavigation() {
    if ($('body').hasClass('navigation-collapsed')) {
        expandNavigation();
    } else {
        collapseNavigation();
    }
}

// adds an alert to the bottom of the page
function showAlert(message, category) {
    alert = $('
' +
        '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
        '×' +
        '</button>' + message + '
');
    $('#alerts').append(alert);
    alert.fadeIn(2000);
}

// floats all mara table headers
function floatMaraTableHeaders() {
    $('.mara-table-float-header').floatThead({
        top: 60,
        position: 'absolute'
    });
}

// when the page layout drastically changes,
// then the floating headers need to be re-positioned
function reflowMaraTableHeaders() {
    $('.mara-table-float-header').floatThead('reflow');
}

// Replaces the content of the element with id `containerId` with the result of calling url
// When the requests succeeds, the content of the onSuccess variable is evaluated
function loadContentAsynchronously(containerId, url, divHeightKey, onSuccess) {
    $.ajax({
        url: url,
        error: function (xhr, textStatus, errorThrown) {
            var icon = '  ';
            showAlert(icon + textStatus + ' while fetching "' + url + '": ' + errorThrown,
                'danger');
            $('#' + containerId).empty().append(icon);
        },
        success: function (data) {
            $('#' + containerId).css('height', '');
            $('#' + containerId).empty().hide().append(data).fadeIn(300);
            eval(onSuccess);
            reflowMaraTableHeaders();
            localStorage.setItem(divHeightKey, $('#' + containerId).height());
        }
    });
}

<|endoftext|>


<commit_before>/**
 * Laravel AJAX Support with Form Validation
 *
 * @dependency jQuery >2
 * @dependency CSS BOOTSRAP >=3
 * @dependency HTML <meta name="_token" content="{!! csrf_token() !!}"/>
 * @autor Daniel Kouba whipstercz@gmail.com
 */
var laravel = (function ($, laravel) {
    laravel.ajax = {};
    laravel.errors = laravel.errors || {};

    //Configuration validation
    laravel.errors.errorBagContainer = $('#errors');
    laravel.errors.showErrorsBag = true;
    laravel.errors.showErrorsInFormGroup = false;

    laravel.ajax.init = function () {
        //Adding info about submit trigger
        $("input[type=submit], button", $('form.ajax')).click(function (event) {
            var submittedBy = $(this).attr('name') || $(this).attr('value');
            $(this).closest('form').attr('data-submitted-by', submittedBy);
        });

        //Setting default AJAX behaviours
        $.ajaxSetup({
            headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')},
            dataType: "json",
            type: 'GET'
        });

        //Sending form.ajax by AJAX
        $(document).on('submit', 'form.ajax', function (event) {
            event.preventDefault();
            $.ajax({
                type: $(this).attr('method'),
                url: $(this).attr('action'),
                data: laravel.ajax.formData(this),
                context: {
                    sender: event.target,
                    url: $(this).attr('action')
                },
                success: laravel.ajax.successHandler,
                error: laravel.ajax.errorHandler
            })
        });

        //AJAX requests for links.ajax
        $(document).on('click', 'a.ajax', function (event) {
            event.preventDefault();
            $.ajax({
                url: this.href,
                context: {
                    sender: event.target,
                    url: this.href
                },
                success: laravel.ajax.successHandler,
                error: laravel.ajax.errorHandler
            });
        });
    };

    //User defined custom Ajax request
    laravel.ajax.send = function(data){
        data = data || {};
        if (data.type == undefined) {
            data.type = 'GET';
        }
        if (data.success == undefined) {
            data.success = laravel.ajax.successHandler;
        }
        if (data.error == undefined) {
            data.error = laravel.ajax.errorHandler;
        }
        $.ajax(data);
    };

    //AJAX response handlers
    laravel.ajax.successHandler = function (payload) {
        //console.info('ajax success',this,  payload);
        //var sender = this.sender;
        //var url = this.url;
        //clean validation errors
        laravel.errors.clearValidation();
        // message
        if (payload.alert) {
            laravel.alert(payload.alert);
        }
        // console.info
        if (payload.dump) {
            laravel.dump(payload);
        }
        // redirect
        if (payload.redirect) {
            laravel.redirect(payload.redirect);
            return;
        }
        // render sections
        if (payload.sections) {
            if ( payload.drawMode == 'append') {
                laravel.appendSections(payload.sections);
            } else {
                laravel.redrawSections(payload.sections);
            }
        }

        //page scrollTo elementID
        if (payload.scrollTo) {
            laravel.scrollTo(payload.scrollTo);
        }

        // eval - run js from PHP
        if (payload.runJavascript) {
            eval(payload.runJavascript);
        }
    };
    laravel.ajax.errorHandler = function (event) {
        var sender = this.sender;
        var url = this.url;
        var payload = event.responseJSON;
        var status = event.status;
        //console.info('ajax error',this,payload,event);

        if (status == 422) {  //validation Error
            laravel.errors.clearValidation(sender);
            laravel.errors.renderValidation(payload, sender);
            //laravel.alert("Sorry. There were validation errors");
        } else if (status == 403) { //forbidden
            laravel.alert("Sorry. You don't have permission for requested page")
        } else if (status == 404) { //not found
            laravel.alert('Sorry. Requested page "' + url + '" not found')
        } else if (status == 200) { //OK but not really :)
            laravel.alert('Sorry. Response is not valid JSON');
        } else if (status == 0) {
            //Aborted request
        } else {
            laravel.alert(event.statusText);
        }
    };
    laravel.ajax.formData = function (form) {
        var $form = $(form);
        var data = $form.serializeArray();
        var submittedBy = $form.attr('data-submitted-by');
        //var data = $form.serialize();
        if (submittedBy != undefined) {
            data.push({name: 'submitted-by', value: submittedBy});
            data.push({name: submittedBy, value: 'submitted-by'});
        }
        return data;
    };

    //defining helpers
    laravel.redrawSection = function (element, html) {
        if (( typeof element ) == 'string') {
            element = $("#" + element)
        } else {
            element = $(element);
        }
        element.html(html);
    };
    laravel.redrawSections = function (sections) {
        for (var elementId in sections) {
            laravel.redrawSection(elementId, sections[elementId]);
        }
    };
    laravel.appendSections = function (sections) {
        for (var elementId in sections) {
            laravel.appendSection(elementId, sections[elementId]);
        }
    };
    laravel.appendSection = function (element, html) {
        if (( typeof element ) == 'string') {
            element = $("#" + element)
        } else {
            element = $(element);
        }
        element.append(html);
    };
    laravel.dump = function (data) {
        if (window.console) {
            console.info(data);
        }
    };
    laravel.redirect = function (url) {
        window.location.href = url;
    };
    laravel.alert = function (message) {
        alert(message);
    };
    laravel.scrollTo = function (elementId) {
        $('html, body').animate({
            scrollTop: $("#" + elementId).offset().top
        }, 2000);
    };

    //laravel error handling
    laravel.errors.clearValidation = function (form) {
        //remove errorBag element id='error'
        if (laravel.errors.showErrorsBag && laravel.errors.errorBagContainer.length > 0) {
            laravel.errors.errorBagContainer.html('');
        }
        //remove existing error classes and error messages from form groups
        if (laravel.errors.showErrorsInFormGroup) {
            $(form).find('.has-error .help-block').text('');
        }
        $(form).find('.has-error').removeClass('has-error');
    };
    laravel.errors.renderValidationErrorBag = function (errors) {
        if (laravel.errors.showErrorsBag) {

            var $ul = $('

');
            for (var fieldName in errors) {
                if (errors.hasOwnProperty(fieldName)) {
                    var fieldErrors = errors[fieldName];
                    //console.info(field,fieldErrors);
                    fieldErrors.forEach(function (error) {
                        $ul.append($('

').text(error))
                    });
                }
            }
            if (laravel.errors.errorBagContainer.length == 0) {
                laravel.alert("ErrorBag display container haven't been found");
            }
            var $errorBag = $('

');
            $errorBag.append($ul);
            laravel.errors.errorBagContainer.append($errorBag);
        }
    };
    laravel.errors.renderValidationFormGroup = function (fieldName, errors, form, shouldFocus) {
        //console.info(fieldName,errors,form.shouldFocus);
        var field = $(form).find('[name="' + fieldName + '"]');
        if (field.length == 0) {
            field = $(form).find('[name="' + fieldName + '[]"]');
        }
        if (field.length == 0) {
            field = $(form).find('#' + fieldName);
        }
        field = field.not('[type="hidden"]').first();
        var formGroup = field.parent();
        //console.info(fieldName,errors,field,form);

        if (shouldFocus) {
            field.focus();
        }

        //add form group error class
        formGroup.addClass('has-error');
        //add form group error message
        if (laravel.errors.showErrorsInFormGroup) {
            var $span = formGroup.find('.help-block');
            if ($span.length == 0) {
                $span = $('');
                formGroup.append($span);
            }
            $span.text(errors.join(', '));
        }
    };
    laravel.errors.renderValidation = function (errors, form) {
        form = form || document;
        //console.info(errors);

        //render errors to errorBag container
        laravel.errors.renderValidationErrorBag(errors);

        var isFirstError = true;
        for (var fieldName in errors) {
            if (errors.hasOwnProperty(fieldName)) {
                var fieldErrors = errors[fieldName];
                //console.info(field,fieldErrors);
                fieldName = laravel.errors.sanitizeFieldName(fieldName);
                laravel.errors.renderValidationFormGroup(fieldName, fieldErrors, form, isFirstError);
                isFirstError = false;
            }
        }
    };
    laravel.errors.sanitizeFieldName = function (name) {
        // converts  notation from dot to array - offices.0.id => offices[0][id]
        var chunks = name.split(".");
        if (chunks.length > 1) {
            var sanitized = chunks[0];
            for (i = 1; i < chunks.length; i++) {
                var chunk = chunks[i];
                sanitized = sanitized + "[" + chunk + "]";
            }
            return sanitized;
        }
        return name;
    };

    laravel.ajax.init();
    return laravel;
})(jQuery, laravel || {});
<commit_msg>removing global ajax<commit_after>/**
 * Laravel AJAX Support with Form Validation
 *
 * @dependency jQuery >2
 * @dependency CSS BOOTSRAP >=3
 * @dependency HTML <meta name="_token" content="{!! csrf_token() !!}"/>
 * @autor Daniel Kouba whipstercz@gmail.com
 */
var laravel = (function ($, laravel) {

    laravel.ajax = {};
    laravel.errors = laravel.errors || {};

    //Configuration validation
    laravel.errors.errorBagContainer = $('#errors');
    laravel.errors.showErrorsBag = true;
    laravel.errors.showErrorsInFormGroup = false;

    laravel.ajax.init = function () {
        //Adding info about submit trigger
        $("input[type=submit], button", $('form.ajax')).click(function (event) {
            var submittedBy = $(this).attr('name') || $(this).attr('value');
            $(this).closest('form').attr('data-submitted-by', submittedBy);
        });

        //Setting default AJAX behaviours
        $.ajaxSetup({
            headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
        });

        //Sending form.ajax by AJAX
        $(document).on('submit', 'form.ajax', function (event) {
            event.preventDefault();
            $.ajax({
                type: $(this).attr('method'),
                url: $(this).attr('action'),
                data: laravel.ajax.formData(this),
                dataType: "json",
                context: {
                    sender: event.target,
                    url: $(this).attr('action')
                },
                success: laravel.ajax.successHandler,
                error: laravel.ajax.errorHandler
            })
        });

        //AJAX requests for links.ajax
        $(document).on('click', 'a.ajax', function (event) {
            event.preventDefault();
            $.ajax({
                url: this.href,
                dataType: "json",
                context: {
                    sender: event.target,
                    url: this.href
                },
                success: laravel.ajax.successHandler,
                error: laravel.ajax.errorHandler
            });
        });
    };

    //User defined custom Ajax request
    laravel.ajax.send = function(data){
        data = data || {};
        if (data.type == undefined) {
            data.type = 'GET';
        }
        if (data.dataType == undefined) {
            data.dataType = 'json';
        }
        if (data.success == undefined) {
            data.success = laravel.ajax.successHandler;
        }
        if (data.error == undefined) {
            data.error = laravel.ajax.errorHandler;
        }
        $.ajax(data);
    };

    //AJAX response handlers
    laravel.ajax.successHandler = function (payload) {
        //console.info('ajax success',this,  payload);
        //var sender = this.sender;
        //var url = this.url;
        //clean validation errors
        laravel.errors.clearValidation();
        // message
        if (payload.alert) {
            laravel.alert(payload.alert);
        }
        // console.info
        if (payload.dump) {
            laravel.dump(payload);
        }
        // redirect
        if (payload.redirect) {
            laravel.redirect(payload.redirect);
            return;
        }
        // render sections
        if (payload.sections) {
            if ( payload.drawMode == 'append') {
                laravel.appendSections(payload.sections);
            } else {
                laravel.redrawSections(payload.sections);
            }
        }

        //page scrollTo elementID
        if (payload.scrollTo) {
            laravel.scrollTo(payload.scrollTo);
        }

        // eval - run js from PHP
        if (payload.runJavascript) {
            eval(payload.runJavascript);
        }
    };
    laravel.ajax.errorHandler = function (event) {
        var sender = this.sender;
        var url = this.url;
        var payload = event.responseJSON;
        var status = event.status;
        //console.info('ajax error',this,payload,event);

        if (status == 422) {  //validation Error
            laravel.errors.clearValidation(sender);
            laravel.errors.renderValidation(payload, sender);
            //laravel.alert("Sorry. There were validation errors");
        } else if (status == 403) { //forbidden
            laravel.alert("Sorry. You don't have permission for requested page")
        } else if (status == 404) { //not found
            laravel.alert('Sorry. Requested page "' + url + '" not found')
        } else if (status == 200) { //OK but not really :)
            laravel.alert('Sorry. Response is not valid JSON');
        } else if (status == 0) {
            //Aborted request
        } else {
            laravel.alert(event.statusText);
        }
    };
    laravel.ajax.formData = function (form) {
        var $form = $(form);
        var data = $form.serializeArray();
        var submittedBy = $form.attr('data-submitted-by');
        //var data = $form.serialize();
        if (submittedBy != undefined) {
            data.push({name: 'submitted-by', value: submittedBy});
            data.push({name: submittedBy, value: 'submitted-by'});
        }
        return data;
    };

    //defining helpers
    laravel.redrawSection = function (element, html) {
        if (( typeof element ) == 'string') {
            element = $("#" + element)
        } else {
            element = $(element);
        }
        element.html(html);
    };
    laravel.redrawSections = function (sections) {
        for (var elementId in sections) {
            laravel.redrawSection(elementId, sections[elementId]);
        }
    };
    laravel.appendSections = function (sections) {
        for (var elementId in sections) {
            laravel.appendSection(elementId, sections[elementId]);
        }
    };
    laravel.appendSection = function (element, html) {
        if (( typeof element ) == 'string') {
            element = $("#" + element)
        } else {
            element = $(element);
        }
        element.append(html);
    };
    laravel.dump = function (data) {
        if (window.console) {
            console.info(data);
        }
    };
    laravel.redirect = function (url) {
        window.location.href = url;
    };
    laravel.alert = function (message) {
        alert(message);
    };
    laravel.scrollTo = function (elementId) {
        $('html, body').animate({
            scrollTop: $("#" + elementId).offset().top
        }, 2000);
    };

    //laravel error handling
    laravel.errors.clearValidation = function (form) {
        //remove errorBag element id='error'
        if (laravel.errors.showErrorsBag && laravel.errors.errorBagContainer.length > 0) {
            laravel.errors.errorBagContainer.html('');
        }
        //remove existing error classes and error messages from form groups
        if (laravel.errors.showErrorsInFormGroup) {
            $(form).find('.has-error .help-block').text('');
        }
        $(form).find('.has-error').removeClass('has-error');
    };
    laravel.errors.renderValidationErrorBag = function (errors) {
        if (laravel.errors.showErrorsBag) {

            var $ul = $('

');
            for (var fieldName in errors) {
                if (errors.hasOwnProperty(fieldName)) {
                    var fieldErrors = errors[fieldName];
                    //console.info(field,fieldErrors);
                    fieldErrors.forEach(function (error) {
                        $ul.append($('

').text(error))
                    });
                }
            }
            if (laravel.errors.errorBagContainer.length == 0) {
                laravel.alert("ErrorBag display container haven't been found");
            }
            var $errorBag = $('

');
            $errorBag.append($ul);
            laravel.errors.errorBagContainer.append($errorBag);
        }
    };
    laravel.errors.renderValidationFormGroup = function (fieldName, errors, form, shouldFocus) {
        //console.info(fieldName,errors,form.shouldFocus);
        var field = $(form).find('[name="' + fieldName + '"]');
        if (field.length == 0) {
            field = $(form).find('[name="' + fieldName + '[]"]');
        }
        if (field.length == 0) {
            field = $(form).find('#' + fieldName);
        }
        field = field.not('[type="hidden"]').first();
        var formGroup = field.parent();
        //console.info(fieldName,errors,field,form);

        if (shouldFocus) {
            field.focus();
        }

        //add form group error class
        formGroup.addClass('has-error');
        //add form group error message
        if (laravel.errors.showErrorsInFormGroup) {
            var $span = formGroup.find('.help-block');
            if ($span.length == 0) {
                $span = $('');
                formGroup.append($span);
            }
            $span.text(errors.join(', '));
        }
    };
    laravel.errors.renderValidation = function (errors, form) {
        form = form || document;
        //console.info(errors);

        //render errors to errorBag container
        laravel.errors.renderValidationErrorBag(errors);

        var isFirstError = true;
        for (var fieldName in errors) {
            if (errors.hasOwnProperty(fieldName)) {
                var fieldErrors = errors[fieldName];
                //console.info(field,fieldErrors);
                fieldName = laravel.errors.sanitizeFieldName(fieldName);
                laravel.errors.renderValidationFormGroup(fieldName, fieldErrors, form, isFirstError);
                isFirstError = false;
            }
        }
    };
    laravel.errors.sanitizeFieldName = function (name) {
        // converts  notation from dot to array - offices.0.id => offices[0][id]
        var chunks = name.split(".");
        if (chunks.length > 1) {
            var sanitized = chunks[0];
            for (i = 1; i < chunks.length; i++) {
                var chunk = chunks[i];
                sanitized = sanitized + "[" + chunk + "]";
            }
            return sanitized;
        }
        return name;
    };

    laravel.ajax.init();
    return laravel;
})(jQuery, laravel || {});
<|endoftext|>


<commit_before>$(document).ready(function () {
  alert("Hi From Login.js");
});
// End Scope
<commit_msg>Se creo la funcion para enviar los valores del formulario de logion al metodo en el controlados<commit_after>$(document).ready(function () {

  // Set the main path on the server
  let URL="http://localhost/EntracesExitEmployees/index.php/"

  $("#js_LoginBtn").click(function () {

    // Get Employee Number
    var EmpNumber=$("#js_EmployeeNmbr").val();

    // Get Employe Password
    var Password=$("#js_Password").val();

    // Start ajax
    $.ajax({
      type:"POST",
      url:URL+"LoginController/Login",
      data:{ EMPNUM:EmpNumber, PASS:Password },
      success:function (data) {

        // Display backend result on the DOM
        $(".Js_LgnResult").html(data);

      },
      error:function (xhr) {
        alert("Error: " +xhr.responseText);
      }

    });
    // End ajax

  });
  // End Click

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