<commit_before>/**
 * Laboratory Information Indexing System
 *
 * An open source mini LIMS for metadata organisation and archival purposes
 *
 * @author      Matt Forster / @frostyforster
 * @copyright   Copyright (c) 2013, Matthew S. Forster
 * @license     MIT (./license.txt)
 * @link        http://github.com/forstermatth/liis
 * @since       Version 1.0
 * @filesource
 */

 /* ------------------------------------------------------------------------ */

/**
 * main.js
 *
 * all of the javascript used in the application
 *
 * @category    LIIS-View
 * @author      Matt Forster / @frostyforster
 * @link        http://github.com/forstermatth/liis
 */

//Procedues ==================================================
$(document).ready(function () {

     //Progress bar -------------------------------------------------
    $('#progbar').hide()

    $('#progbar').ajaxStart(function () {
        $(this).show();
    })
    $('#progbar').ajaxStop(function () {
        $(this).hide();
    })

    // Record-------------------------------------------------------
    $("#view").addClass('disabled');
    $('#view').removeClass('btn-main');

    $('#addsampleimage').click(function () {
        proj = document.getElementById('samp_exp_id').value;
        id = document.getElementById('samp_id').value
        window.open(siteurl+'sample/upload_image/' + proj + '/' + id, '', 'left=500,top=500,width=400px,height=400px,location=no,menubar=no,resizeable=no,scrollbars=no,titlebar=no,status=no,toolbar=no');
    });

    $('#addcultureimage').click(function () {
        id = document.getElementById('cult_id').value;
        window.open(siteurl+'culture/upload_image/' + id, '', 'left=500,top=500,width=400px,height=400px,location=no,menubar=no,resizeable=no,scrollbars=no,titlebar=no,status=no,toolbar=no');
    });

    // Search ------------------------------------------------------
    $('#searchCulture').click(function () {
        $('#results').empty();
        var data = $('#searchform').serializeArray();
        $('#results').load(siteurl+'culture/do_search', data, function () {
            sessionStorage.setItem('stored', 1);
            sessionStorage.setItem('cultquery', $('#omnibar').val());
            sessionStorage.setItem('cultfilter', $('input[name=filter]:checked').val());
        });
    });

    $('#searchSample').click(function () {
        $('#results').empty();
        var data = $('#searchform').serializeArray();
        $('#results').load(siteurl+'sample/do_search', data, function () {
            sessionStorage.setItem('stored', 1);
            sessionStorage.setItem('sampquery', $('#omnibar').val());
            sessionStorage.setItem('sampfilter', $('input[name=filter]:checked').val());
        });
    });

    if (sessionStorage.stored && (location.pathname == siteurl+'culture/' || location.pathname == siteurl+'sample/' || location.pathname == siteurl+'culture' || location.pathname == siteurl+'sample')) {
        var href = window.location.pathname;
        href = href.split('/');

        var id = 0;
        jQuery.each(href,function(i, path) {
           if(path === 'sample' || path === 'culture') {id = i; return false;}
        });

        $('#results').empty();
        $('#progbar').show();

        if ($('#culture').attr('class') == 'active') {
            data = {
                'query': sessionStorage.cultquery,
                'filter': sessionStorage.cultfilter
            };
            $('#results').load(siteurl + href[id] + '/do_search', data, function () {
                $('#progbar').hide();
            });
            $('#omnibar').val(sessionStorage.cultquery);
            $('input[name=filter]').filter('[value=' + sessionStorage.cultfilter + ']').prop('checked', 'checked');
        } else {
            data = {
                'query': sessionStorage.sampquery,
                'filter': sessionStorage.sampfilter
            };
            $('#results').load(siteurl + href[id] + '/do_search', data, function () {
                $('#progbar').hide();
            });
            $('#omnibar').val(sessionStorage.sampquery);
            $('input[name=filter]').filter('[value=' + sessionStorage.sampfilter + ']').prop('checked', 'checked');
        }
    }

    if (location.pathname == siteurl+'culture/recent/' || location.pathname == siteurl+'sample/recent/' || location.pathname == siteurl+'culture/recent' || location.pathname == siteurl+'sample/recent') {
        var href = window.location.pathname;
        href = href.split('/');

        var id = 0;
        jQuery.each(href,function(i, path) {
           if(path === 'sample' || path === 'culture') {id = i; return false;}
        });

        $('#results').empty();
        $('#progbar').show();
        data = {
            'query': 'none',
            'filter': 'recent'
        };
        $('#results').load(siteurl + href[id] + '/do_search', data, function () {
            $('#progbar').hide();
        });
    }

    //Create/edit --------------------------------------------------
    var vials = $('#vials legend').length;
    $('#addvial').click(function () {
        vials++;

        var form = ['<legend>Vial ' + vials + '</legend>',
            '
',
            '
',
            'Vial ID',
            '
<input type="text" onblur="" style="width:120px;" name="vial[' + vials + '][VIAL_ID]" maxlength="10" value="">
',
            '
',
            '
',
            'Vial Storage location',
            '
<input type="text" onblur="" name="vial[' + vials + '][VIAL_STOR_LOC]" maxlength="20" value="">
',
            '
',
            '
',
            'Growth Temperature',
            '
<input type="text" onblur="" name="vial[' + vials + '][VIAL_GROWTH_TEMP]" maxlength="20" value="">
',
            '
',
            '
',
            '
',
            '
',
            'Growth Type',
            '
<input type="text" onblur="" style="width:686px;" name="vial[' + vials + '][VIAL_GROWTH_TYPE]" maxlength="60" value="">
',
            '
',
            '
',
            '
',
            '
',
            'Vial Notes',
            '<textarea rows="1" name="vial[' + vials + '][VIAL_NOTES]" style=" width: 686px; resize:vertical;"></textarea>',
            '
',
            '
'
        ].join('\n');

        $('#vials').append(form);
    });

    var dnarna = $('#dnarna legend').length;
    $('#adddnarna').click(function () {
        dnarna++;

        var form = ['<legend>Genetic Information ' + dnarna + '</legend>',
            '
',
            '
',
            'Identification Number',
            '
<input type="text" onblur="" name="dnarna[' + dnarna + '][DNARNA_ID]" maxlength="10" value="">
',
            '
',
            '
',
            '
',
            '',
            '<input type="radio" name="dnarna[' + dnarna + '][DNARNA_TYPE]" id="optionsRadios1" value="DNA" checked>',
            'DNA',
            '',
            '
',
            '
',
            '',
            '<input type="radio" name="dnarna[' + dnarna + '][DNARNA_TYPE]" id="optionsRadios2" value="RNA" >',
            'RNA',
            '',
            '
',
            '
',
            '
',
            'Gen Bank Number',
            '
<input type="text" onblur="" style="width:325px;" maxlength="40" name="dnarna[' + dnarna + '][DNARNA_GBANKNUM]" value="">
',
            '
',
            '
	',

            '
',
            '
',
            'Date of Extraction',
            '
<input type="text" onblur="" maxlength="10" name="dnarna[' + dnarna + '][DNARNA_DATE]" placeholder="YYYY-MM-DD" value="">
',
            '
',
            '
',
            'Volume of Solution',
            '
<input type="text" onblur="" maxlength="10" name="dnarna[' + dnarna + '][DNARNA_VOL]" value="">
',
            '
	',
            '
',
            'Concentration of Solution',
            '
<input type="text" onblur="" maxlength="10" name="dnarna[' + dnarna + '][DNARNA_CONC]" value="">
',
            '
',
            '
',
            '
',
            '
',
            'Comments',
            '
<textarea rows="1" name="dnarna[' + dnarna + '][DNARNA_NOTES]" style="width: 686px; resize:vertical;"></textarea>
',
            '
',
            '
',

            '
',
            '
',
            'Image description',
            '
<input type="text" onblur="" name="dnarna[' + dnarna + '][DNARNA_IMG_CAP]" maxlength="20"  style="width:160px;" value="">
',
            '
',
            '
',
            'File:',
            '
<input type="file" name="dnarna[' + dnarna + '][DNARNA_IMG_PATH]" id="">

',
            '
',
            '
'
        ].join('\n');

        $('#dnarna').append(form);
    });

    //Form submission ----------------------------------------------
    $('#submitCulture').click(function () {
        $('#message').empty();
        var data = $('#createForm').serializeArray();
        $('#message').load(siteurl+'culture/do_create', data);
    });

    $('#submitSample').click(function () {
        $('#message').empty();
        var data = $('#createForm').serializeArray();
        $('#message').load(siteurl+'sample/do_create', data);
    });

    $('#editCulture').click(function () {
        $('#message').empty();
        var data = $('#createForm').serializeArray();
        $('#message').load(siteurl+'culture/do_edit/', data);
    });

    $('#editSample').click(function () {
        $('#message').empty();
        var data = $('#createForm').serializeArray();
        $('#message').load(siteurl+'sample/do_edit/', data);
    });

    $('#submitLogin').click(function () {
        $('#message').empty();
        var data = $('#loginForm').serializeArray();
        $('#message').load(siteurl+'login/do_login', data);
    });

    $('#submitUserLogin').click(function () {
        $('#message').empty();
        var data = $('#userForm').serializeArray();
        $('#usermgmt').modal('hide');
        $('#message').load(siteurl+'login/do_login', data);
    });

    //Export/Import ------------------------------------------------
    $('#startexport').click(function () {
        var href = window.location.pathname;
        href = href.split('/');
        var id = 0;
        jQuery.each(href,function(i, path) {
           if(path === "sample" || path === "culture") {id = i; return false;}
        });

        var data = $('#projectform').serialize();
        $.ajax({
            url: siteurl + href[id] + '/do_export',
            data: data,
            type: 'POST',
            success: function (html) {
                $('.log').append(html);
                var textarea = document.getElementById('log');
                textarea.scrollTop = textarea.scrollHeight;
            }
        });

    });

    $('#startimport').click(function() {
        var href = window.location.pathname;
        href = href.split('/');
        var id = 0;
        jQuery.each(href,function(i, path) {
           if(path === "sample" || path === "culture") {id = i; return false;}
        });

        var data = new FormData();
        jQuery.each($('#userfile')[0].files, function(i, file) {
            data.append('file-' + i, file);
        });

        $.ajax({
            url: siteurl + href[id] + '/do_import',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(html) {
                $('.log').append(html);
                var textarea = document.getElementById('log');
                textarea.scrollTop = textarea.scrollHeight;
            }
        });
    });

    //User Management ----------------------------------------------
    $("#clear-btn").click(function () {
        $("#userbox").load(siteurl+"user/create");
    });

});

//Functions ========================================================

//Search ----------------------------------------------------------

function highlightCell(row) {
    $(".highlight").removeClass("highlight");
    $(row).addClass("highlight");
    var href = window.location.pathname;
    href = href.split('/');
    var a = document.getElementById('view');
    a.href = siteurl + $.trim(href[1]) + "/view/" + row.id;
    $("#view").removeClass('disabled');
    $("#view").addClass('btn-main');
}

//User Management -------------------------------------------------

function selectUser(row) {
    $(".highlight").removeClass("highlight");
    $(row).addClass("highlight");
    id = $(row).attr('id');
    $("#userbox").load(siteurl+"user/update/" + id);
}

function clearForm() {
    $("#userbox").load(siteurl+'user/create');
}

function clearFeedback() {
    $("#userfeedback").empty();
}

function createUser() {
    clearFeedback();
    var data = $("form").serializeArray();

    $("#userfeedback").load(siteurl+"user/do_create", data, function () {
        $("#userTable").load(siteurl+"user/listUsers");
    });
}

function updateUser() {
    clearFeedback();
    var data = $("form").serializeArray();

    $("#userfeedback").load(siteurl+"user/do_update", data);
    $("#userTable").load(siteurl+"user/listUsers");
}

function deleteUser() {
    clearFeedback();
    var id = $('.highlight').attr('id');
    $("#userfeedback").load(siteurl+"user/do_delete/" + id, function () {
        $("#userTable").load(siteurl+"user/listUsers");
    });
    clearForm();
}<commit_msg>more testing bugs<commit_after>/**
 * Laboratory Information Indexing System
 *
 * An open source mini LIMS for metadata organisation and archival purposes
 *
 * @author      Matt Forster / @frostyforster
 * @copyright   Copyright (c) 2013, Matthew S. Forster
 * @license     MIT (./license.txt)
 * @link        http://github.com/forstermatth/liis
 * @since       Version 1.0
 * @filesource
 */

 /* ------------------------------------------------------------------------ */

/**
 * main.js
 *
 * all of the javascript used in the application
 *
 * @category    LIIS-View
 * @author      Matt Forster / @frostyforster
 * @link        http://github.com/forstermatth/liis
 */

//Procedues ==================================================
$(document).ready(function () {

     //Progress bar -------------------------------------------------
    $('#progbar').hide()

    $('#progbar').ajaxStart(function () {
        $(this).show();
    })
    $('#progbar').ajaxStop(function () {
        $(this).hide();
    })

    // Record-------------------------------------------------------
    $("#view").addClass('disabled');
    $('#view').removeClass('btn-main');

    $('#addsampleimage').click(function () {
        proj = document.getElementById('samp_exp_id').value;
        id = document.getElementById('samp_id').value
        window.open(siteurl+'sample/upload_image/' + proj + '/' + id, '', 'left=500,top=500,width=400px,height=400px,location=no,menubar=no,resizeable=no,scrollbars=no,titlebar=no,status=no,toolbar=no');
    });

    $('#addcultureimage').click(function () {
        id = document.getElementById('cult_id').value;
        window.open(siteurl+'culture/upload_image/' + id, '', 'left=500,top=500,width=400px,height=400px,location=no,menubar=no,resizeable=no,scrollbars=no,titlebar=no,status=no,toolbar=no');
    });

    // Search ------------------------------------------------------
    $('#searchCulture').click(function () {
        $('#results').empty();
        var data = $('#searchform').serializeArray();
        $('#results').load(siteurl+'culture/do_search', data, function () {
            sessionStorage.setItem('stored', 1);
            sessionStorage.setItem('cultquery', $('#omnibar').val());
            sessionStorage.setItem('cultfilter', $('input[name=filter]:checked').val());
        });
    });

    $('#searchSample').click(function () {
        $('#results').empty();
        var data = $('#searchform').serializeArray();
        $('#results').load(siteurl+'sample/do_search', data, function () {
            sessionStorage.setItem('stored', 1);
            sessionStorage.setItem('sampquery', $('#omnibar').val());
            sessionStorage.setItem('sampfilter', $('input[name=filter]:checked').val());
        });
    });

    if (sessionStorage.stored && (location.pathname == siteurl+'culture/' || location.pathname == siteurl+'sample/' || location.pathname == siteurl+'culture' || location.pathname == siteurl+'sample')) {
        var href = window.location.pathname;
        href = href.split('/');

        var id = 0;
        jQuery.each(href,function(i, path) {
           if(path === 'sample' || path === 'culture') {id = i; return false;}
        });

        $('#results').empty();
        $('#progbar').show();

        if ($('#culture').attr('class') == 'active') {
            data = {
                'query': sessionStorage.cultquery,
                'filter': sessionStorage.cultfilter
            };
            $('#results').load(siteurl + href[id] + '/do_search', data, function () {
                $('#progbar').hide();
            });
            $('#omnibar').val(sessionStorage.cultquery);
            $('input[name=filter]').filter('[value=' + sessionStorage.cultfilter + ']').prop('checked', 'checked');
        } else {
            data = {
                'query': sessionStorage.sampquery,
                'filter': sessionStorage.sampfilter
            };
            $('#results').load(siteurl + href[id] + '/do_search', data, function () {
                $('#progbar').hide();
            });
            $('#omnibar').val(sessionStorage.sampquery);
            $('input[name=filter]').filter('[value=' + sessionStorage.sampfilter + ']').prop('checked', 'checked');
        }
    }

    if (location.pathname == siteurl+'culture/recent/' || location.pathname == siteurl+'sample/recent/' || location.pathname == siteurl+'culture/recent' || location.pathname == siteurl+'sample/recent') {
        var href = window.location.pathname;
        href = href.split('/');

        var id = 0;
        jQuery.each(href,function(i, path) {
           if(path === 'sample' || path === 'culture') {id = i; return false;}
        });

        $('#results').empty();
        $('#progbar').show();
        data = {
            'query': 'none',
            'filter': 'recent'
        };
        $('#results').load(siteurl + href[id] + '/do_search', data, function () {
            $('#progbar').hide();
        });
    }

    //Create/edit --------------------------------------------------
    var vials = $('#vials legend').length;
    $('#addvial').click(function () {
        vials++;

        var form = ['<legend>Vial ' + vials + '</legend>',
            '
',
            '
',
            'Vial ID',
            '
<input type="text" onblur="" style="width:120px;" name="vial[' + vials + '][VIAL_ID]" maxlength="10" value="">
',
            '
',
            '
',
            'Vial Storage location',
            '
<input type="text" onblur="" name="vial[' + vials + '][VIAL_STOR_LOC]" maxlength="20" value="">
',
            '
',
            '
',
            'Growth Temperature',
            '
<input type="text" onblur="" name="vial[' + vials + '][VIAL_GROWTH_TEMP]" maxlength="20" value="">
',
            '
',
            '
',
            '
',
            '
',
            'Growth Type',
            '
<input type="text" onblur="" style="width:686px;" name="vial[' + vials + '][VIAL_GROWTH_TYPE]" maxlength="60" value="">
',
            '
',
            '
',
            '
',
            '
',
            'Vial Notes',
            '<textarea rows="1" name="vial[' + vials + '][VIAL_NOTES]" style=" width: 686px; resize:vertical;"></textarea>',
            '
',
            '
'
        ].join('\n');

        $('#vials').append(form);
    });

    var dnarna = $('#dnarna legend').length;
    $('#adddnarna').click(function () {
        dnarna++;

        var form = ['<legend>Genetic Information ' + dnarna + '</legend>',
            '
',
            '
',
            'Identification Number',
            '
<input type="text" onblur="" name="dnarna[' + dnarna + '][DNARNA_ID]" maxlength="10" value="">
',
            '
',
            '
',
            '
',
            '',
            '<input type="radio" name="dnarna[' + dnarna + '][DNARNA_TYPE]" id="optionsRadios1" value="DNA" checked>',
            'DNA',
            '',
            '
',
            '
',
            '',
            '<input type="radio" name="dnarna[' + dnarna + '][DNARNA_TYPE]" id="optionsRadios2" value="RNA" >',
            'RNA',
            '',
            '
',
            '
',
            '
',
            'Gen Bank Number',
            '
<input type="text" onblur="" style="width:325px;" maxlength="40" name="dnarna[' + dnarna + '][DNARNA_GBANKNUM]" value="">
',
            '
',
            '
	',

            '
',
            '
',
            'Date of Extraction',
            '
<input type="text" onblur="" maxlength="10" name="dnarna[' + dnarna + '][DNARNA_DATE]" placeholder="YYYY-MM-DD" value="">
',
            '
',
            '
',
            'Volume of Solution',
            '
<input type="text" onblur="" maxlength="10" name="dnarna[' + dnarna + '][DNARNA_VOL]" value="">
',
            '
	',
            '
',
            'Concentration of Solution',
            '
<input type="text" onblur="" maxlength="10" name="dnarna[' + dnarna + '][DNARNA_CONC]" value="">
',
            '
',
            '
',
            '
',
            '
',
            'Comments',
            '
<textarea rows="1" name="dnarna[' + dnarna + '][DNARNA_NOTES]" style="width: 686px; resize:vertical;"></textarea>
',
            '
',
            '
',

            '
',
            '
',
            'Image description',
            '
<input type="text" onblur="" name="dnarna[' + dnarna + '][DNARNA_IMG_CAP]" maxlength="20"  style="width:160px;" value="">
',
            '
',
            '
',
            'File:',
            '
<input type="file" name="dnarna[' + dnarna + '][DNARNA_IMG_PATH]" id="">

',
            '
',
            '
'
        ].join('\n');

        $('#dnarna').append(form);
    });

    //Form submission ----------------------------------------------
    $('#submitCulture').click(function () {
        $('#message').empty();
        var data = $('#createForm').serializeArray();
        $('#message').load(siteurl+'culture/do_create', data);
    });

    $('#submitSample').click(function () {
        $('#message').empty();
        var data = $('#createForm').serializeArray();
        $('#message').load(siteurl+'sample/do_create', data);
    });

    $('#editCulture').click(function () {
        $('#message').empty();
        var data = $('#createForm').serializeArray();
        $('#message').load(siteurl+'culture/do_edit/', data);
    });

    $('#editSample').click(function () {
        $('#message').empty();
        var data = $('#createForm').serializeArray();
        $('#message').load(siteurl+'sample/do_edit/', data);
    });

    $('#submitLogin').click(function () {
        $('#message').empty();
        var data = $('#loginForm').serializeArray();
        $('#message').load(siteurl+'login/do_login', data);
    });

    $('#submitUserLogin').click(function () {
        $('#message').empty();
        var data = $('#userForm').serializeArray();
        $('#usermgmt').modal('hide');
        $('#message').load(siteurl+'login/do_login', data);
    });

    //Export/Import ------------------------------------------------
    $('#startexport').click(function () {
        var href = window.location.pathname;
        href = href.split('/');
        var id = 0;
        jQuery.each(href,function(i, path) {
           if(path === "sample" || path === "culture") {id = i; return false;}
        });

        var data = $('#projectform').serialize();
        $.ajax({
            url: siteurl + href[id] + '/do_export',
            data: data,
            type: 'POST',
            success: function (html) {
                $('.log').append(html);
                var textarea = document.getElementById('log');
                textarea.scrollTop = textarea.scrollHeight;
            }
        });

    });

    $('#startimport').click(function() {
        var href = window.location.pathname;
        href = href.split('/');
        var id = 0;
        jQuery.each(href,function(i, path) {
           if(path === "sample" || path === "culture") {id = i; return false;}
        });

        var data = new FormData();
        jQuery.each($('#userfile')[0].files, function(i, file) {
            data.append('file-' + i, file);
        });

        $.ajax({
            url: siteurl + href[id] + '/do_import',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(html) {
                $('.log').append(html);
                var textarea = document.getElementById('log');
                textarea.scrollTop = textarea.scrollHeight;
            }
        });
    });

    //User Management ----------------------------------------------
    $("#clear-btn").click(function () {
        $("#userbox").load(siteurl+"user/create");
    });

});

//Functions ========================================================

//Search ----------------------------------------------------------

function highlightCell(row) {
    $(".highlight").removeClass("highlight");
    $(row).addClass("highlight");
    var href = window.location.pathname;
    href = href.split('/');
    var id = 0;
    jQuery.each(href,function(i, path) {
       if(path === "sample" || path === "culture") {id = i; return false;}
    });
    var a = document.getElementById('view');
    a.href = siteurl + $.trim(href[id]) + "/view/" + row.id;
    $("#view").removeClass('disabled');
    $("#view").addClass('btn-main');
}

//User Management -------------------------------------------------

function selectUser(row) {
    $(".highlight").removeClass("highlight");
    $(row).addClass("highlight");
    id = $(row).attr('id');
    $("#userbox").load(siteurl+"user/update/" + id);
}

function clearForm() {
    $("#userbox").load(siteurl+'user/create');
}

function clearFeedback() {
    $("#userfeedback").empty();
}

function createUser() {
    clearFeedback();
    var data = $("form").serializeArray();

    $("#userfeedback").load(siteurl+"user/do_create", data, function () {
        $("#userTable").load(siteurl+"user/listUsers");
    });
}

function updateUser() {
    clearFeedback();
    var data = $("form").serializeArray();

    $("#userfeedback").load(siteurl+"user/do_update", data);
    $("#userTable").load(siteurl+"user/listUsers");
}

function deleteUser() {
    clearFeedback();
    var id = $('.highlight').attr('id');
    $("#userfeedback").load(siteurl+"user/do_delete/" + id, function () {
        $("#userTable").load(siteurl+"user/listUsers");
    });
    clearForm();
}<|endoftext|>


<commit_before>'use strict';

app.controller('party/profile', [
  '$scope', 'displayService', 'party', 'pageService','constantService', 'modelService',
  function ($scope, display, party, page, constants, models) {
    var getUsers = function(volumes){

      var users = {};

      users.otherCollaborators = [];
      users.sponsors = $scope.party.parents;
      users.databrary = _.filter($scope.party.children, function(i) {
        return i.site > page.constants.permission.NONE && i.party.id != models.Login.user.id;
      });

      users.labOnly = _.filter($scope.party.children, function(i) {
        return i.site === page.constants.permission.NONE && i.party.id !== models.Login.user.id;
      });

      users.otherCollaborators = _(volumes).pluck('access').flatten().uniq(function(i) {
        return i.party.id;
      }).filter(function(u) {
        return u.individual === constants.permission.ADMIN && u.party.id !== models.Login.user.id;
      }).value();
      // The "value()" call is to actually force theb chain to work.

      var filterOnId = function(i) {
        return i.party.id;
      };

      var getDisplayName = function(i) {
        return i.party.alias || i.party.name;
      };

      _.each(users, function(_value, key) {
        users[key] = _(users[key]).uniq(filterOnId).sortBy(getDisplayName).value();
      });

      return users;
    };

    $scope.unselectAll = function() {

      // This is a quick helper function to make sure that the isSelected
      // class is set to empty and to avoid repeating code.
      var unSetSelected = function(v) {
        v.isSelected = '';
        if(v.v !== undefined) {

          v.v = _.map(v.v, function(a) {
            a.isSelected = '';
            return a;
          });
        }

        return v;
      };

      $scope.volumes.individual = _.map($scope.volumes.individual, unSetSelected);

      $scope.volumes.collaborator = _.map($scope.volumes.collaborator, unSetSelected);

      $scope.volumes.inherited = _.map($scope.volumes.inherited, unSetSelected);

      $scope.users.sponsors = _.map($scope.users.sponsors, unSetSelected);

      $scope.users.databrary = _.map($scope.users.databrary, unSetSelected);

      $scope.users.labOnly = _.map($scope.users.labOnly, unSetSelected);

      $scope.users.otherCollaborators = _.map($scope.users.otherCollaborators, unSetSelected);

    };

    $scope.clickVolume = function(volume) {

      $scope.unselectAll();
      volume.isSelected = 'volumeSelected';
      volume = _.flatten([volume.v || volume]);

      _.each(volume, function(vol) {
        _.each(vol.access, function(acc) {

          var userSelectFunction = function(user, index, array) {
            if(user.party.id == acc.party.id) {
              array[index].isSelected = 'userSelected';
            }
          };

          _.each($scope.users.sponsors,userSelectFunction);
          _.each($scope.users.databrary,userSelectFunction);
          _.each($scope.users.labOnly,userSelectFunction);
          _.each($scope.users.otherCollaborators,userSelectFunction);

        });
      });
    };

    // This should take in a user, then select volumes on each thing.
    $scope.clickUser = function(user) {
      $scope.unselectAll();
      user.isSelected = 'userSelected';
      var i;

      var compareFunction = function(value, key, array) {
        for(var j = 0; j < value.access.length; j++) {
          if(value.access[j].party.id === user.party.id) {
            array[key].isSelected = 'volumeSelected';
          }
        }
      };

      _.each($scope.volumes.individual, compareFunction);
      _.each($scope.volumes.collaborator, compareFunction);

      for(i = 0; i < $scope.volumes.inherited.length; i++) {
        _.each($scope.volumes.inherited[i].v, compareFunction);
      }
    };

    var getParents = function(parents) {
      return _.compact(_.map(parents, function(p) {
        if(p.member) {
          return _.zipObject(['p', 'v'], [p, []]);
        }
      }));
    };

    var getVolumes = function(volumes) {
      var tempVolumes = _.zipObject(['individual', 'collaborator'], [[], []]);

      tempVolumes.inherited = getParents(party.parents);

      _.each(volumes, function(v) {

        var isCurrent = _.find(v.access, function(r) {
          return r.party.id === models.Login.user.id;
        });

        if(isCurrent && isCurrent.children) v.network = 'network';

        if(isCurrent && isCurrent.individual == page.constants.permission.ADMIN) {
          // The "mini-object" with v and [v] is to make sure that the data is all
          // shaped the same, making looping over it *substantially* simpler.
          tempVolumes.individual.push(v);
        } else if(isCurrent) {
          tempVolumes.collaborator.push(v);
        } else {
          for (var i = 0; i < v.access.length; i++) {
            for (var j = 0; j < tempVolumes.inherited.length; j++) {
              if (v.access[i].children && v.access[i].party.id === tempVolumes.inherited[j].p.party.id) {
                tempVolumes.inherited[j].v.push(v);
              }
            }
          }
        }

      });

      var getDisplayName = function(i) {
        return i.alias || i.name;
      };

      tempVolumes.individual = _.sortBy(tempVolumes.individual, getDisplayName);
      tempVolumes.collaborator = _.sortBy(tempVolumes.collaborator, getDisplayName);

      return tempVolumes;

    };

    $scope.party = party;
    $scope.users = getUsers(party.volumes);
    $scope.volumes = getVolumes(party.volumes);
    console.log("Constants: ",constants);
    console.log($scope.users);

    $scope.page = page;
    $scope.profile = page.$location.path() === '/profile';
    display.title = party.name;

  }
]);
<commit_msg>Properly add othercollaborators.<commit_after>'use strict';

app.controller('party/profile', [
  '$scope', 'displayService', 'party', 'pageService','constantService', 'modelService',
  function ($scope, display, party, page, constants, models) {
    var getUsers = function(volumes){

      var users = {};

      users.otherCollaborators = [];
      users.sponsors = $scope.party.parents;
      console.log($scope.party);

      users.databrary = _.filter($scope.party.children, function(i) {
        return i.site > page.constants.permission.NONE && i.party.id != models.Login.user.id;
      });

      users.labOnly = _.filter($scope.party.children, function(i) {
        return i.site === page.constants.permission.NONE && i.party.id !== models.Login.user.id;
      });

      var tempArray = _($scope.volumes.individual).pluck('access').flatten().uniq(function(i){
        return i.party.id;
      }).filter(function(i){
        return i.party.id != models.Login.user.id;
      }).value();

      var arrayOfEverything = users.sponsors.concat(users.databrary).concat(users.labOnly);

      users.otherCollaborators = _.filter(tempArray, function(i){
        return !(_.find(arrayOfEverything, function(j){
          return i.party.id === j.party.id;
        }));
      });

      // users.otherCollaborators = _(volumes).pluck('access').flatten().uniq(function(i) {
      //   return i.party.id;
      // }).filter(function(u) {
      //   return u.individual >= constants.permission.READ && u.party.id !== models.Login.user.id;
      // }).value();
      // The "value()" call is to actually force theb chain to work.

      var filterOnId = function(i) {
        return i.party.id;
      };

      var getDisplayName = function(i) {
        return i.party.alias || i.party.name;
      };

      _.each(users, function(_value, key) {
        users[key] = _(users[key]).uniq(filterOnId).sortBy(getDisplayName).value();
      });

      return users;
    };

    $scope.unselectAll = function() {

      // This is a quick helper function to make sure that the isSelected
      // class is set to empty and to avoid repeating code.
      var unSetSelected = function(v) {
        v.isSelected = '';
        if(v.v !== undefined) {

          v.v = _.map(v.v, function(a) {
            a.isSelected = '';
            return a;
          });
        }

        return v;
      };

      $scope.volumes.individual = _.map($scope.volumes.individual, unSetSelected);

      $scope.volumes.collaborator = _.map($scope.volumes.collaborator, unSetSelected);

      $scope.volumes.inherited = _.map($scope.volumes.inherited, unSetSelected);

      $scope.users.sponsors = _.map($scope.users.sponsors, unSetSelected);

      $scope.users.databrary = _.map($scope.users.databrary, unSetSelected);

      $scope.users.labOnly = _.map($scope.users.labOnly, unSetSelected);

      $scope.users.otherCollaborators = _.map($scope.users.otherCollaborators, unSetSelected);

    };

    $scope.clickVolume = function(volume) {

      $scope.unselectAll();
      volume.isSelected = 'volumeSelected';
      volume = _.flatten([volume.v || volume]);

      _.each(volume, function(vol) {
        _.each(vol.access, function(acc) {
          var userSelectFunction = function(user, index, array) {
            if(user.party.id == acc.party.id) {
              array[index].isSelected = 'userSelected';
            }
          };

          _.each($scope.users.sponsors,userSelectFunction);
          _.each($scope.users.databrary,userSelectFunction);
          _.each($scope.users.labOnly,userSelectFunction);
          _.each($scope.users.otherCollaborators,userSelectFunction);

        });
      });
    };

    // This should take in a user, then select volumes on each thing.
    $scope.clickUser = function(user) {
      $scope.unselectAll();
      user.isSelected = 'userSelected';
      var i;

      var compareFunction = function(value, key, array) {
        for(var j = 0; j < value.access.length; j++) {
          if(value.access[j].party.id === user.party.id) {
            array[key].isSelected = 'volumeSelected';
          }
        }
      };

      _.each($scope.volumes.individual, compareFunction);
      _.each($scope.volumes.collaborator, compareFunction);

      for(i = 0; i < $scope.volumes.inherited.length; i++) {
        _.each($scope.volumes.inherited[i].v, compareFunction);
      }
    };

    var getParents = function(parents) {
      return _.compact(_.map(parents, function(p) {
        if(p.member) {
          return _.zipObject(['p', 'v'], [p, []]);
        }
      }));
    };

    var getVolumes = function(volumes) {
      var tempVolumes = _.zipObject(['individual', 'collaborator'], [[], []]);

      tempVolumes.inherited = getParents(party.parents);

      _.each(volumes, function(v) {

        var isCurrent = _.find(v.access, function(r) {
          return r.party.id === models.Login.user.id;
        });

        if(isCurrent && isCurrent.individual == page.constants.permission.ADMIN) {
          // The "mini-object" with v and [v] is to make sure that the data is all
          // shaped the same, making looping over it *substantially* simpler.
          tempVolumes.individual.push(v);
        } else if(isCurrent) {
          tempVolumes.collaborator.push(v);
        } else {
          for (var i = 0; i < v.access.length; i++) {
            for (var j = 0; j < tempVolumes.inherited.length; j++) {
              if (v.access[i].children && v.access[i].party.id === tempVolumes.inherited[j].p.party.id) {
                tempVolumes.inherited[j].v.push(v);
              }
            }
          }
        }

      });

      var getDisplayName = function(i) {
        return i.alias || i.name;
      };

      tempVolumes.individual = _.sortBy(tempVolumes.individual, getDisplayName);
      tempVolumes.collaborator = _.sortBy(tempVolumes.collaborator, getDisplayName);

      return tempVolumes;

    };

    $scope.party = party;
    $scope.volumes = getVolumes(party.volumes);
    $scope.users = getUsers(party.volumes);

    console.log("Constants: ",constants);
    console.log($scope.users);

    $scope.page = page;
    $scope.profile = page.$location.path() === '/profile';
    display.title = party.name;

  }
]);
<|endoftext|>


<commit_before>import jsTokens, { matchToToken } from "js-tokens";
import esutils from "esutils";
import Chalk from "chalk";

let deprecationWarningShown = false;

type Location = {
  column: number,
  line: number,
};

type NodeLocation = {
  end: Location,
  start: Location,
};

/**
 * Chalk styles for token types.
 */

function getDefs(chalk) {
  return {
    keyword: chalk.cyan,
    capitalized: chalk.yellow,
    jsx_tag: chalk.yellow,
    punctuator: chalk.yellow,
    // bracket:  intentionally omitted.
    number: chalk.magenta,
    string: chalk.green,
    regex: chalk.magenta,
    comment: chalk.grey,
    invalid: chalk.white.bgRed.bold,
    gutter: chalk.grey,
    marker: chalk.red.bold,
  };
}

/**
 * RegExp to test for newlines in terminal.
 */

const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;

/**
 * RegExp to test for what seems to be a JSX tag name.
 */

const JSX_TAG = /^[a-z][\w-]*$/i;

/**
 * RegExp to test for the three types of brackets.
 */

const BRACKET = /^[()[\]{}]$/;

/**
 * Get the type of token, specifying punctuator type.
 */

function getTokenType(match) {
  const [offset, text] = match.slice(-2);
  const token = matchToToken(match);

  if (token.type === "name") {
    if (esutils.keyword.isReservedWordES6(token.value)) {
      return "keyword";
    }

    if (
      JSX_TAG.test(token.value) &&
      (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")
    ) {
      return "jsx_tag";
    }

    if (token.value[0] !== token.value[0].toLowerCase()) {
      return "capitalized";
    }
  }

  if (token.type === "punctuator" && BRACKET.test(token.value)) {
    return "bracket";
  }

  return token.type;
}

/**
 * Highlight `text`.
 */

function highlight(defs: Object, text: string) {
  return text.replace(jsTokens, function(...args) {
    const type = getTokenType(args);
    const colorize = defs[type];
    if (colorize) {
      return args[0]
        .split(NEWLINE)
        .map(str => colorize(str))
        .join("\n");
    } else {
      return args[0];
    }
  });
}

/**
 * Extract what lines should be marked and highlighted.
 */

function getMarkerLines(
  loc: NodeLocation,
  source: Array<string>,
  opts: Object,
): { start: number, end: number, markerLines: Object } {
  const startLoc: Location = Object.assign(
    {},
    { column: 0, line: -1 },
    loc.start,
  );
  const endLoc: Location = Object.assign({}, startLoc, loc.end);
  const linesAbove = opts.linesAbove || 2;
  const linesBelow = opts.linesBelow || 3;

  const startLine = startLoc.line;
  const startColumn = startLoc.column;
  const endLine = endLoc.line;
  const endColumn = endLoc.column;

  let start = Math.max(startLine - (linesAbove + 1), 0);
  let end = Math.min(source.length, endLine + linesBelow);

  if (startLine === -1) {
    start = 0;
  }

  if (endLine === -1) {
    end = source.length;
  }

  const lineDiff = endLine - startLine;
  const markerLines = {};

  if (lineDiff) {
    for (let i = 0; i <= lineDiff; i++) {
      const lineNumber = i + startLine;

      if (!startColumn) {
        markerLines[lineNumber] = true;
      } else if (i === 0) {
        const sourceLength = source[lineNumber - 1].length;

        markerLines[lineNumber] = [startColumn, sourceLength - startColumn];
      } else if (i === lineDiff) {
        markerLines[lineNumber] = [0, endColumn];
      } else {
        const sourceLength = source[lineNumber - i].length;

        markerLines[lineNumber] = [0, sourceLength];
      }
    }
  } else {
    if (startColumn === endColumn) {
      if (startColumn) {
        markerLines[startLine] = [startColumn, 0];
      } else {
        markerLines[startLine] = true;
      }
    } else {
      markerLines[startLine] = [startColumn, endColumn - startColumn];
    }
  }

  return { start, end, markerLines };
}

export function codeFrameColumns(
  rawLines: string,
  loc: NodeLocation,
  opts: Object = {},
): string {
  const highlighted =
    (opts.highlightCode && Chalk.supportsColor) || opts.forceColor;
  let chalk = Chalk;
  if (opts.forceColor) {
    chalk = new Chalk.constructor({ enabled: true });
  }
  const maybeHighlight = (chalkFn, string) => {
    return highlighted ? chalkFn(string) : string;
  };
  const defs = getDefs(chalk);
  if (highlighted) rawLines = highlight(defs, rawLines);

  const lines = rawLines.split(NEWLINE);
  const { start, end, markerLines } = getMarkerLines(loc, lines, opts);

  const numberMaxWidth = String(end).length;

  const frame = lines
    .slice(start, end)
    .map((line, index) => {
      const number = start + 1 + index;
      const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
      const gutter = ` ${paddedNumber} | `;
      const hasMarker = markerLines[number];
      if (hasMarker) {
        let markerLine = "";
        if (Array.isArray(hasMarker)) {
          const markerSpacing = line
            .slice(0, Math.max(hasMarker[0] - 1, 0))
            .replace(/[^\t]/g, " ");
          const numberOfMarkers = hasMarker[1] || 1;

          markerLine = [
            "\n ",
            maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")),
            markerSpacing,
            maybeHighlight(defs.marker, "^").repeat(numberOfMarkers),
          ].join("");
        }
        return [
          maybeHighlight(defs.marker, ">"),
          maybeHighlight(defs.gutter, gutter),
          line,
          markerLine,
        ].join("");
      } else {
        return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
      }
    })
    .join("\n");

  if (highlighted) {
    return chalk.reset(frame);
  } else {
    return frame;
  }
}

/**
 * Create a code frame, adding line numbers, code highlighting, and pointing to a given position.
 */

export default function(
  rawLines: string,
  lineNumber: number,
  colNumber: ?number,
  opts: Object = {},
): string {
  if (!deprecationWarningShown) {
    deprecationWarningShown = true;

    const deprecationError = new Error(
      "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.",
    );
    deprecationError.name = "DeprecationWarning";

    if (process.emitWarning) {
      process.emitWarning(deprecationError);
    } else {
      console.warn(deprecationError);
    }
  }

  colNumber = Math.max(colNumber, 0);

  const location: NodeLocation = {
    start: { column: colNumber, line: lineNumber },
  };

  return codeFrameColumns(rawLines, location, opts);
}
<commit_msg>Make syntax highlighting for `@` and `#` nicer (#6550)<commit_after>import jsTokens, { matchToToken } from "js-tokens";
import esutils from "esutils";
import Chalk from "chalk";

let deprecationWarningShown = false;

type Location = {
  column: number,
  line: number,
};

type NodeLocation = {
  end: Location,
  start: Location,
};

/**
 * Chalk styles for token types.
 */

function getDefs(chalk) {
  return {
    keyword: chalk.cyan,
    capitalized: chalk.yellow,
    jsx_tag: chalk.yellow,
    punctuator: chalk.yellow,
    // bracket:  intentionally omitted.
    number: chalk.magenta,
    string: chalk.green,
    regex: chalk.magenta,
    comment: chalk.grey,
    invalid: chalk.white.bgRed.bold,
    gutter: chalk.grey,
    marker: chalk.red.bold,
  };
}

/**
 * RegExp to test for newlines in terminal.
 */

const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;

/**
 * RegExp to test for what seems to be a JSX tag name.
 */

const JSX_TAG = /^[a-z][\w-]*$/i;

/**
 * RegExp to test for the three types of brackets.
 */

const BRACKET = /^[()[\]{}]$/;

/**
 * Get the type of token, specifying punctuator type.
 */

function getTokenType(match) {
  const [offset, text] = match.slice(-2);
  const token = matchToToken(match);

  if (token.type === "name") {
    if (esutils.keyword.isReservedWordES6(token.value)) {
      return "keyword";
    }

    if (
      JSX_TAG.test(token.value) &&
      (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")
    ) {
      return "jsx_tag";
    }

    if (token.value[0] !== token.value[0].toLowerCase()) {
      return "capitalized";
    }
  }

  if (token.type === "punctuator" && BRACKET.test(token.value)) {
    return "bracket";
  }

  if (
    token.type === "invalid" &&
    (token.value === "@" || token.value === "#")
  ) {
    return "punctuator";
  }

  return token.type;
}

/**
 * Highlight `text`.
 */

function highlight(defs: Object, text: string) {
  return text.replace(jsTokens, function(...args) {
    const type = getTokenType(args);
    const colorize = defs[type];
    if (colorize) {
      return args[0]
        .split(NEWLINE)
        .map(str => colorize(str))
        .join("\n");
    } else {
      return args[0];
    }
  });
}

/**
 * Extract what lines should be marked and highlighted.
 */

function getMarkerLines(
  loc: NodeLocation,
  source: Array<string>,
  opts: Object,
): { start: number, end: number, markerLines: Object } {
  const startLoc: Location = Object.assign(
    {},
    { column: 0, line: -1 },
    loc.start,
  );
  const endLoc: Location = Object.assign({}, startLoc, loc.end);
  const linesAbove = opts.linesAbove || 2;
  const linesBelow = opts.linesBelow || 3;

  const startLine = startLoc.line;
  const startColumn = startLoc.column;
  const endLine = endLoc.line;
  const endColumn = endLoc.column;

  let start = Math.max(startLine - (linesAbove + 1), 0);
  let end = Math.min(source.length, endLine + linesBelow);

  if (startLine === -1) {
    start = 0;
  }

  if (endLine === -1) {
    end = source.length;
  }

  const lineDiff = endLine - startLine;
  const markerLines = {};

  if (lineDiff) {
    for (let i = 0; i <= lineDiff; i++) {
      const lineNumber = i + startLine;

      if (!startColumn) {
        markerLines[lineNumber] = true;
      } else if (i === 0) {
        const sourceLength = source[lineNumber - 1].length;

        markerLines[lineNumber] = [startColumn, sourceLength - startColumn];
      } else if (i === lineDiff) {
        markerLines[lineNumber] = [0, endColumn];
      } else {
        const sourceLength = source[lineNumber - i].length;

        markerLines[lineNumber] = [0, sourceLength];
      }
    }
  } else {
    if (startColumn === endColumn) {
      if (startColumn) {
        markerLines[startLine] = [startColumn, 0];
      } else {
        markerLines[startLine] = true;
      }
    } else {
      markerLines[startLine] = [startColumn, endColumn - startColumn];
    }
  }

  return { start, end, markerLines };
}

export function codeFrameColumns(
  rawLines: string,
  loc: NodeLocation,
  opts: Object = {},
): string {
  const highlighted =
    (opts.highlightCode && Chalk.supportsColor) || opts.forceColor;
  let chalk = Chalk;
  if (opts.forceColor) {
    chalk = new Chalk.constructor({ enabled: true });
  }
  const maybeHighlight = (chalkFn, string) => {
    return highlighted ? chalkFn(string) : string;
  };
  const defs = getDefs(chalk);
  if (highlighted) rawLines = highlight(defs, rawLines);

  const lines = rawLines.split(NEWLINE);
  const { start, end, markerLines } = getMarkerLines(loc, lines, opts);

  const numberMaxWidth = String(end).length;

  const frame = lines
    .slice(start, end)
    .map((line, index) => {
      const number = start + 1 + index;
      const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
      const gutter = ` ${paddedNumber} | `;
      const hasMarker = markerLines[number];
      if (hasMarker) {
        let markerLine = "";
        if (Array.isArray(hasMarker)) {
          const markerSpacing = line
            .slice(0, Math.max(hasMarker[0] - 1, 0))
            .replace(/[^\t]/g, " ");
          const numberOfMarkers = hasMarker[1] || 1;

          markerLine = [
            "\n ",
            maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")),
            markerSpacing,
            maybeHighlight(defs.marker, "^").repeat(numberOfMarkers),
          ].join("");
        }
        return [
          maybeHighlight(defs.marker, ">"),
          maybeHighlight(defs.gutter, gutter),
          line,
          markerLine,
        ].join("");
      } else {
        return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
      }
    })
    .join("\n");

  if (highlighted) {
    return chalk.reset(frame);
  } else {
    return frame;
  }
}

/**
 * Create a code frame, adding line numbers, code highlighting, and pointing to a given position.
 */

export default function(
  rawLines: string,
  lineNumber: number,
  colNumber: ?number,
  opts: Object = {},
): string {
  if (!deprecationWarningShown) {
    deprecationWarningShown = true;

    const deprecationError = new Error(
      "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.",
    );
    deprecationError.name = "DeprecationWarning";

    if (process.emitWarning) {
      process.emitWarning(deprecationError);
    } else {
      console.warn(deprecationError);
    }
  }

  colNumber = Math.max(colNumber, 0);

  const location: NodeLocation = {
    start: { column: colNumber, line: lineNumber },
  };

  return codeFrameColumns(rawLines, location, opts);
}
<|endoftext|>


<commit_before>/*
 * JQGyrate - Alpha v0.9 - 04/08/2013
 * https://github.com/puneetkay/JQGyrate/
 *
 * Copyright (c) 2013 Puneet Kalra
 * under the MIT license.
 */

(function($,window,undefined){

	$.fn.gyrate = function(options){

		function initialise(e,o){
			// Double check options here, or return false.
			// Once all validated, start gyrator.
			gyrator(e,o);
		}

		function gyrator(e,o){

			// Recursive calling.
			setTimeout(function(){
				//gyrator(e,o); // Currently disabled for development.
			},o.speed);
		}

		// Default values
		var defaults = {
			speed: 10000, // Speed of gyrator
			items: {}, // Items for gyrator
			dance: 'circle', // Dance type, circle, shuffle etc.
			style: 'fade', // Effects for gyrate, fade, rotateX, rotateY etc.
			target: 'html' // Target attribute of elements.
		};

		// Merge options with defaults.
		var data = $.extend(defaults, options);

		// Data object ready, Now head for logic
		return this.each(function(){
			var elem = $(this);
			if(elem == null)
				return false;

			initialise(elem, data);

		});

	}

})(jQuery,this);<commit_msg>Basic Gyrator done, working mode.<commit_after>/*
 * JQGyrate - Alpha v0.9 - 04/08/2013
 * https://github.com/puneetkay/JQGyrate/
 *
 * Copyright (c) 2013 Puneet Kalra
 * under the MIT license.
 */

(function($,window,undefined){

	$.fn.gyrate = function(options){

		function initialise(e,o){
			// Double check options here, or return false.
			// Once all validated, start gyrator.
			gyrator(e,o);
		}

		var index = -1;
		var elem;
		function gyrator(e,o){
			index++;
			if(index == o.items.length){index=0;}

			elem.animate({opacity:0.0},function(){
				elem.html(o.items[index]);
				elem.animate({opacity:1},function(){

					// Recursive calling.
					setTimeout(function(){
						gyrator(e,o); // Currently disabled for development.
					},o.speed);

		 		});
			});

		}

		// Default values
		var defaults = {
			speed: 1000, // Speed of gyrator
			items: {}, // Items for gyrator
			dance: 'circle', // Dance type, circle, shuffle etc.
			style: 'fade', // Effects for gyrate, fade, rotateX, rotateY etc.
			target: 'html' // Target attribute of elements.
		};

		// Merge options with defaults.
		var data = $.extend(defaults, options);

		// Data object ready, Now head for logic
		return this.each(function(){
			elem = $(this);
			if(elem == null)
				return false;

			initialise(elem, data);

		});

	}

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


<commit_before>'use strict';

var app = angular.module('PyFetch', ['ngRoute', 'angular-loading-bar', 'ui.bootstrap']);

app.config(['$routeProvider', '$locationProvider', 'cfpLoadingBarProvider', '$httpProvider',
    function ($routeProvider, $locationProvider, cfpLoadingBarProvider, $httpProvider) {
        if (!$httpProvider.defaults.headers.get) {
            $httpProvider.defaults.headers.get = {};
        }
        $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
        $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
        $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
        $locationProvider.html5Mode(true);
        cfpLoadingBarProvider.includeSpinner = false;
        $routeProvider.
            when('/project/edit/:projectName', {
                templateUrl: 'component/project-edit',
                controller: 'projectEditCtrl'
            }).
            when('/project/add/new', {
                templateUrl: 'component/project-edit',
                controller: 'projectAddCtrl'
            }).
            when('/project', {
                templateUrl: 'component/project',
                controller: 'projectCtrl'
            }).
            when('/slave', {
                templateUrl: 'component/slave',
                controller: 'slaveCtrl'
            }).
            when('/slave/task/:ip', {
                templateUrl: 'component/task',
                controller: 'slaveTaskCtrl'
            }).
            when('/project/result/:projectName', {
                templateUrl: 'component/result',
                controller: 'projectResultCtrl'
            }).
            when('/project/task/:projectName', {
                templateUrl: 'component/task',
                controller: 'projectTaskCtrl'
            }).
            otherwise({
                redirectTo: '/project'
            });
    }]);

app.controller('projectAddCtrl', ['$scope', '$rootScope', '$http', '$location', 'appAlert', function ($scope, $rootScope, $http, $location, appAlert) {
    load_and_exec_CodeMirror();
    $scope.input_write = true;
    //设置区域的折叠
    $scope.status = {
        isFirstOpen: true,
        isFirstDisabled: false,
        open: true
    };

    //表单与提交
    $scope.project = {};
    $scope.save_project = function () {
        var formData = $scope.project;
        formData['code'] = window._editor.getValue();//从全局变量_editor中获取code
        $http.post('/api/project/save', formData).success(function (data) {
            if (data.success) {
                $location.url('/project/edit/' + $scope.project.name);
                appAlert.add('success', data.msg, 3000);
            } else {
                appAlert.add('danger', data.msg, 5000);
            }
        });
    };
}]);

app.controller('projectEditCtrl', ['$scope', '$routeParams', '$http', 'appAlert', 'appModal', function ($scope, $routeParams, $http, appAlert, appModal) {
    load_and_exec_CodeMirror();
    $scope.showTest = true;
    $scope.projectName = $routeParams.projectName;

    $scope.project = {};

    $http.get('/api/project/' + $scope.projectName).success(function (data) {
        $scope.project = data;
        document.getElementById('project_code_editor').value = data.code;
    });

    //表单与提交
    $scope.save_project = function () {

        appModal.open();

        var formData = $scope.project;
        formData['code'] = window._editor.getValue();//从全局变量_editor中获取code
        formData['edit'] = true; //标识为编辑计划
        $http.post('/api/project/save', formData).success(function (data) {
            if (data.success) {
                appAlert.add('success', data.msg, 3000);
            } else {
                appAlert.add('danger', data.msg, 5000);
            }
        });
    };

    $scope.exec_test = function () {
        var formData = $scope.project;
        formData['code'] = window._editor.getValue();//从全局变量_editor中获取code
        formData['edit'] = true; //标识为编辑计划
        $http.post('/api/project/exec_test', formData).success(function (data) {
            if (data.success) {
                appAlert.add('success', data.msg, 3000);
            } else {
                appAlert.add('danger', data.msg, 5000);
            }
        });
    };
}]);

app.controller('projectResultCtrl', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
    $http.get('/api/result/' + $routeParams.projectName).success(function (data) {
        $scope.th_title = [];
        for (var key in data[0]) {
            $scope.th_title.push(key);
        }
        $scope.results = data;
    });
}]);

app.controller('slaveTaskCtrl', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
    $http.get('/api/slave/' + $routeParams.ip).success(function (data) {
        $scope.tasks = data;
    });
}]);

app.controller('projectTaskCtrl', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
    $http.get('/api/task/' + $routeParams.projectName).success(function (data) {
        $scope.tasks = data;
    });
}]);

app.controller('projectCtrl', function ($scope, $http) {
    var load = function (manual) {
        manual && ($scope.show_load_icon = true);

        $http.get('/api/project').success(function (data) {
            setTimeout(function () {
                $scope.show_load_icon = false;
            }, 1);
            $scope.projects = data;
        });
    };
    load(false);

    $scope.refresh = function () {
        load(true);
    };
});

app.controller('slaveCtrl', ['$scope', '$routeParams', '$http', function ($scope, $routeParams, $http) {
    var load = function (manual) {
        manual && ($scope.show_load_icon = true);

        $http.get('/api/slave').success(function (data) {
            setTimeout(function () {
                $scope.show_load_icon = false;
            }, 1);
            $scope.slave = data;
        });
    };
    load(false);

    $scope.refresh = function () {
        load(true);
    };
}]);

app.controller('NavBarCtrl', function ($scope, $location) {
    $scope.isActive = function (route) {
        return $location.path().indexOf(route) === 0;
    }
});

app.controller('scrollToTop', function ($scope) {
    $scope.toTop = function () {
        document.body.scrollTop && (document.body.scrollTop = 0);
        document.documentElement.scrollTop && (document.documentElement.scrollTop = 0);
    }
});

//todo 已经使用模态框替换, 请删除该服务以及相应的js依赖
app.factory('appAlert', [
    '$rootScope', '$timeout', '$sce', function ($rootScope, $timeout, $sce) {
        var alertService;
        $rootScope.alerts = [];
        return alertService = {
            add: function (type, msg, timeout) {
                $rootScope.alerts.push({
                    type: type,
                    msg: $sce.trustAsHtml(msg),
                    close: function () {
                        return alertService.closeAlert(this);
                    }
                });

                if (timeout) {
                    $timeout(function () {
                        alertService.closeAlert(this);
                    }, timeout);
                }
            },
            closeAlert: function (alert) {
                return this.closeAlertIdx($rootScope.alerts.indexOf(alert));
            },
            closeAlertIdx: function (index) {
                return $rootScope.alerts.splice(index, 1);
            },
            clear: function () {
                $rootScope.alerts = [];
            }
        };
    }
]);
function load_and_exec_CodeMirror(defaultValue) {
    $script(["/static/js/codemirror.js"], function () {
        $script(["/static/js/codemirror-component.min.js"], function () {
            window._editor = CodeMirror.fromTextArea(document.getElementById("project_code_editor"), {
                lineNumbers: true,
                styleActiveLine: true,
                autofocus: true,
                tabSize: 4
            });

            defaultValue && window._editor.setValue(defaultValue)
        });
    });
}

app.factory('appModal', function ($rootScope, $modal) {
    return {
        open: function (size,sure,cancel) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'myModalContent.html',
                controller: 'ModalInstanceCtrl',
                size: size,
                resolve: {
                    items: function () {
                        return ['item1', 'item2', 'item3'];
                    }
                }
            });

            modalInstance.result.then(function (selectedItem) {
                alert(selectedItem);
                $rootScope.selected = selectedItem;
            }, function (data) {
                alert(data);
                console.log('Modal dismissed at: ' + new Date());
            });
        }
    }
});

//app.controller('ModalCtrl', function ($scope, $modal, $log) {
//    $scope.items = ['item1', 'item2', 'item3'];
//
//    $scope.animationsEnabled = true;
//
//    $scope.open = function (size) {
//
//        var modalInstance = $modal.open({
//            animation: $scope.animationsEnabled,
//            templateUrl: 'myModalContent.html',
//            controller: 'ModalInstanceCtrl',
//            size: size,
//            resolve: {
//                items: function () {
//                    return $scope.items;
//                }
//            }
//        });
//
//        modalInstance.result.then(function (selectedItem) {
//            $scope.selected = selectedItem;
//        }, function () {
//            $log.info('Modal dismissed at: ' + new Date());
//        });
//    };
//
//    $scope.toggleAnimation = function () {
//        $scope.animationsEnabled = !$scope.animationsEnabled;
//    };
//});

// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.

app.controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {

    $scope.items = items;
    $scope.selected = {
        item: $scope.items[0]
    };

    $scope.ok = function () {
        $modalInstance.close($scope.selected.item);
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
});<commit_msg>test bootstrap modal<commit_after>'use strict';

var app = angular.module('PyFetch', ['ngRoute', 'angular-loading-bar', 'ui.bootstrap']);

app.config(['$routeProvider', '$locationProvider', 'cfpLoadingBarProvider', '$httpProvider',
    function ($routeProvider, $locationProvider, cfpLoadingBarProvider, $httpProvider) {
        if (!$httpProvider.defaults.headers.get) {
            $httpProvider.defaults.headers.get = {};
        }
        $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
        $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
        $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
        $locationProvider.html5Mode(true);
        cfpLoadingBarProvider.includeSpinner = false;
        $routeProvider.
            when('/project/edit/:projectName', {
                templateUrl: 'component/project-edit',
                controller: 'projectEditCtrl'
            }).
            when('/project/add/new', {
                templateUrl: 'component/project-edit',
                controller: 'projectAddCtrl'
            }).
            when('/project', {
                templateUrl: 'component/project',
                controller: 'projectCtrl'
            }).
            when('/slave', {
                templateUrl: 'component/slave',
                controller: 'slaveCtrl'
            }).
            when('/slave/task/:ip', {
                templateUrl: 'component/task',
                controller: 'slaveTaskCtrl'
            }).
            when('/project/result/:projectName', {
                templateUrl: 'component/result',
                controller: 'projectResultCtrl'
            }).
            when('/project/task/:projectName', {
                templateUrl: 'component/task',
                controller: 'projectTaskCtrl'
            }).
            otherwise({
                redirectTo: '/project'
            });
    }]);

app.controller('projectAddCtrl', ['$scope', '$rootScope', '$http', '$location', 'appAlert', function ($scope, $rootScope, $http, $location, appAlert) {
    load_and_exec_CodeMirror();
    $scope.input_write = true;
    //设置区域的折叠
    $scope.status = {
        isFirstOpen: true,
        isFirstDisabled: false,
        open: true
    };

    //表单与提交
    $scope.project = {};
    $scope.save_project = function () {
        var formData = $scope.project;
        formData['code'] = window._editor.getValue();//从全局变量_editor中获取code
        $http.post('/api/project/save', formData).success(function (data) {
            if (data.success) {
                $location.url('/project/edit/' + $scope.project.name);
                appAlert.add('success', data.msg, 3000);
            } else {
                appAlert.add('danger', data.msg, 5000);
            }
        });
    };
}]);

app.controller('projectEditCtrl', ['$scope', '$routeParams', '$http', 'appAlert', 'appModal', function ($scope, $routeParams, $http, appAlert, appModal) {
    load_and_exec_CodeMirror();
    $scope.showTest = true;
    $scope.projectName = $routeParams.projectName;

    $scope.project = {};

    $http.get('/api/project/' + $scope.projectName).success(function (data) {
        $scope.project = data;
        document.getElementById('project_code_editor').value = data.code;
    });

    //表单与提交
    $scope.save_project = function () {

        appModal.open();

        var formData = $scope.project;
        formData['code'] = window._editor.getValue();//从全局变量_editor中获取code
        formData['edit'] = true; //标识为编辑计划
        $http.post('/api/project/save', formData).success(function (data) {
            if (data.success) {
                appAlert.add('success', data.msg, 3000);
            } else {
                appAlert.add('danger', data.msg, 5000);
            }
        });
    };

    $scope.exec_test = function () {
        var formData = $scope.project;
        formData['code'] = window._editor.getValue();//从全局变量_editor中获取code
        formData['edit'] = true; //标识为编辑计划
        $http.post('/api/project/exec_test', formData).success(function (data) {
            if (data.success) {
                appAlert.add('success', data.msg, 3000);
            } else {
                appAlert.add('danger', data.msg, 5000);
            }
        });
    };
}]);

app.controller('projectResultCtrl', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
    $http.get('/api/result/' + $routeParams.projectName).success(function (data) {
        $scope.th_title = [];
        for (var key in data[0]) {
            $scope.th_title.push(key);
        }
        $scope.results = data;
    });
}]);

app.controller('slaveTaskCtrl', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
    $http.get('/api/slave/' + $routeParams.ip).success(function (data) {
        $scope.tasks = data;
    });
}]);

app.controller('projectTaskCtrl', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
    $http.get('/api/task/' + $routeParams.projectName).success(function (data) {
        $scope.tasks = data;
    });
}]);

app.controller('projectCtrl', function ($scope, $http) {
    var load = function (manual) {
        manual && ($scope.show_load_icon = true);

        $http.get('/api/project').success(function (data) {
            setTimeout(function () {
                $scope.show_load_icon = false;
            }, 1);
            $scope.projects = data;
        });
    };
    load(false);

    $scope.refresh = function () {
        load(true);
    };
});

app.controller('slaveCtrl', ['$scope', '$routeParams', '$http', function ($scope, $routeParams, $http) {
    var load = function (manual) {
        manual && ($scope.show_load_icon = true);

        $http.get('/api/slave').success(function (data) {
            setTimeout(function () {
                $scope.show_load_icon = false;
            }, 1);
            $scope.slave = data;
        });
    };
    load(false);

    $scope.refresh = function () {
        load(true);
    };
}]);

app.controller('NavBarCtrl', function ($scope, $location) {
    $scope.isActive = function (route) {
        return $location.path().indexOf(route) === 0;
    }
});

app.controller('scrollToTop', function ($scope) {
    $scope.toTop = function () {
        document.body.scrollTop && (document.body.scrollTop = 0);
        document.documentElement.scrollTop && (document.documentElement.scrollTop = 0);
    }
});

//todo 已经使用模态框替换, 请删除该服务以及相应的js依赖
app.factory('appAlert', [
    '$rootScope', '$timeout', '$sce', function ($rootScope, $timeout, $sce) {
        var alertService;
        $rootScope.alerts = [];
        return alertService = {
            add: function (type, msg, timeout) {
                $rootScope.alerts.push({
                    type: type,
                    msg: $sce.trustAsHtml(msg),
                    close: function () {
                        return alertService.closeAlert(this);
                    }
                });

                if (timeout) {
                    $timeout(function () {
                        alertService.closeAlert(this);
                    }, timeout);
                }
            },
            closeAlert: function (alert) {
                return this.closeAlertIdx($rootScope.alerts.indexOf(alert));
            },
            closeAlertIdx: function (index) {
                return $rootScope.alerts.splice(index, 1);
            },
            clear: function () {
                $rootScope.alerts = [];
            }
        };
    }
]);
function load_and_exec_CodeMirror(defaultValue) {
    $script(["/static/js/codemirror.js"], function () {
        $script(["/static/js/codemirror-component.min.js"], function () {
            window._editor = CodeMirror.fromTextArea(document.getElementById("project_code_editor"), {
                lineNumbers: true,
                styleActiveLine: true,
                autofocus: true,
                tabSize: 4
            });

            defaultValue && window._editor.setValue(defaultValue)
        });
    });
}

app.factory('appModal', function ($rootScope, $modal) {
    return {
        open: function (size,sure,cancel) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'myModalContent.html',
                controller: 'ModalInstanceCtrl',
                size: size,
                resolve: {
                    items: function () {
                        return ['item1', 'item2', 'item3'];
                    }
                }
            });

            modalInstance.result.then(function (selectedItem) {
                alert(selectedItem);
                $rootScope.selected = selectedItem;
            }, function (data) {
                alert(data);
                console.log('Modal dismissed at: ' + new Date());
            });
        }
    }
});

app.controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {

    $scope.items = items;
    $scope.selected = {
        item: $scope.items[0]
    };

    $scope.ok = function () {
        $modalInstance.close($scope.selected.item);
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
});<|endoftext|>


<commit_before>import RTabListItemContent from 'ui-library/components/r-tab-list-item/content/template';

export default RTabListItemContent;
<commit_msg>Correcting import path for tab-list-item/content<commit_after>import RTabListItemContent from 'ui-library/components/r-tab-list-item/content/component';

export default RTabListItemContent;
<|endoftext|>


<commit_before>/**
 * xGesture.js
 * https://github.com/kiinlam/xGesture
 */

; (function (window, $) {
    var isSupportTouch = 'ontouchend' in document ? true : false,
        _touchstart = isSupportTouch ? 'touchstart' : 'mousedown',
        _touchmove = isSupportTouch ? 'touchmove' : 'mousemove',
        _touchend = isSupportTouch ? 'touchend' : 'mouseup',
        touch = {},
        touchTimeout, tapTimeout, swipeTimeout, longTapTimeout,
        longTapDelay = 750,
        gesture;

    function direction(x1, x2, y1, y2) {
        return Math.abs(x1 - x2) >=
            Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down');
    }

    function longTap() {
        longTapTimeout = null;
        if (touch.last) {
            touch.el.trigger('longTap');
            touch = {};
        }
    }

    function cancelLongTap() {
        if (longTapTimeout) clearTimeout(longTapTimeout);
        longTapTimeout = null;
    }

    function cancelAll() {
        if (touchTimeout) clearTimeout(touchTimeout);
        if (tapTimeout) clearTimeout(tapTimeout);
        if (swipeTimeout) clearTimeout(swipeTimeout);
        if (longTapTimeout) clearTimeout(longTapTimeout);
        touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null;
        touch = {};
    }

    function isPrimaryTouch(event) {
        return (event.pointerType == 'touch' ||
            event.pointerType == event.MSPOINTER_TYPE_TOUCH)
            && event.isPrimary;
    }

    function isPointerEventType(e, type) {
        return (e.type == 'pointer' + type ||
            e.type.toLowerCase() == 'mspointer' + type);
    }

    (function () {
        var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType;

        if ('MSGesture' in window) {
            gesture = new MSGesture();
            gesture.target = document.body;
        }

        $(document)
            .on('MSGestureEnd', function (e) {
                var swipeDirectionFromVelocity =
                    e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null;
                if (swipeDirectionFromVelocity) {
                    touch.el.trigger('swipe');
                    touch.el.trigger('swipe' + swipeDirectionFromVelocity);
                }
            })
            .on(_touchstart + ' MSPointerDown pointerdown', function (e) {
                if ((_isPointerType = isPointerEventType(e, 'down')) &&
                    !isPrimaryTouch(e)) return;
                firstTouch = _isPointerType || !isSupportTouch ? e : e.touches[0];
                if (e.touches && e.touches.length === 1 && touch.x2) {
                    // Clear out touch movement data if we have it sticking around
                    // This can occur if touchcancel doesn't fire due to preventDefault, etc.
                    touch.x2 = undefined;
                    touch.y2 = undefined;
                }
                now = Date.now();
                delta = now - (touch.last || now);
                touch.el = $('tagName' in firstTouch.target ?
                    firstTouch.target : firstTouch.target.parentNode);
                touchTimeout && clearTimeout(touchTimeout);
                touch.x1 = firstTouch.pageX;
                touch.y1 = firstTouch.pageY;
                if (delta > 0 && delta <= 250) touch.isDoubleTap = true;
                touch.last = now;
                longTapTimeout = setTimeout(longTap, longTapDelay);
                // adds the current touch contact for IE gesture recognition
                if (gesture && _isPointerType) gesture.addPointer(e.pointerId);
            })
            .on(_touchmove + ' MSPointerMove pointermove', function (e) {
                var moveX = moveY = 0;
                if (!touch.el) return;
                if ((_isPointerType = isPointerEventType(e, 'move')) &&
                    !isPrimaryTouch(e)) return;
                firstTouch = _isPointerType || !isSupportTouch ? e : e.touches[0];
                cancelLongTap();
                touch.x2 = firstTouch.pageX;
                touch.y2 = firstTouch.pageY;

                moveX = Math.abs(touch.x1 - touch.x2);
                moveY = Math.abs(touch.y1 - touch.y2);
                deltaX += moveX;
                deltaY += moveY;

                if (moveX > 30 || moveY > 30) {
                    touch.el.trigger('draw', {detail: touch});
                }
            })
            .on(_touchend + ' MSPointerUp pointerup', function (e) {
                if ((_isPointerType = isPointerEventType(e, 'up')) &&
                    !isPrimaryTouch(e)) return;
                cancelLongTap();

                // swipe
                if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
                    (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))

                    swipeTimeout = setTimeout(function () {
                        touch.el.trigger('swipe');
                        touch.el.trigger('swipe' + (direction(touch.x1, touch.x2, touch.y1, touch.y2)));
                        touch = {};
                    }, 0);

                // normal tap
                else if ('last' in touch)
                    // don't fire tap when delta position changed by more than 30 pixels,
                    // for instance when moving to a point and back to origin
                    if (deltaX < 30 && deltaY < 30) {
                        // delay by one tick so we can cancel the 'tap' event if 'scroll' fires
                        // ('tap' fires before 'scroll')
                        tapTimeout = setTimeout(function () {

                            // trigger universal 'tap' with the option to cancelTouch()
                            // (cancelTouch cancels processing of single vs double taps for faster 'tap' response)
                            touch.el.trigger('tap', {'cancelTouch': cancelAll});

                            // trigger double tap immediately
                            if (touch.isDoubleTap) {
                                if (touch.el) touch.el.trigger('doubleTap');
                                touch = {};
                            }

                            // trigger single tap after 250ms of inactivity
                            else {
                                touchTimeout = setTimeout(function () {
                                    touchTimeout = null
                                    if (touch.el) touch.el.trigger('singleTap')
                                    touch = {}
                                }, 250);
                            }
                        }, 0);
                    } else {
                        touch = {};
                    }
                deltaX = deltaY = 0;

            })
            // when the browser window loses focus,
            // for example when a modal dialog is shown,
            // cancel all ongoing events
            .on('touchcancel MSPointerCancel pointercancel', cancelAll);

        // scrolling the window indicates intention of the user
        // to scroll, not tap or swipe, so cancel all ongoing events
        // $(window).on('scroll', cancelAll);
        window.addEventListener('scroll', cancelAll, false);
    })();

    ;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'draw',
        'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function (eventName) {
            $.fn[eventName] = function (callback) { return this.on(eventName, callback) }
        });
})(window, xEvent);<commit_msg>add drawEnd event<commit_after>/**
 * xGesture.js
 * https://github.com/kiinlam/xGesture
 */

; (function (window, $) {
    var isSupportTouch = 'ontouchend' in document ? true : false,
        _touchstart = isSupportTouch ? 'touchstart' : 'mousedown',
        _touchmove = isSupportTouch ? 'touchmove' : 'mousemove',
        _touchend = isSupportTouch ? 'touchend' : 'mouseup',
        touch = {},
        touchTimeout, tapTimeout, swipeTimeout, longTapTimeout,
        longTapDelay = 750,
        gesture;

    function direction(x1, x2, y1, y2) {
        return Math.abs(x1 - x2) >=
            Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down');
    }

    function longTap() {
        longTapTimeout = null;
        if (touch.last) {
            touch.el.trigger('longTap');
            touch = {};
        }
    }

    function cancelLongTap() {
        if (longTapTimeout) clearTimeout(longTapTimeout);
        longTapTimeout = null;
    }

    function cancelAll() {
        if (touchTimeout) clearTimeout(touchTimeout);
        if (tapTimeout) clearTimeout(tapTimeout);
        if (swipeTimeout) clearTimeout(swipeTimeout);
        if (longTapTimeout) clearTimeout(longTapTimeout);
        touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null;
        touch = {};
    }

    function isPrimaryTouch(event) {
        return (event.pointerType == 'touch' ||
            event.pointerType == event.MSPOINTER_TYPE_TOUCH)
            && event.isPrimary;
    }

    function isPointerEventType(e, type) {
        return (e.type == 'pointer' + type ||
            e.type.toLowerCase() == 'mspointer' + type);
    }

    (function () {
        var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType;

        if ('MSGesture' in window) {
            gesture = new MSGesture();
            gesture.target = document.body;
        }

        $(document)
            .on('MSGestureEnd', function (e) {
                var swipeDirectionFromVelocity =
                    e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null;
                if (swipeDirectionFromVelocity) {
                    touch.el.trigger('swipe');
                    touch.el.trigger('swipe' + swipeDirectionFromVelocity);
                }
            })
            .on(_touchstart + ' MSPointerDown pointerdown', function (e) {
                if ((_isPointerType = isPointerEventType(e, 'down')) &&
                    !isPrimaryTouch(e)) return;
                firstTouch = _isPointerType || !isSupportTouch ? e : e.touches[0];
                if (e.touches && e.touches.length === 1 && touch.x2) {
                    // Clear out touch movement data if we have it sticking around
                    // This can occur if touchcancel doesn't fire due to preventDefault, etc.
                    touch.x2 = undefined;
                    touch.y2 = undefined;
                }
                now = Date.now();
                delta = now - (touch.last || now);
                touch.el = $('tagName' in firstTouch.target ?
                    firstTouch.target : firstTouch.target.parentNode);
                touchTimeout && clearTimeout(touchTimeout);
                touch.x1 = firstTouch.pageX;
                touch.y1 = firstTouch.pageY;
                if (delta > 0 && delta <= 250) touch.isDoubleTap = true;
                touch.last = now;
                longTapTimeout = setTimeout(longTap, longTapDelay);
                // adds the current touch contact for IE gesture recognition
                if (gesture && _isPointerType) gesture.addPointer(e.pointerId);
            })
            .on(_touchmove + ' MSPointerMove pointermove', function (e) {
                var moveX = moveY = 0;
                if (!touch.el) return;
                if ((_isPointerType = isPointerEventType(e, 'move')) &&
                    !isPrimaryTouch(e)) return;
                firstTouch = _isPointerType || !isSupportTouch ? e : e.touches[0];
                cancelLongTap();
                touch.x2 = firstTouch.pageX;
                touch.y2 = firstTouch.pageY;

                moveX = Math.abs(touch.x1 - touch.x2);
                moveY = Math.abs(touch.y1 - touch.y2);
                deltaX += moveX;
                deltaY += moveY;

                if (moveX > 30 || moveY > 30) {
                    touch.el.trigger('draw', {detail: touch});
                }
            })
            .on(_touchend + ' MSPointerUp pointerup', function (e) {
                if ((_isPointerType = isPointerEventType(e, 'up')) &&
                    !isPrimaryTouch(e)) return;
                cancelLongTap();

                // draw end
                if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 3) ||
                    (touch.y2 && Math.abs(touch.y1 - touch.y2) > 3))

                    touch.el.trigger('drawEnd');

                // swipe
                if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
                    (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))

                    swipeTimeout = setTimeout(function () {
                        touch.el.trigger('swipe');
                        touch.el.trigger('swipe' + (direction(touch.x1, touch.x2, touch.y1, touch.y2)));
                        touch = {};
                    }, 0);

                // normal tap
                else if ('last' in touch)
                    // don't fire tap when delta position changed by more than 30 pixels,
                    // for instance when moving to a point and back to origin
                    if (deltaX < 30 && deltaY < 30) {
                        // delay by one tick so we can cancel the 'tap' event if 'scroll' fires
                        // ('tap' fires before 'scroll')
                        tapTimeout = setTimeout(function () {

                            // trigger universal 'tap' with the option to cancelTouch()
                            // (cancelTouch cancels processing of single vs double taps for faster 'tap' response)
                            touch.el.trigger('tap', {'cancelTouch': cancelAll});

                            // trigger double tap immediately
                            if (touch.isDoubleTap) {
                                if (touch.el) touch.el.trigger('doubleTap');
                                touch = {};
                            }

                            // trigger single tap after 250ms of inactivity
                            else {
                                touchTimeout = setTimeout(function () {
                                    touchTimeout = null
                                    if (touch.el) touch.el.trigger('singleTap')
                                    touch = {}
                                }, 250);
                            }
                        }, 0);
                    } else {
                        touch = {};
                    }
                deltaX = deltaY = 0;

            })
            // when the browser window loses focus,
            // for example when a modal dialog is shown,
            // cancel all ongoing events
            .on('touchcancel MSPointerCancel pointercancel', cancelAll);

        // scrolling the window indicates intention of the user
        // to scroll, not tap or swipe, so cancel all ongoing events
        // $(window).on('scroll', cancelAll);
        window.addEventListener('scroll', cancelAll, false);
    })();

    ;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'draw',
        'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function (eventName) {
            $.fn[eventName] = function (callback) { return this.on(eventName, callback) }
        });
})(window, xEvent);<|endoftext|>


<commit_before><commit_msg>Update project vquery to v4.4.0<commit_after><|endoftext|>


<commit_before>
require.config({
    paths: {
        pumascript: '../src/pumascript'
    }
});

require(['pumascript'], function(puma){

    function PumaInjector(dependencies){
        this.version = "1.0"
        this.puma = puma;
        this.deps = dependencies || [];
        this.installDeps();
    };

    PumaInjector.prototype.getExternalScript = function(url) {
        console.log('Getting the Lib from web');
        var xhttp = new XMLHttpRequest();
        var that = this;
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                // Action to be performed when the document is read;
                try {
                    var result = that.puma.evalPuma(this.responseText);
                    if(result.success) that.createScriptNode(url);
                }
                catch (e) {
                    console.log('Error in puma interpretation');
                    console.error(e);
                }
            }
        };
        xhttp.open("GET", url, true);
        xhttp.send();
    };

    PumaInjector.prototype.createScriptNode = function(url){
        var script = document.createElement('script');
        script.src = url;
        document.getElementsByTagName('head')[0].appendChild(script);
    };

    PumaInjector.prototype.installDeps = function(deps){
        var dependencyList = deps || this.deps;

        //Retrieve the script from CDN's
        for(var i=0;i<dependencyList.length;i++){
            this.getExternalScript(dependencyList[i]);
        }
    };

    return new PumaInjector(["https://code.jquery.com/jquery-2.2.4.js"]);
});<commit_msg>Added integrity check<commit_after>
require.config({
    paths: {
        pumascript: '../src/pumascript'
    }
});

require(['pumascript'], function(puma){

    function PumaInjector(dependencies){
        this.version = "1.0"
        this.puma = puma;
        this.deps = dependencies || [];
        this.installDeps();
    };

    PumaInjector.FORCE_INJECT = true;

    PumaInjector.prototype.getExternalScript = function(dependency) {
        console.log('Getting the Lib from web');
        var xhttp = new XMLHttpRequest();
        var that = this;
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                // Action to be performed when the document is read;
                try {
                    var result = that.puma.evalPuma(this.responseText);
                    if(result.success) that.createScriptNode(dependency);
                }
                catch (e) {
                    console.log('Error in puma interpretation');
                    console.error(e);
                    if(PumaInjector.FORCE_INJECT) that.createScriptNode(dependency);
                }
            }
        };
        xhttp.open("GET", dependency.url, true);
        xhttp.send();
    };

    PumaInjector.prototype.createScriptNode = function(dependency){
        var script = document.createElement('script');
        script.src = dependency.url;
        script.setAttribute("crossorigin", "anonymous");
        script.integrity = dependency.checksum;
        document.getElementsByTagName('head')[0].appendChild(script);
    };

    PumaInjector.prototype.installDeps = function(deps){
        var dependencyList = deps || this.deps;

        //Retrieve the script from CDN's
        for(var i=0;i<dependencyList.length;i++){
            this.getExternalScript(dependencyList[i]);
        }
    };

    return new PumaInjector([{url: "https://code.jquery.com/jquery-2.2.4.js",
                             checksum: "sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="}]);
});<|endoftext|>