<commit_before>import template from './billing-details.html';

const billingDetails = {
  template,
  controller: class {
    constructor(
      ENV,
      $state,
      $stateParams,
      WorkspaceService,
      currentStateService,
      customersService,
      usersService,
      ncUtils,
      invoicesService,
      paypalInvoicesService,
      features,
      titleService,
      BillingUtils) {
      // @ngInject
      this.ENV = ENV;
      this.$state = $state;
      this.$stateParams = $stateParams;
      this.WorkspaceService = WorkspaceService;
      this.currentStateService = currentStateService;
      this.customersService = customersService;
      this.usersService = usersService;
      this.ncUtils = ncUtils;
      this.titleService = titleService;
      this.BillingUtils = BillingUtils;
      this.features = features;
      this.invoicesService = invoicesService;
      this.paypalInvoicesService = paypalInvoicesService;
    }

    $onInit() {
      this.paypalVisible = this.features.isVisible('paypal');
      this.showAccountingRecords = this.ENV.accountingMode === 'accounting';
      this.invoice = {};
      this.loading = true;
      this.loadInvoice().finally(() => this.loading = false);
      this.titleService.setTitle(this.BillingUtils.getPageTitle());
    }

    loadInvoice() {
      return this.getInvoiceService().$get(this.$stateParams.uuid).then(invoice => {
        this.invoice = angular.extend({
          period: this.BillingUtils.formatPeriod(invoice),
          items: this.getInvoiceItems(invoice)},
          invoice,
        );

        return invoice;
      })
      .then(invoice => {
        const customer_uuid = this.ncUtils.getUUID(invoice.customer);
        return this.customersService.$get(customer_uuid);
      })
      .then(currentCustomer => {
        this.WorkspaceService.setWorkspace({
          customer: currentCustomer,
          project: null,
          hasCustomer: true,
          workspace: 'organization',
        });

        return this.usersService.getCurrentUser().then(currentUser => {
          const status = this.customersService.checkCustomerUser(currentCustomer, currentUser);
          this.currentStateService.setOwnerOrStaff(status);
          this.currentStateService.setCustomer(currentCustomer);
        });
      })
      .catch(() => {
        this.$state.go('errorPage.notFound');
      });
    }

    getInvoiceItems(invoice) {
      let items = invoice.items || [];
      let openstack_items = invoice.opestack_items || [];
      return items.concat(openstack_items.concat(invoice.offering_items || []));
    }

    getInvoiceService() {
      if (!this.showAccountingRecords && this.paypalVisible) {
        return this.paypalInvoicesService;
      } else {
        return this.invoicesService;
      }
    }
  }
};

export default billingDetails;
<commit_msg>Render generic invoice items with OpenStack items and offering items [WAL-1141]<commit_after>import template from './billing-details.html';

const billingDetails = {
  template,
  controller: class {
    constructor(
      ENV,
      $state,
      $stateParams,
      WorkspaceService,
      currentStateService,
      customersService,
      usersService,
      ncUtils,
      invoicesService,
      paypalInvoicesService,
      features,
      titleService,
      BillingUtils) {
      // @ngInject
      this.ENV = ENV;
      this.$state = $state;
      this.$stateParams = $stateParams;
      this.WorkspaceService = WorkspaceService;
      this.currentStateService = currentStateService;
      this.customersService = customersService;
      this.usersService = usersService;
      this.ncUtils = ncUtils;
      this.titleService = titleService;
      this.BillingUtils = BillingUtils;
      this.features = features;
      this.invoicesService = invoicesService;
      this.paypalInvoicesService = paypalInvoicesService;
    }

    $onInit() {
      this.paypalVisible = this.features.isVisible('paypal');
      this.showAccountingRecords = this.ENV.accountingMode === 'accounting';
      this.invoice = {};
      this.loading = true;
      this.loadInvoice().finally(() => this.loading = false);
      this.titleService.setTitle(this.BillingUtils.getPageTitle());
    }

    loadInvoice() {
      return this.getInvoiceService().$get(this.$stateParams.uuid).then(invoice => {
        this.invoice = angular.extend({
          period: this.BillingUtils.formatPeriod(invoice),
          items: this.getInvoiceItems(invoice)},
          invoice,
        );

        return invoice;
      })
      .then(invoice => {
        const customer_uuid = this.ncUtils.getUUID(invoice.customer);
        return this.customersService.$get(customer_uuid);
      })
      .then(currentCustomer => {
        this.WorkspaceService.setWorkspace({
          customer: currentCustomer,
          project: null,
          hasCustomer: true,
          workspace: 'organization',
        });

        return this.usersService.getCurrentUser().then(currentUser => {
          const status = this.customersService.checkCustomerUser(currentCustomer, currentUser);
          this.currentStateService.setOwnerOrStaff(status);
          this.currentStateService.setCustomer(currentCustomer);
        });
      })
      .catch(() => {
        this.$state.go('errorPage.notFound');
      });
    }

    getInvoiceItems(invoice) {
      const items = invoice.items || [];
      const openstack_items = invoice.openstack_items || [];
      const offering_items = invoice.offering_items || [];
      const generic_items = invoice.generic_items || [];
      return [
        ...items,
        ...openstack_items,
        ...offering_items,
        ...generic_items,
      ];
    }

    getInvoiceService() {
      if (!this.showAccountingRecords && this.paypalVisible) {
        return this.paypalInvoicesService;
      } else {
        return this.invoicesService;
      }
    }
  }
};

export default billingDetails;
<|endoftext|>


<commit_before>define([
    'underscore',
    'backbone',
    'views/subscription-item-view',
    'marionette',
    'templates',
    'dataTables'

], function (_, Backbone, SubscriptionItemView) {

    var SubscriptionsCompositeView = Backbone.Marionette.CompositeView.extend({

        itemView: SubscriptionItemView,

        template: 'subscriptions-composite',

        itemViewContainer: 'tbody',

        onRender: function() {

            var $subscriptionsTable = this.$el.find('#subscriptions-table');

            $subscriptionsTable.dataTable();

            $('.datatable').each(function(){
                var datatable = $(this);

                // SEARCH - Add the placeholder for Search and Turn this into in-line formcontrol
                var search_input = datatable.closest('.dataTables_wrapper').find('div[id$=_filter] input');
                search_input.attr('placeholder', 'Search')
                search_input.addClass('form-control input-small')
                search_input.css('width', '250px')

                // SEARCH CLEAR - Use an Icon
                var clear_input = datatable.closest('.dataTables_wrapper').find('div[id$=_filter] a');
                clear_input.html('')
                clear_input.css('margin-left', '5px')

                // LENGTH - Inline-Form control
                var length_sel = datatable.closest('.dataTables_wrapper').find('div[id$=_length] select');
                length_sel.addClass('form-control input-small')
                length_sel.css('width', '75px')

                // LENGTH - Info adjust location
                var length_sel = datatable.closest('.dataTables_wrapper').find('div[id$=_info]');
                length_sel.css('margin-top', '18px')
            });

        }

    });

    return SubscriptionsCompositeView;

});<commit_msg>Integrate Bootstrap pagination into dataTables<commit_after>define([
    'underscore',
    'backbone',
    'views/subscription-item-view',
    'marionette',
    'templates',
    'dataTables',
    'dataTablesBootstrap'

], function (_, Backbone, SubscriptionItemView) {

    var SubscriptionsCompositeView = Backbone.Marionette.CompositeView.extend({

        itemView: SubscriptionItemView,

        template: 'subscriptions-composite',

        itemViewContainer: 'tbody',

        onRender: function() {

            var $subscriptionsTable = this.$el.find('#subscriptions-table');

            var dataTable = $subscriptionsTable.dataTable({
                'sPaginationType': 'bootstrap'
            });

            $('.datatable').each(function(){
                var datatable = $(this);

                // SEARCH - Add the placeholder for Search and Turn this into in-line formcontrol
                var search_input = datatable.closest('.dataTables_wrapper').find('div[id$=_filter] input');
                search_input.attr('placeholder', 'Search')
                search_input.addClass('form-control input-small')
                search_input.css('width', '250px')

                // SEARCH CLEAR - Use an Icon
                var clear_input = datatable.closest('.dataTables_wrapper').find('div[id$=_filter] a');
                clear_input.html('')
                clear_input.css('margin-left', '5px')

                // LENGTH - Inline-Form control
                var length_sel = datatable.closest('.dataTables_wrapper').find('div[id$=_length] select');
                length_sel.addClass('form-control input-small')
                length_sel.css('width', '75px')

                // LENGTH - Info adjust location
                var length_sel = datatable.closest('.dataTables_wrapper').find('div[id$=_info]');
                length_sel.css('margin-top', '18px')
            });

            dataTable.extend

        }

    });

    return SubscriptionsCompositeView;

});<|endoftext|>


<commit_before>'use strict';

const chai = require('chai');

const plate = require('../index');

const expect = chai.expect;

describe('Those postal codes', function() {
  it('should be valid', function() {
    expect(plate.validate('10188')).to.be.true;
    expect(plate.validate('49080')).to.be.true;
  });
});

describe('Those postal codes', function() {
  it('should be invalid', function() {
    expect(plate.validate('90000')).to.be.false;
    expect(plate.validate('00000')).to.be.false;
    expect(plate.validate('1abcd')).to.be.false;
    expect(plate.validate('123456')).to.be.false;
    expect(plate.validate('1234')).to.be.false;
    expect(plate.validate('1 2 3 4')).to.be.false;
  });
});

describe('Those dirty postal codes', function() {
  it('should be cleaned', function() {
    expect(plate.clean(' 123 45 ')).to.equal('12345');
  });
});
<commit_msg>Fix wrong naming in tests<commit_after>'use strict';

const chai = require('chai');

const postalCode = require('../index');

const expect = chai.expect;

describe('Those postal codes', function() {
  it('should be valid', function() {
    expect(postalCode.validate('10188')).to.be.true;
    expect(postalCode.validate('49080')).to.be.true;
  });
});

describe('Those postal codes', function() {
  it('should be invalid', function() {
    expect(postalCode.validate('90000')).to.be.false;
    expect(postalCode.validate('00000')).to.be.false;
    expect(postalCode.validate('1abcd')).to.be.false;
    expect(postalCode.validate('123456')).to.be.false;
    expect(postalCode.validate('1234')).to.be.false;
    expect(postalCode.validate('1 2 3 4')).to.be.false;
  });
});

describe('Those dirty postal codes', function() {
  it('should be cleaned', function() {
    expect(postalCode.clean(' 123 45 ')).to.equal('12345');
  });
});
<|endoftext|>


<commit_before>// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma'),
      require('karma-phantomjs-launcher'),
      require('karma-junit-reporter')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: ['progress', 'kjhtml', 'junit'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhatomJS'],
    singleRun: false,
    junitReporter: {
      outputDir: '',
      outputFile: 'test.xml'
    }
  });
};
<commit_msg>typo fix<commit_after>// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma'),
      require('karma-phantomjs-launcher'),
      require('karma-junit-reporter')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: ['progress', 'kjhtml', 'junit'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: false,
    junitReporter: {
      outputDir: '',
      outputFile: 'test.xml'
    }
  });
};
<|endoftext|>


<commit_before>function drawPage() {
    console.log(json);
    var output = "";
    var u2fScript="";
    var start = "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "                          Manage Profile	\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "                <input type=\"hidden\" name=\"profile\" value=\"default\" />\n";

    var body = "";

    for (var i in json.return.fieldValues) {
        body = body + "
\n" +
        "                           " +
        "" + json.return.fieldValues[i].displayName;
        if (json.return.fieldValues[i].required == "true") {
            body = body + " *";
        }

        body = body + " \n	" +
            "
";

        if (json.return.fieldValues[i].readOnly == "true") {
            body = body + "                        <input type=\"text\" disabled=\"\" value=\"" + json.return.fieldValues[i].fieldValue + "\" id=\"" + json.return.fieldValues[i].claimUri + "\" name=\"" + json.return.fieldValues[i].claimUri + "\" style=\"height: 30px;  align: left;width: 100%;padding-left: 25px;padding-right: 25px;\" />\n" +
                " <input type=\"hidden\" name=\"" + json.return.fieldValues[i].claimUri + "\" value=\"" + json.return.fieldValues[i].fieldValue + "\" />";
        }
        else {
            body = body + "<input type=\"text\" value=\"" + json.return.fieldValues[i].fieldValue + "\" id=\"" + json.return.fieldValues[i].claimUri + "\" name=\"" + json.return.fieldValues[i].claimUri +
                "\" style=\"height: 30px;  align: left;width: 100%;padding-left: 25px;padding-right: 25px;\" />";

        }
        body = body + "
\n" +
            "
";

    }

    var endString ="
\n" +
        "               " +
        "
" +
        "                    <button id=\"connectFedBtn\" class=\"btn btn-primary mgL14px\" onclick=\"drawFIDORegistration(this);\" type=\"button\" >Manage U2F Authentication</button>" +
        "

"+
        "
" +
        "                        <input type=\"button\" onclick=\"validate();\" class=\"btn btn-primary\" value=\"Update\"/>\n" +
        "                        <input type=\"button\" onclick=\"cancel();\" class=\"btn\" value=\"Cancel\"/>\n" +
        "
" +
        "
\n" +
        "
"+
        "
\n" +
        "
\n" +
        "
";

    output =  u2fScript + start + body + endString;
    $("#gadgetBody").empty();
    $("#gadgetBody").append(output);
}

function cancel() {
    gadgets.Hub.publish('org.wso2.is.dashboard', {
        msg:'A message from User profile',
        id:"user_profile  .shrink-widget"
    });

}

function validate() {
    var element = "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "        <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>\n" +
        "
Modal title
\n" +
        "
\n" +
        "
\n" +
        "
One fine body…
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
";
    $("#message").append(element);

    for (var i in json.return.fieldValues) {
        var fldname = json.return.fieldValues[i].claimUri;
        var displayName = json.return.fieldValues[i].displayName;

        if (json.return.fieldValues[i].required == "true") {
            if (validateEmpty(fldname).length > 0) {
                message({content:displayName + ' is required', type:'warning', cbk:function () {
                } });
                return false;
            }
        }
        if ((json.return.fieldValues[i].regEx).length > 0) {
            var reg = new RegExp(json.return.fieldValues[i].regEx);
            var value = document.getElementsByName(fldname)[0].value;

            var valid = reg.test(value);
            if (value != '' && !valid) {
                message({content:displayName + ' is not valid', type:'warning', cbk:function () {
                } });
                return false;
            }

        }
    }

    var unsafeCharPattern = /[<>`\"]/;
    var elements = document.getElementsByTagName("input");
    for (i = 0; i < elements.length; i++) {
        if ((elements[i].type === 'text' || elements[i].type === 'password') &&
            elements[i].value != null && elements[i].value.match(unsafeCharPattern) != null) {
            message({content:'Unauthorized characters are specified', type:'warning', cbk:function () {
            } });
            return false;
        }
    }
    submitUpdate();
}

function validateEmpty(fldname) {
    var fld = document.getElementsByName(fldname)[0];
    var error = "";
    var value = fld.value;
    if (value.length == 0) {
        error = fld.name + " ";
        return error;
    }
    value = value.replace(/^\s+/, "");
    if (value.length == 0) {
        error = fld.name + "(contains only spaces) ";
        return error;
    }
    return error;
}

function reloadGrid() {
    $.ajax({
               url: "/portal/gadgets/user_profile/index.jag",
               type: "GET",
               data: "&cookie=" + cookie + "&user=" + userName,
               success: function (data) {
json = $.parseJSON(data);
drawPage();

               },
               error: function (e) {
                   message({content: 'Error occurred while loading values for the grid.', type: 'error', cbk: function () {
                   }});
               }
           });
}

function deleteFIDOToken(deviceRemarks){

 var msg = "You are about to remove Id '" + username + "' From IDP '" + idPId + "'. Do you want to proceed?";
    message({content: msg, type: 'confirm', okCallback: function () {
        $.ajax({
                   url: "/portal/gadgets/connected_accounts/index.jag",
                   type: "POST",
                   data: "&cookie=" + cookie + "&username=" + username + "&idPId=" + idPId + "&action=fedDelete",
                   success: function (data) {
                       var resp = $.parseJSON(data);
                       if (resp.success == true) {
                           reloadFedGrid();
                       } else {
                           if (typeof resp.reLogin != 'undefined' && resp.reLogin == true) {
                               window.top.location.href = window.location.protocol + '//' + serverUrl + '/dashboard/logout.jag';
                           } else {
                               if (resp.message != null && resp.message.length > 0) {
                                   message({content: resp.message, type: 'error', cbk: function () {
                                   }});
                               } else {
                                   message({content: 'Error occurred while deleting user account.', type: 'error', cbk: function () {
                                   }});
                               }
                           }
                       }
                   },
                   error: function (e) {
                       message({content: 'Error occurred while deleting user account.', type: 'error', cbk: function () {
                       }});
                   }
               });
    }, cancelCallback: function () {
    }});
}

function drawFIDORegistration() {

$.ajax({
           url: "/portal/gadgets/user_profile/controllers/my-profile/fido-metadata.jag",
           type: "GET",
           data: "&cookie=" + cookie + "&action=idPList",
           success: function (data) {

var deviceMetadata = null;
if(data != null && "" != data){
               var resp = $.parseJSON(data);
	       deviceMetadata = resp.return;
}

                       var top =
                               "
\n" +
                               "
\n" +
                               "
\n" +
       			       "                <legend>Manage FIDO U2F Device </legend>\n" +
                               "                <form method=\"post\" class=\"form-horizontal\" id=\"associateForm\" name=\"selfReg\"  >\n";
                       var middle = "";
                   if (deviceMetadata != null && deviceMetadata.length > 0) {
                       var middle =
                               "
\n" +
                               "
\n" +
                               "
\n" +
                               "
\n" +
                               "                    Device Remarks	\n" +
                               "                    Action	\n" +
                               "
\n" +
                               "
\n";

                       if (isArray(deviceMetadata)) {
                           for (var i in deviceMetadata) {
                               middle = middle +
                                         "
\n" +
                                         "                     Registration Time : " + deviceMetadata[i] + "	\n" +
                                         "                    \n" +
                                         "                         Remove\n" +
                                         "                    	\n" +
                                         "
\n";
                           }
                       }
                       else {

                           middle = middle +
                                     "
\n" +
                                     "                     Registration Time : "  + deviceMetadata + "	\n" +
                                     "                    \n" +
                                     "                         Remove\n" +
                                     "                    	\n" +
                                     "
\n";

                       }

                       var middle = middle + "
\n" +
                                  "
\n" +
                                  "
";
 }
else {
middle = middle + " Device not registered yet please register your device ! ";
}

                       var end =
                               "
\n" +
                               "
\n" +
                               "                            <input type=\"button\" onclick=\"startFIDO();\" class=\"btn btn-primary\" style=\"margin-right: 5px;\" value=\"Attach FIDO Token\"/>\n" +
                               "                            <input type=\"button\" onclick=\"drawPage();\" class=\"btn\" value=\"Done\"/>\n" +
                               "
\n" +
                               "

\n" +
                               "                </form>\n" +
                               "
\n" +
                               "
\n" +
                               "
   ";

                       var output = top + middle + end;

                       $("#gadgetBody").empty();
                       $("#gadgetBody").append(output);

           },
           error: function (e) {
               message({content: 'Error occurred while loading identity providers.', type: 'error', cbk: function () {
               }});
           }
       });
}

function isArray(element) {
    return Object.prototype.toString.call(element) === '[object Array]';
}
<commit_msg>Fixing IDENTITY-4442<commit_after>function drawPage() {
    console.log(json);
    var output = "";
    var u2fScript="";
    var start = "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "                          Manage Profile	\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "                <input type=\"hidden\" name=\"profile\" value=\"default\" />\n";

    var body = "";

    for (var i in json.return.fieldValues) {
        if (json.return.fieldValues[i].claimUri =="http://wso2.org/claims/identity/accountDisabled") {
            continue;
        }

        body = body + "
\n" +
        "                           " +
        "" + json.return.fieldValues[i].displayName;
        if (json.return.fieldValues[i].required == "true") {
            body = body + " *";
        }

        body = body + " \n	" +
            "
";

        if (json.return.fieldValues[i].readOnly == "true") {
            body = body + "                        <input type=\"text\" disabled=\"\" value=\"" + json.return.fieldValues[i].fieldValue + "\" id=\"" + json.return.fieldValues[i].claimUri + "\" name=\"" + json.return.fieldValues[i].claimUri + "\" style=\"height: 30px;  align: left;width: 100%;padding-left: 25px;padding-right: 25px;\" />\n" +
                " <input type=\"hidden\" name=\"" + json.return.fieldValues[i].claimUri + "\" value=\"" + json.return.fieldValues[i].fieldValue + "\" />";
        }
        else {
            body = body + "<input type=\"text\" value=\"" + json.return.fieldValues[i].fieldValue + "\" id=\"" + json.return.fieldValues[i].claimUri + "\" name=\"" + json.return.fieldValues[i].claimUri +
                "\" style=\"height: 30px;  align: left;width: 100%;padding-left: 25px;padding-right: 25px;\" />";

        }
        body = body + "
\n" +
            "
";

    }

    var endString ="
\n" +
        "               " +
        "
" +
        "                    <button id=\"connectFedBtn\" class=\"btn btn-primary mgL14px\" onclick=\"drawFIDORegistration(this);\" type=\"button\" >Manage U2F Authentication</button>" +
        "

"+
        "
" +
        "                        <input type=\"button\" onclick=\"validate();\" class=\"btn btn-primary\" value=\"Update\"/>\n" +
        "                        <input type=\"button\" onclick=\"cancel();\" class=\"btn\" value=\"Cancel\"/>\n" +
        "
" +
        "
\n" +
        "
"+
        "
\n" +
        "
\n" +
        "
";

    output =  u2fScript + start + body + endString;
    $("#gadgetBody").empty();
    $("#gadgetBody").append(output);
}

function cancel() {
    gadgets.Hub.publish('org.wso2.is.dashboard', {
        msg:'A message from User profile',
        id:"user_profile  .shrink-widget"
    });

}

function validate() {
    var element = "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "        <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>\n" +
        "
Modal title
\n" +
        "
\n" +
        "
\n" +
        "
One fine body…
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
";
    $("#message").append(element);

    for (var i in json.return.fieldValues) {
        var fldname = json.return.fieldValues[i].claimUri;
        var displayName = json.return.fieldValues[i].displayName;

        if (json.return.fieldValues[i].required == "true") {
            if (validateEmpty(fldname).length > 0) {
                message({content:displayName + ' is required', type:'warning', cbk:function () {
                } });
                return false;
            }
        }
        if ((json.return.fieldValues[i].regEx).length > 0) {
            var reg = new RegExp(json.return.fieldValues[i].regEx);
            var value = document.getElementsByName(fldname)[0].value;

            var valid = reg.test(value);
            if (value != '' && !valid) {
                message({content:displayName + ' is not valid', type:'warning', cbk:function () {
                } });
                return false;
            }

        }
    }

    var unsafeCharPattern = /[<>`\"]/;
    var elements = document.getElementsByTagName("input");
    for (i = 0; i < elements.length; i++) {
        if ((elements[i].type === 'text' || elements[i].type === 'password') &&
            elements[i].value != null && elements[i].value.match(unsafeCharPattern) != null) {
            message({content:'Unauthorized characters are specified', type:'warning', cbk:function () {
            } });
            return false;
        }
    }
    submitUpdate();
}

function validateEmpty(fldname) {
    var fld = document.getElementsByName(fldname)[0];
    var error = "";
    var value = fld.value;
    if (value.length == 0) {
        error = fld.name + " ";
        return error;
    }
    value = value.replace(/^\s+/, "");
    if (value.length == 0) {
        error = fld.name + "(contains only spaces) ";
        return error;
    }
    return error;
}

function reloadGrid() {
    $.ajax({
               url: "/portal/gadgets/user_profile/index.jag",
               type: "GET",
               data: "&cookie=" + cookie + "&user=" + userName,
               success: function (data) {
json = $.parseJSON(data);
drawPage();

               },
               error: function (e) {
                   message({content: 'Error occurred while loading values for the grid.', type: 'error', cbk: function () {
                   }});
               }
           });
}

function deleteFIDOToken(deviceRemarks){

 var msg = "You are about to remove Id '" + username + "' From IDP '" + idPId + "'. Do you want to proceed?";
    message({content: msg, type: 'confirm', okCallback: function () {
        $.ajax({
                   url: "/portal/gadgets/connected_accounts/index.jag",
                   type: "POST",
                   data: "&cookie=" + cookie + "&username=" + username + "&idPId=" + idPId + "&action=fedDelete",
                   success: function (data) {
                       var resp = $.parseJSON(data);
                       if (resp.success == true) {
                           reloadFedGrid();
                       } else {
                           if (typeof resp.reLogin != 'undefined' && resp.reLogin == true) {
                               window.top.location.href = window.location.protocol + '//' + serverUrl + '/dashboard/logout.jag';
                           } else {
                               if (resp.message != null && resp.message.length > 0) {
                                   message({content: resp.message, type: 'error', cbk: function () {
                                   }});
                               } else {
                                   message({content: 'Error occurred while deleting user account.', type: 'error', cbk: function () {
                                   }});
                               }
                           }
                       }
                   },
                   error: function (e) {
                       message({content: 'Error occurred while deleting user account.', type: 'error', cbk: function () {
                       }});
                   }
               });
    }, cancelCallback: function () {
    }});
}

function drawFIDORegistration() {

$.ajax({
           url: "/portal/gadgets/user_profile/controllers/my-profile/fido-metadata.jag",
           type: "GET",
           data: "&cookie=" + cookie + "&action=idPList",
           success: function (data) {

var deviceMetadata = null;
if(data != null && "" != data){
               var resp = $.parseJSON(data);
	       deviceMetadata = resp.return;
}

                       var top =
                               "
\n" +
                               "
\n" +
                               "
\n" +
       			       "                <legend>Manage FIDO U2F Device </legend>\n" +
                               "                <form method=\"post\" class=\"form-horizontal\" id=\"associateForm\" name=\"selfReg\"  >\n";
                       var middle = "";
                   if (deviceMetadata != null && deviceMetadata.length > 0) {
                       var middle =
                               "
\n" +
                               "
\n" +
                               "
\n" +
                               "
\n" +
                               "                    Device Remarks	\n" +
                               "                    Action	\n" +
                               "
\n" +
                               "
\n";

                       if (isArray(deviceMetadata)) {
                           for (var i in deviceMetadata) {
                               middle = middle +
                                         "
\n" +
                                         "                     Registration Time : " + deviceMetadata[i] + "	\n" +
                                         "                    \n" +
                                         "                         Remove\n" +
                                         "                    	\n" +
                                         "
\n";
                           }
                       }
                       else {

                           middle = middle +
                                     "
\n" +
                                     "                     Registration Time : "  + deviceMetadata + "	\n" +
                                     "                    \n" +
                                     "                         Remove\n" +
                                     "                    	\n" +
                                     "
\n";

                       }

                       var middle = middle + "
\n" +
                                  "
\n" +
                                  "
";
 }
else {
middle = middle + " Device not registered yet please register your device ! ";
}

                       var end =
                               "
\n" +
                               "
\n" +
                               "                            <input type=\"button\" onclick=\"startFIDO();\" class=\"btn btn-primary\" style=\"margin-right: 5px;\" value=\"Attach FIDO Token\"/>\n" +
                               "                            <input type=\"button\" onclick=\"drawPage();\" class=\"btn\" value=\"Done\"/>\n" +
                               "
\n" +
                               "

\n" +
                               "                </form>\n" +
                               "
\n" +
                               "
\n" +
                               "
   ";

                       var output = top + middle + end;

                       $("#gadgetBody").empty();
                       $("#gadgetBody").append(output);

           },
           error: function (e) {
               message({content: 'Error occurred while loading identity providers.', type: 'error', cbk: function () {
               }});
           }
       });
}

function isArray(element) {
    return Object.prototype.toString.call(element) === '[object Array]';
}
<|endoftext|>


<commit_before>module.exports = function(config) {

  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.');
    process.exit(1);
  }

  // Browsers to run on Sauce Labs
  // Check out https://saucelabs.com/platforms for all browser/OS combos
  var customLaunchers = {
    'SL_Chrome': {
      base: 'SauceLabs',
      browserName: 'chrome'
    },
    'SL_Firefox': {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '26'
    }
  };

  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      'src/*.js',
      'test/*.js'
    ],
    reporters: ['dots'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    sauceLabs: {
      username: process.env.SAUCE_USERNAME,
      accessKey: process.env.SAUCE_ACCESS_KEY,
      testName: 'Karma and Sauce Labs demo',
      // Change this value if you are using a different CI than Travis
      build: process.env.TRAVIS_JOB_ID
    },
    // Increase timeout in case connection in CI is slow
    captureTimeout: 120000,
    customLaunchers: customLaunchers,
    browsers: Object.keys(customLaunchers),
    singleRun: true
  });
};
<commit_msg>test: use saucelabs reporter in the example<commit_after>module.exports = function(config) {

  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.');
    process.exit(1);
  }

  // Browsers to run on Sauce Labs
  // Check out https://saucelabs.com/platforms for all browser/OS combos
  var customLaunchers = {
    'SL_Chrome': {
      base: 'SauceLabs',
      browserName: 'chrome'
    },
    'SL_Firefox': {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '26'
    }
  };

  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      'src/*.js',
      'test/*.js'
    ],
    reporters: ['dots', 'saucelabs'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    sauceLabs: {
      username: process.env.SAUCE_USERNAME,
      accessKey: process.env.SAUCE_ACCESS_KEY,
      testName: 'Karma and Sauce Labs demo',
      // Change this value if you are using a different CI than Travis
      build: process.env.TRAVIS_JOB_ID
    },
    // Increase timeout in case connection in CI is slow
    captureTimeout: 120000,
    customLaunchers: customLaunchers,
    browsers: Object.keys(customLaunchers),
    singleRun: true
  });
};
<|endoftext|>


<commit_before>'use strict';

var ensureObject         = require('es5-ext/object/valid-object')
  , forEach              = require('es5-ext/object/for-each')
  , capitalize           = require('es5-ext/string/#/capitalize')
  , db                   = require('../../db')
  , _                    = require('mano').i18n.bind('Statistics time per role pdf')
  , resolveFullStepPath  = require('../../utils/resolve-processing-step-full-path')
  , getDurationDaysHours = require('../../view/utils/get-duration-days-hours');

module.exports = function (result, config) {
	var processingStepsMeta = ensureObject(ensureObject(config).processingStepsMeta);
	var data = [];

	forEach(result.steps.byStep, function (data, key) {
		var step = data.processing;
		step.label =  db['BusinessProcess' +
			capitalize.call(processingStepsMeta[key]._services[0])].prototype
			.processingSteps.map.getBySKeyPath(resolveFullStepPath(key)).label;

		data.push(step);
		step.avgTime = getDurationDaysHours(step.avgTime);
		step.minTime = getDurationDaysHours(step.minTime);
		step.maxTime = getDurationDaysHours(step.maxTime);
	});

	var total, processingTotal, correctionTotal, correctionByUsers;
	correctionTotal         = result.steps.all.correction;
	correctionTotal.label   = _("Total correcting time");
	correctionByUsers       = result.steps.all.correction;
	correctionByUsers.label = _("Corrections by the users");
	processingTotal         = result.businessProceesses.processing;
	processingTotal.label   = _("Total process without corrections");

	total                   = result.businessProceesses.processing;
	total.label             = _("Total process");

	[correctionTotal, correctionByUsers, processingTotal, total].forEach(
		function (totalItem) {
			if (!totalItem.count) {
				totalItem.avgTime = totalItem.minTime = totalItem.maxTime = _("N/A");
			} else {
				totalItem.avgTime = getDurationDaysHours(totalItem.avgTime);
				totalItem.minTime = getDurationDaysHours(totalItem.minTime);
				totalItem.maxTime = getDurationDaysHours(totalItem.maxTime);
			}
			data.push(totalItem);
		}
	);

	return data.map(function (row) {
		return [
			row.label,
			row.count,
			row.avgTime,
			row.minTime,
			row.maxTime
		].join();
	}).join('\n');
};
<commit_msg>Fix CSV export<commit_after>'use strict';

var copy                = require('es5-ext/object/copy')
  , ensureObject        = require('es5-ext/object/valid-object')
  , forEach             = require('es5-ext/object/for-each')
  , capitalize          = require('es5-ext/string/#/capitalize')
  , db                  = require('../../db')
  , _                   = require('mano').i18n.bind('Statistics time per role pdf')
  , resolveFullStepPath = require('../../utils/resolve-processing-step-full-path');

var resolveDays = function (time) { return time / (1000 * 60 * 60 * 24); };

module.exports = function (result, config) {
	var processingStepsMeta = ensureObject(ensureObject(config).processingStepsMeta);
	var data = [];

	forEach(result.steps.byStep, function (stepData, key) {
		var step = stepData.processing;
		step.label =  db['BusinessProcess' +
			capitalize.call(processingStepsMeta[key]._services[0])].prototype
			.processingSteps.map.getBySKeyPath(resolveFullStepPath(key)).label;

		data.push(step);
	});

	var total, processingTotal, correctionTotal, correctionByUsers;
	correctionTotal         = result.steps.all.correction;
	correctionTotal.label   = _("Total correcting time");
	correctionByUsers       = copy(result.steps.all.correction);
	correctionByUsers.label = _("Corrections by the users");
	processingTotal         = result.businessProcesses.processing;
	processingTotal.label   = _("Total process without corrections");

	total                   = copy(result.businessProcesses.processing);
	total.label             = _("Total process");

	data.push(correctionTotal, correctionByUsers, processingTotal, total);

	return data.map(function (row) {
		return [
			JSON.stringify(row.label),
			row.count,
			row.count ? resolveDays(row.avgTime) : '',
			row.count ? resolveDays(row.minTime) : '',
			row.count ? resolveDays(row.maxTime) : ''
		].join();
	}).join('\n');
};
<|endoftext|>


<commit_before>/// <reference path="GameDraw.js" />
/// <reference path="GameObjects.js" />
var GameEngine = ( function () {
    var board,
        players,
        dices,
        firstDiceThrow,
        currentPlayer,
        hasChosen,
        indexOfChosenField,
        indexOfTargetField,
        diceSound = new Audio('Sounds/dice.wav');

    function start() {
        players = [];
        // playerOneName , playerTwoName - variables containing names from start screen
        players.push(Object.create(GameObjects.Player).init('First', 'white'));
        players.push(Object.create(GameObjects.Player).init('Second', 'black'));

        board = GameObjects.Board.init();

        // dices.rollDices() ; dices.usedNumber(number) ; dices.clearNumbers()
        dices = GameObjects.Dices.init();

        firstDiceThrow = true;

        GameDraw.initGame(board, players);
    }

    function clickedToRollDices() {
        diceSound.play();
        if (firstDiceThrow) {
            throwFirstDiceToDeterminePlayer();
            dices.numbers['mustThrowAgain'] = true;
            // after the first throw which is for who will be first the first player throws again his real dices
            currentPlayer = players[0].isOnTurn ? players[0] : players[1];
            firstDiceThrow = false;
        } else if (dices.numbers.length === 0) {
            dices.rollDices();
            //dices.numbers = [6,6,6,6];
            currentPlayer = players[0].isOnTurn ? players[0] : players[1];
        }

        diceSound.currentTime = 0;
        GameDraw.updatePlayerNames(currentPlayer);
        // DO NOT USE dices.clearNumbers here!!!!
    }

    function throwFirstDiceToDeterminePlayer() {
        dices.rollDices();
        if (dices.numbers[dices.numbers.length - 2] > dices.numbers[dices.numbers.length - 1]) {
            players[0].isOnTurn = true;
        } else if (dices.numbers[dices.numbers.length - 2] < dices.numbers[dices.numbers.length - 1]) {
            players[1].isOnTurn = true;
        } else {
            firstDiceThrow = true;
            dices.clearNumbers();
            throwFirstDiceToDeterminePlayer();
        }
    }

    function setCurrentPlayerOnTurn() {
        if (players[0].isOnTurn) {
            players[0].isOnTurn = false;
            players[1].isOnTurn = true;
            return players[0];
        } else {
            players[0].isOnTurn = true;
            players[1].isOnTurn = false;
            return players[1];
        }
    }

    function update(pressedField) {
        if (dices.numbers['mustThrowAgain']) {
            return;
        }
        var canExtract = checkIfPlayerCanExtractPieces(currentPlayer, board);

        // alert(hasChosen +' ' + indexOfChosenField +' ' +  indexOfTargetField +' ' +  canExtract)

        if (hasChosen) {
            indexOfTargetField = getIndexOfPossibleTargetFields(indexOfChosenField, currentPlayer, board, dices.numbers);

            if (indexOfTargetField.indexOf(pressedField) < 0) {
                return;
            }

            board.movePiece(indexOfChosenField, pressedField);

            hasChosen = false;

            dices.usedNumber(Math.abs(pressedField - indexOfChosenField));

            checkForPinnedPiece(board);

            if (dices.numbers.length === 0) {
                alert('No more moves. Next player turn');
                setAvailabilityOfFields(board);
                GameDraw.updateDices();
                updatePlayGround();
                setCurrentPlayerOnTurn();
                return;
            }

        } else {
            if (!canExtract) {
                var possibleStartPositions = getIndexOfFieldsWithMovesAvailable(currentPlayer, board, dices.numbers);
                // alert(possibleStartPositions)
                if (!possibleStartPositions.length) {
                    alert('No moves');
                    //dices.clearNumbers();
                    setAvailabilityOfFields(board);
                    GameDraw.updateDices();
                    updatePlayGround();
                    setCurrentPlayerOnTurn();

                    return;
                } else if (possibleStartPositions.length === 1) {

                    if (board[possibleStartPositions[0]].pieces.length >= 5) {
                        board[possibleStartPositions[0]].pieces[4].isChosen = true;
                    } else {
                        board[possibleStartPositions[0]].pieces[board[possibleStartPositions[0]].pieces.length - 1].isChosen = true;
                    }

                    hasChosen = true;
                    indexOfChosenField = possibleStartPositions[0];
                    // alert(hasChosen + ' ' + indexOfChosenField)

                } else {
                    if (possibleStartPositions.indexOf(pressedField) > -1) {
                        if (board[pressedField].pieces.length >= 5) {
                            board[pressedField].pieces[4].isChosen = true;
                        } else {
                            board[pressedField].pieces[board[pressedField].pieces.length - 1].isChosen = true;
                        }
                    } else {
                        return;
                    }

                    hasChosen = true;
                    indexOfChosenField = pressedField;
                    // alert(hasChosen + ' ' + indexOfChosenField)

                }

            } else {
                // drago tuka move da tegli playera..

            }
        }

        updatePlayGround();
        GameDraw.updateDices();

        if (!currentPlayer.countOfPieces) {
            alert(currentPlayer.name + ' WINS!!!')
        }
    }

    function getIndexOfFieldsWithMovesAvailable(player, board, numbers) {
        var direction,
            i, j,
            result = [],
            color = player.color,
            index;

        color = color.substring(0, 1).toUpperCase() + color.substring(1);

        if (color.toLowerCase() === 'white') {
            direction = 1;

            if (board[0].pieces.length) {
                for (j = 0; j < numbers.length; j += 1) {
                    if (board[0 + numbers[j] * direction]['availableFor' + color]) {
                        return [0];
                    }
                }

                return result;
            }
        } else {
            direction = -1;

            if (board[board.length - 1].pieces.length) {
                for (j = 0; j < numbers.length; j += 1) {
                    if (board[board.length - 1 + numbers[j] * direction]['availableFor' + color]) {
                        return [board.length - 1];
                    }
                }

                return result;
            }
        }

        for (i = 1, len = board.length; i < board.length - 1; i += 1) {
            if (board[i].pieces.length > 0 && board[i].pieces[0].color === color.toLowerCase()) {
                for (j = 0; j < numbers.length; j += 1) {
                    index = i + numbers[j] * direction;
                    if (0 < index && index < 25 && board[index]['availableFor' + color]) {
                        result.push(i);
                        break;
                    }
                }
            }
        }

        return result;
    }

    function getIndexOfPossibleTargetFields(markedIndex, player, board, numbers) {
        alert('clicked position ' + markedIndex + '\n dices to play' + numbers)

        var color = player.color,
            i,
            result = [],
            direction,
            index;

        if (color === 'white') {
            direction = 1
        } else {
            direction = -1
        }

        color = color.substring(0, 1).toUpperCase() + color.substring(1);

        for (i = 0; i < numbers.length; i++) {
            index = markedIndex + numbers[i] * direction;

            if (0 < index && index < 25 && board[index]['availableFor' + color]) {
                result.push(markedIndex + numbers[i] * direction);
            }
        }

        return result;
    }

    function checkForPinnedPiece(board) {
        var i,
            len = board.length;

        for (i = 1; i < len - 1; i += 1) {
            if (board[i].pieces.length === 2 && board[i].pieces[0].color !== board[i].pieces[1].color) {
                var shifted = board[i].pieces.shift();
                if (shifted.color === 'white') {
                    board[0].pieces.push(shifted);
                    updatePlayGround();
                    return;
                } else {
                    board[len - 1].pieces.push(shifted);
                    updatePlayGround();
                    return;
                }
            }
        }
    }

    function checkIfPlayerCanExtractPieces(player, board) {
        var color = player.color,
            i,
            count = 0;

        if (color === 'white') {
            for (i = 19; i <= 24; i += 1) {
                if (board[i].pieces.length > 0 && board[i].pieces[0].color === color) {
                    count += board[i].pieces.length;
                }
            }
        } else {
            for (i = 1; i <= 6; i += 1) {
                if (board[i].pieces.length > 0 && board[i].pieces[0].color === color) {
                    count += board[i].pieces.length;
                }
            }
        }

        return count === player.countOfPieces;
    }

    function setAvailabilityOfFields(board) {
            var i,
                len = board.length - 1;
            for (i = 1; i < len; i += 1) {
                board[i].availableForBlack = true;
                board[i].availableForWhite = true;

                if (board[i].pieces.length > 1 && board[i].pieces[1].color === 'white') {
                    board[i].availableForBlack = false;
                }
                if (board[i].pieces.length > 1 && board[i].pieces[1].color === 'black') {
                    board[i].availableForWhite = false;
                }
            }
        }

    function updatePlayGround() {
        GameDraw.updatePlayGround(board);
    }

    function getDices() {
        return dices;
    }

    return {
        start: start,
        update: update,
        clickedToRollDices: clickedToRollDices,
        dices: getDices
    };
}() );

// // All events will call GameEngine.Update() and GameDraw.Update().

//// Logic to add
function checkIfPlayerIsMakingNormalMoves(currentActivePlayer, currentPlayerMoves, maximumAllowedMovesInTurn) {
    if (currentPlayerMoves < maximumAllowedMovesInTurn && !currentActivePlayer.hasHitChecker && !currentActivePlayer.canTakeChecker) {
        return true;
    }
    return false;
}

function play() {

    var maximumAllowedMovesInTurn;
    var currentActivePlayer;
    var inactivePlayer;
    var currentPlayerMoves = 0;   // DA SE IZNESAT TEZI PROMENLIVI GORE POSLE

    //FIRST DICE ROLL CHECK
    if (!checkIfDiceHaveBeenThrownBefore(firstDiceThrow)) {
        throwFirstDiceToDeterminePlayer();
    }

    setCurrentPlayerOnTurn(firstPlayerOnTurn); //Will create the current player on turn
    //value,and have a inactivePlayer  value for the one that isnt  on turn at the moment

    //IF NO MOVES AVAILABLE SWITCH PLAYERS WITHOUT THROWING DICE (player hit and all his 6 spaces are currently closed by enemy)
    if (!currentActivePlayer.hasMovesAvailable) {  //LOGIC NEEDS TO BE ADDED,WHEN  HAS MOVES AVAILABLE BECOMES FALSE- IT'S TRUE ON START,BUT CHANGES
        firstPlayerOnTurn = !firstPlayerOnTurn;
        play();
    }

    //THROW DICE
    throwDiceAndCheckMaxMovesForTurn();

    //IF HAS HIT CHECKERS
    while (currentActivePlayer.hasHitChecker) {

        if (!currentActivePlayer.hasHitChecker) {
            break;
        }

        //WHITE PLAYER - player 1
        if (currentActivePlayer.color === 'white') {
            //check if first dice number field is available
            if (board.fields[firstDice.number].availableForWhite) {
                if (board.fields[firstDice.number].length > 0 && board.fields[firstDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[25].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }
            }
            if (board.fields[secondDice.number].availableForWhite) {
                if (board.fields[secondDice.number].length > 0 && board.fields[secondDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[25].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    hasNoMoves = true;
                    break;
                }
            }

        }

        //IF BLACK PLAYER - player 2

        else {
            //check if first dice number field is available
            if (board.fields[firstDice.number].availableForBlack) {
                if (board.fields[firstDice.number].length > 0 && board.fields[firstDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[0].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }
            }
            if (board.fields[secondDice.number].availableForBlack) {
                if (board.fields[secondDice.number].length > 0 && board.fields[secondDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[0].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }
            }

        }

    }

    if (currentPlayerMoves === maximumAllowedMovesInTurn) {
        play();
    }

    //CHECK IF PLAYER IS CURRENTLY TAKING CHECKERS

    if (currentPlayerMoves === maximumAllowedMovesInTurn) {
        play();
    }

    //JUST MOVE CHECKERS
    if (!checkIfPlayerIsMakingNormalMoves(currentActivePlayer, currentPlayerMoves, maximumAllowedMovesInTurn)) { //CHECK IF PLAYER HAS TO END TURN
        firstPlayerOnTurn = !firstPlayerOnTurn;
        play();
    }

    if (currentActivePlayer.color === 'white') {//white player - player1

        var isClickValidForStartPosition = false;

        while (!isClickValidForStartPosition) {
            //wait for mouse click for start position
            //get X and Y of clicked position
            //determine which board.fields place it is
            //check if that position contains his checkers  (isAvailable for white/black)
            //if no -> leave ,the  while loop will repeat itself and await new click for start position
            // if yes =>  isClickValidForStartPosition = true;
            //highlight which board places the checker from the start position can move to
            //wait for click to determine end position
            //get X and Y of clicked position
            //determine which board.fields place it is
            //if it is one of the possible places,considering the start position -> make the move and draw ,
            //else keep highligted and wait correct click for end position
            //currentPlayerMoves++
            //check is all possible moves for this player,for this turn are made and change players if so
        }

    }
    else {  //black player - player 2

    }
    draw();
}
<commit_msg>method checkForPinnedPiece now doesn't loop - checks current clicked field. setAvailabilityOfFields at init added<commit_after>/// <reference path="GameDraw.js" />
/// <reference path="GameObjects.js" />
var GameEngine = ( function () {
    var board,
        players,
        dices,
        firstDiceThrow,
        currentPlayer,
        hasChosen,
        indexOfChosenField,
        indexOfTargetField,
        diceSound = new Audio('Sounds/dice.wav');

    function start() {
        players = [];
        // playerOneName , playerTwoName - variables containing names from start screen
        players.push(Object.create(GameObjects.Player).init('First', 'white'));
        players.push(Object.create(GameObjects.Player).init('Second', 'black'));

        board = GameObjects.Board.init();

        // dices.rollDices() ; dices.usedNumber(number) ; dices.clearNumbers()
        dices = GameObjects.Dices.init();

        firstDiceThrow = true;

        GameDraw.initGame(board, players);
        setAvailabilityOfFields(board);
    }

    function clickedToRollDices() {
        diceSound.play();
        if (firstDiceThrow) {
            throwFirstDiceToDeterminePlayer();
            dices.numbers['mustThrowAgain'] = true;
            // after the first throw which is for who will be first the first player throws again his real dices
            currentPlayer = players[0].isOnTurn ? players[0] : players[1];
            firstDiceThrow = false;
        } else if (dices.numbers.length === 0) {
            dices.rollDices();
            //dices.numbers = [6,6,6,6];
            currentPlayer = players[0].isOnTurn ? players[0] : players[1];
        }

        diceSound.currentTime = 0;
        GameDraw.updatePlayerNames(currentPlayer);
        // DO NOT USE dices.clearNumbers here!!!!
    }

    function throwFirstDiceToDeterminePlayer() {
        dices.rollDices();
        if (dices.numbers[dices.numbers.length - 2] > dices.numbers[dices.numbers.length - 1]) {
            players[0].isOnTurn = true;
        } else if (dices.numbers[dices.numbers.length - 2] < dices.numbers[dices.numbers.length - 1]) {
            players[1].isOnTurn = true;
        } else {
            firstDiceThrow = true;
            dices.clearNumbers();
            throwFirstDiceToDeterminePlayer();
        }
    }

    function setCurrentPlayerOnTurn() {
        if (players[0].isOnTurn) {
            players[0].isOnTurn = false;
            players[1].isOnTurn = true;
            return players[0];
        } else {
            players[0].isOnTurn = true;
            players[1].isOnTurn = false;
            return players[1];
        }
    }

    function update(pressedField) {
        if (dices.numbers['mustThrowAgain']) {
            return;
        }
        var canExtract = checkIfPlayerCanExtractPieces(currentPlayer, board);

        // alert(hasChosen +' ' + indexOfChosenField +' ' +  indexOfTargetField +' ' +  canExtract)

        if (hasChosen) {
            indexOfTargetField = getIndexOfPossibleTargetFields(indexOfChosenField, currentPlayer, board, dices.numbers);

            if (indexOfTargetField.indexOf(pressedField) < 0) {
                return;
            }

            board.movePiece(indexOfChosenField, pressedField);

            hasChosen = false;

            dices.usedNumber(Math.abs(pressedField - indexOfChosenField));

            checkForPinnedPiece(pressedField);

            if (dices.numbers.length === 0) {
                alert('No more moves. Next player turn');
                setAvailabilityOfFields(board);
                GameDraw.updateDices();
                updatePlayGround();
                setCurrentPlayerOnTurn();
                return;
            }

        } else {
            if (!canExtract) {
                var possibleStartPositions = getIndexOfFieldsWithMovesAvailable(currentPlayer, board, dices.numbers);
                // alert(possibleStartPositions)
                if (!possibleStartPositions.length) {
                    alert('No moves');
                    //dices.clearNumbers();
                    setAvailabilityOfFields(board);
                    GameDraw.updateDices();
                    updatePlayGround();
                    setCurrentPlayerOnTurn();

                    return;
                } else if (possibleStartPositions.length === 1) {

                    if (board[possibleStartPositions[0]].pieces.length >= 5) {
                        board[possibleStartPositions[0]].pieces[4].isChosen = true;
                    } else {
                        board[possibleStartPositions[0]].pieces[board[possibleStartPositions[0]].pieces.length - 1].isChosen = true;
                    }

                    hasChosen = true;
                    indexOfChosenField = possibleStartPositions[0];
                    // alert(hasChosen + ' ' + indexOfChosenField)

                } else {
                    if (possibleStartPositions.indexOf(pressedField) > -1) {
                        if (board[pressedField].pieces.length >= 5) {
                            board[pressedField].pieces[4].isChosen = true;
                        } else {
                            board[pressedField].pieces[board[pressedField].pieces.length - 1].isChosen = true;
                        }
                    } else {
                        return;
                    }

                    hasChosen = true;
                    indexOfChosenField = pressedField;
                    // alert(hasChosen + ' ' + indexOfChosenField)

                }

            } else {
                // drago tuka move da tegli playera..

            }
        }

        updatePlayGround();
        GameDraw.updateDices();

        if (!currentPlayer.countOfPieces) {
            alert(currentPlayer.name + ' WINS!!!')
        }
    }

    function getIndexOfFieldsWithMovesAvailable(player, board, numbers) {
        var direction,
            i, j,
            result = [],
            color = player.color,
            index;

        color = color.substring(0, 1).toUpperCase() + color.substring(1);

        if (color.toLowerCase() === 'white') {
            direction = 1;

            if (board[0].pieces.length) {
                for (j = 0; j < numbers.length; j += 1) {
                    if (board[0 + numbers[j] * direction]['availableFor' + color]) {
                        return [0];
                    }
                }

                return result;
            }
        } else {
            direction = -1;

            if (board[board.length - 1].pieces.length) {
                for (j = 0; j < numbers.length; j += 1) {
                    if (board[board.length - 1 + numbers[j] * direction]['availableFor' + color]) {
                        return [board.length - 1];
                    }
                }

                return result;
            }
        }

        for (i = 1, len = board.length; i < board.length - 1; i += 1) {
            if (board[i].pieces.length > 0 && board[i].pieces[0].color === color.toLowerCase()) {
                for (j = 0; j < numbers.length; j += 1) {
                    index = i + numbers[j] * direction;
                    if (0 < index && index < 25 && board[index]['availableFor' + color]) {
                        result.push(i);
                        break;
                    }
                }
            }
        }

        return result;
    }

    function getIndexOfPossibleTargetFields(markedIndex, player, board, numbers) {
        alert('clicked position ' + markedIndex + '\n dices to play' + numbers)

        var color = player.color,
            i,
            result = [],
            direction,
            index;

        if (color === 'white') {
            direction = 1
        } else {
            direction = -1
        }

        color = color.substring(0, 1).toUpperCase() + color.substring(1);

        for (i = 0; i < numbers.length; i++) {
            index = markedIndex + numbers[i] * direction;

            if (0 < index && index < 25 && board[index]['availableFor' + color]) {
                result.push(markedIndex + numbers[i] * direction);
            }
        }

        return result;
    }

    function checkForPinnedPiece(pressedField) {
        // var i,
        //     len = board.length;

        // for (i = 1; i < len - 1; i += 1) {
            if (board[pressedField].pieces.length === 2 && board[pressedField].pieces[0].color !== board[pressedField].pieces[1].color) {
                var shifted = board[pressedField].pieces.shift();
                if (shifted.color === 'white') {
                    board[0].pieces.push(shifted);
                    updatePlayGround();
                    return;
                } else {
                    board[len - 1].pieces.push(shifted);
                    updatePlayGround();
                    return;
                }
            }
        // }
    }

    function checkIfPlayerCanExtractPieces(player, board) {
        var color = player.color,
            i,
            count = 0;

        if (color === 'white') {
            for (i = 19; i <= 24; i += 1) {
                if (board[i].pieces.length > 0 && board[i].pieces[0].color === color) {
                    count += board[i].pieces.length;
                }
            }
        } else {
            for (i = 1; i <= 6; i += 1) {
                if (board[i].pieces.length > 0 && board[i].pieces[0].color === color) {
                    count += board[i].pieces.length;
                }
            }
        }

        return count === player.countOfPieces;
    }

    function setAvailabilityOfFields(board) {
            var i,
                len = board.length - 1;
            for (i = 1; i < len; i += 1) {
                board[i].availableForBlack = true;
                board[i].availableForWhite = true;

                if (board[i].pieces.length > 1 && board[i].pieces[1].color === 'white') {
                    board[i].availableForBlack = false;
                }
                if (board[i].pieces.length > 1 && board[i].pieces[1].color === 'black') {
                    board[i].availableForWhite = false;
                }
            }
        }

    function updatePlayGround() {
        GameDraw.updatePlayGround(board);
    }

    function getDices() {
        return dices;
    }

    return {
        start: start,
        update: update,
        clickedToRollDices: clickedToRollDices,
        dices: getDices
    };
}() );

// // All events will call GameEngine.Update() and GameDraw.Update().

//// Logic to add
function checkIfPlayerIsMakingNormalMoves(currentActivePlayer, currentPlayerMoves, maximumAllowedMovesInTurn) {
    if (currentPlayerMoves < maximumAllowedMovesInTurn && !currentActivePlayer.hasHitChecker && !currentActivePlayer.canTakeChecker) {
        return true;
    }
    return false;
}

function play() {

    var maximumAllowedMovesInTurn;
    var currentActivePlayer;
    var inactivePlayer;
    var currentPlayerMoves = 0;   // DA SE IZNESAT TEZI PROMENLIVI GORE POSLE

    //FIRST DICE ROLL CHECK
    if (!checkIfDiceHaveBeenThrownBefore(firstDiceThrow)) {
        throwFirstDiceToDeterminePlayer();
    }

    setCurrentPlayerOnTurn(firstPlayerOnTurn); //Will create the current player on turn
    //value,and have a inactivePlayer  value for the one that isnt  on turn at the moment

    //IF NO MOVES AVAILABLE SWITCH PLAYERS WITHOUT THROWING DICE (player hit and all his 6 spaces are currently closed by enemy)
    if (!currentActivePlayer.hasMovesAvailable) {  //LOGIC NEEDS TO BE ADDED,WHEN  HAS MOVES AVAILABLE BECOMES FALSE- IT'S TRUE ON START,BUT CHANGES
        firstPlayerOnTurn = !firstPlayerOnTurn;
        play();
    }

    //THROW DICE
    throwDiceAndCheckMaxMovesForTurn();

    //IF HAS HIT CHECKERS
    while (currentActivePlayer.hasHitChecker) {

        if (!currentActivePlayer.hasHitChecker) {
            break;
        }

        //WHITE PLAYER - player 1
        if (currentActivePlayer.color === 'white') {
            //check if first dice number field is available
            if (board.fields[firstDice.number].availableForWhite) {
                if (board.fields[firstDice.number].length > 0 && board.fields[firstDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[25].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }
            }
            if (board.fields[secondDice.number].availableForWhite) {
                if (board.fields[secondDice.number].length > 0 && board.fields[secondDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[25].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    hasNoMoves = true;
                    break;
                }
            }

        }

        //IF BLACK PLAYER - player 2

        else {
            //check if first dice number field is available
            if (board.fields[firstDice.number].availableForBlack) {
                if (board.fields[firstDice.number].length > 0 && board.fields[firstDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[0].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }
            }
            if (board.fields[secondDice.number].availableForBlack) {
                if (board.fields[secondDice.number].length > 0 && board.fields[secondDice.number][0].color === inactivePlayer.color) {
                    //HIT HIS CHECKER AND PLACE YOUR OWN
                }
                else {
                    //TODO JUST ADD YOUR CHECKER
                }
                //CHANGE THE STATE OF THAT BOARD SPOT
                currentPlayerMoves++;
                if (board.fields[0].length === 0) {
                    currentActivePlayer.hasHitChecker = false;
                    break;
                }
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }

            }
            else {
                currentPlayerMoves++; //you lose a move,because u cant set your pull there
                if (currentPlayerMoves === maximumAllowedMovesInTurn) {
                    firstPlayerOnTurn = !firstPlayerOnTurn;
                    break;
                }
            }

        }

    }

    if (currentPlayerMoves === maximumAllowedMovesInTurn) {
        play();
    }

    //CHECK IF PLAYER IS CURRENTLY TAKING CHECKERS

    if (currentPlayerMoves === maximumAllowedMovesInTurn) {
        play();
    }

    //JUST MOVE CHECKERS
    if (!checkIfPlayerIsMakingNormalMoves(currentActivePlayer, currentPlayerMoves, maximumAllowedMovesInTurn)) { //CHECK IF PLAYER HAS TO END TURN
        firstPlayerOnTurn = !firstPlayerOnTurn;
        play();
    }

    if (currentActivePlayer.color === 'white') {//white player - player1

        var isClickValidForStartPosition = false;

        while (!isClickValidForStartPosition) {
            //wait for mouse click for start position
            //get X and Y of clicked position
            //determine which board.fields place it is
            //check if that position contains his checkers  (isAvailable for white/black)
            //if no -> leave ,the  while loop will repeat itself and await new click for start position
            // if yes =>  isClickValidForStartPosition = true;
            //highlight which board places the checker from the start position can move to
            //wait for click to determine end position
            //get X and Y of clicked position
            //determine which board.fields place it is
            //if it is one of the possible places,considering the start position -> make the move and draw ,
            //else keep highligted and wait correct click for end position
            //currentPlayerMoves++
            //check is all possible moves for this player,for this turn are made and change players if so
        }

    }
    else {  //black player - player 2

    }
    draw();
}
<|endoftext|>


<commit_before><commit_msg>Fixed broken license for seedrandom.js<commit_after><|endoftext|>


<commit_before>var buildAccessIcons = function(access) {
  var access_html = '';
  if (access == []) {
    access_html += '';
  } else {

    if (access['submit_new_ticket'] && access['submit_new_ticket'] == 'edit')
    {
      access_html += '';
    } else if (access['view_tickets'] && access['view_tickets'] == 'edit') {
      access_html += '';
    } else {
      access_html += '';
    }

    if (access['view_orders'] && access['view_orders'] == 'edit') {
      access_html += '';
    }

    if(access['manage_contacts'] && access['manage_contacts'] == 'edit') {
      access_html += '';
    }

  }
  return access_html;
}
var populateContactLists = function (clientID) {
  /*

   submit_new_ticket: "edit"    inbox_plus
   view_tickets: "edit",  eye_open
   view_device: "view",
   view_orders: "edit" usd
   view_service: "edit",
   view_orders: "edit",
   view_quotes: "edit",
   */

  $('#toList').html('');
  $('#ccList').html('');
  $('#sourceList').html('');
  $.getJSON('/api/v1/ubersmith/clients/clientid/' + clientID + '/contacts', function(data){
    var options = '';
    for (var x = 0; x < data.length; x++) {
      var contact = data[x];
      var access_html = '';

      if (contact.access) {
        access_html = buildAccessIcons(contact.access);
      } else {
        access_html = buildAccessIcons([]);
      }

      if (contact.real_name == 'Amir Keric' || contact.real_name == 'Amir West')
      {
        contact.real_name = 'Dr. BadAss';
        access_html += '';
      }

      if (contact.dc_access_role && contact.dc_access_role != 'N/A') {
        access_html += '';
      }

      options += '
' + contact['real_name'] + ' ' +access_html + '
';
    }
    $('#sourceList').html(options);
    prepareDroppableLists();
  });
}

var populateDeviceList = function (clientID) {
  $('#deviceID').html('');
  $.getJSON('/api/v1/ubersmith/clients/clientid/' + clientID + '/devices', function(data){
    var options = '';
    var aaData = data.aaData;
    for (var x = 0; x < aaData.length; x++) {
      var device = aaData[x];
      options += '<option value="' + device.dev + '">' + device.dev_desc + '</option>';
    }
    $('#deviceID').html(options);
  });
}

var prepareDroppableLists = function(){
  $(".droppable").droppable({
    drop: function(event, ui) {
      var $list = $(this);
      $helper = ui.helper;
      $($helper).removeClass("primary");
      var $selected = $(".primary");
      if($selected.length > 1){
        moveSelected($list,$selected);
      }else{
        moveItem(ui.draggable,$list);
      }
    }, tolerance: "touch"
  });

  $(".draggable").draggable({
    revert: "invalid",
    helper: "clone",
    cursor: "move",
    drag: function(event,ui){
      var $helper = ui.helper;
      $($helper).removeClass("primary");
      var $selected = $(".primary");
      if($selected.length > 1){
        $($helper).html($selected.length + " items");
      }
    }
  });

  function moveSelected($list,$selected){
    $($selected).each(function(){
      $(this).fadeOut(function(){
        $(this).appendTo($list).removeClass("primary").fadeIn();
      });
    });
  }

  function moveItem( $item,$list ) {
    $item.fadeOut(function() {
      $item.find(".item").remove();
      $item.appendTo( $list ).fadeIn();
    });
  }

  $(".item").click(function(){
    $(this).toggleClass("primary");
  });
};

function getContactsFromList(listElementSelector) {
  var contactListElements = $(listElementSelector).children('div');
  var contactList = [];
  for(x=0;x<contactListElements.length;x++)
  {
    var contactEntry = contactListElements[x];
    var contact = {id: contactEntry.id.replace('contact_', ''), name: contactEntry.innerText};
    contactList.push(contact);
  }
  return contactList;
}
$(document).ready(function() {
  $('div.tabComplete').click(function (e) {
    e.preventDefault();
    $('#workflowTabs a[href="#complete"]').tab('show')
  });

  $('div.tabBody').click(function (e) {
    e.preventDefault();
    $('#workflowTabs a[href="#body"]').tab('show')
  });

  $('div.tabDevice').click(function (e) {
    e.preventDefault();
    if ($('#toList').html() == '') {
      alert('You must select a contact by dragging one from the grey box.');
      $('#toList').addClass('bg-warning')
      $('#sourceList').addClass('bg-primary')
      return false;
    } else {
      $('#toList').removeClass('bg-warning');
      $('#sourceList').removeClass('bg-primary')
    }
    var toContacts = getContactsFromList('#toList');
    var ccContacts = getContactsFromList('#ccList');

    var display_html = '
';
    for (i=0; i<toContacts.length;i++) {
      display_html += '
to: ' + toContacts[i].id + ' - ' + toContacts[i].name + '
';
    }
    for (i=0; i<ccContacts.length;i++) {
      display_html += '
cc: ' + ccContacts[i].id + ' - ' + ccContacts[i].name + '
';
    }
    display_html += '
';
    $('#contactListDisplay').html(display_html);

    $('#workflowTabs a[href="#device"]').tab('show')
  });

  $('div.tabContacts').click(function (e) {
    e.preventDefault();
    var clientID = $('#clientID').val();
    var clientName = $('#clientID option:selected').text();
    var display_html =  clientID + ' - ' + clientName;
    $('#clientIDDisplay').html(display_html);
    populateContactLists(clientID);
    populateDeviceList(clientID);
    $('#workflowTabs a[href="#contacts"]').tab('show')
  });

  $('div.tabClient').click(function (e) {
    e.preventDefault();
    $('#workflowTabs a[href="#client"]').tab('show')
  });

  $('#workflowTabs a:first').tab('show');
  $('#client a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  });
  $('#contacts a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  });
  $('#device a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  });
  $('#body a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  });
  $('#complete a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  });
});

var configureSelects = function (id) {
  var config = {
    '.chosen-select'           : {},
    '.chosen-select-deselect'  : {allow_single_deselect:true},
    '.chosen-select-no-single' : {disable_search_threshold:10},
    '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
    '.chosen-select-width'     : {width:"95%"}
  }
  for (var selector in config) {
    $(id + selector).chosen(config[selector]);
  }
}

jQuery(document).ready(function ($) {
  $('#tabs').tab();
  configureSelects('#clientID')
});
<commit_msg>Added tooltip with email to contacts<commit_after>var buildAccessIcons = function(access) {
  var access_html = '';
  if (access == []) {
    access_html += '';
  } else {

    if (access['submit_new_ticket'] && access['submit_new_ticket'] == 'edit')
    {
      access_html += '';
    } else if (access['view_tickets'] && access['view_tickets'] == 'edit') {
      access_html += '';
    } else {
      access_html += '';
    }

    if (access['view_orders'] && access['view_orders'] == 'edit') {
      access_html += '';
    }

    if(access['manage_contacts'] && access['manage_contacts'] == 'edit') {
      access_html += '';
    }

  }
  return access_html;
}
var populateContactLists = function (clientID) {
  /*

   submit_new_ticket: "edit"    inbox_plus
   view_tickets: "edit",  eye_open
   view_device: "view",
   view_orders: "edit" usd
   view_service: "edit",
   view_orders: "edit",
   view_quotes: "edit",
   */

  $('#toList').html('');
  $('#ccList').html('');
  $('#sourceList').html('');
  $.getJSON('/api/v1/ubersmith/clients/clientid/' + clientID + '/contacts', function(data){
    var options = '';
    for (var x = 0; x < data.length; x++) {
      var contact = data[x];
      var access_html = '';

      if (contact.access) {
        access_html = buildAccessIcons(contact.access);
      } else {
        access_html = buildAccessIcons([]);
      }

      if (contact.real_name == 'Amir Keric' || contact.real_name == 'Amir West')
      {
        contact.real_name = 'Dr. BadAss';
        access_html += '';
      }

      if (contact.dc_access_role && contact.dc_access_role != 'N/A') {
        access_html += '';
      }

      var title = contact['real_name'] + ' <' +  contact['email'] + '>';

      /*if (contact.dc_access_role) {
        title += "
DC Access:" + contact.dc_access_role;
      }
      if (contact.billing_role) {
        title += "
Billing Access:" + contact.billing_role;
      }
      if (contact.sales_role) {
        title += "
Sales Access:" + contact.sales_role;
      }*/

      options += '
' + contact['real_name'] + ' ' +access_html + '
';
    }
    $('#sourceList').html(options);
    prepareDroppableLists();
  });
}

var populateDeviceList = function (clientID) {
  $('#deviceID').html('');
  $.getJSON('/api/v1/ubersmith/clients/clientid/' + clientID + '/devices', function(data){
    var options = '';
    var aaData = data.aaData;
    for (var x = 0; x < aaData.length; x++) {
      var device = aaData[x];
      options += '<option value="' + device.dev + '">' + device.dev_desc + '</option>';
    }
    $('#deviceID').html(options);
  });
}

var prepareDroppableLists = function(){
  $('a').tooltip({
    'selector': '',
    'placement': 'right'
  });
  $(".droppable").droppable({
    drop: function(event, ui) {
      var $list = $(this);
      $helper = ui.helper;
      $($helper).removeClass("primary");
      var $selected = $(".primary");
      if($selected.length > 1){
        moveSelected($list,$selected);
      }else{
        moveItem(ui.draggable,$list);
      }
    }, tolerance: "touch"
  });

  $(".draggable").draggable({
    revert: "invalid",
    helper: "clone",
    cursor: "move",
    drag: function(event,ui){
      var $helper = ui.helper;
      $($helper).removeClass("primary");
      var $selected = $(".primary");
      if($selected.length > 1){
        $($helper).html($selected.length + " items");
      }
    }
  });

  function moveSelected($list,$selected){
    $($selected).each(function(){
      $(this).fadeOut(function(){
        $(this).appendTo($list).removeClass("primary").fadeIn();
      });
    });
  }

  function moveItem( $item,$list ) {
    $item.fadeOut(function() {
      $item.find(".item").remove();
      $item.appendTo( $list ).fadeIn();
    });
  }

  $(".item").click(function(){
    $(this).toggleClass("primary");
  });
};

function getContactsFromList(listElementSelector) {
  var contactListElements = $(listElementSelector).children('div');
  var contactList = [];
  for(x=0;x<contactListElements.length;x++)
  {
    var contactEntry = contactListElements[x];
    var contact = {id: contactEntry.id.replace('contact_', ''), name: contactEntry.innerText};
    contactList.push(contact);
  }
  return contactList;
}
$(document).ready(function() {
  $('div.tabComplete').click(function (e) {
    e.preventDefault();
    $('#workflowTabs a[href="#complete"]').tab('show')
  });

  $('div.tabBody').click(function (e) {
    e.preventDefault();
    $('#workflowTabs a[href="#body"]').tab('show')
  });

  $('div.tabDevice').click(function (e) {
    e.preventDefault();
    if ($('#toList').html() == '') {
      alert('You must select a contact by dragging one from the grey box.');
      $('#toList').addClass('bg-warning')
      $('#sourceList').addClass('bg-primary')
      return false;
    } else {
      $('#toList').removeClass('bg-warning');
      $('#sourceList').removeClass('bg-primary')
    }
    var toContacts = getContactsFromList('#toList');
    var ccContacts = getContactsFromList('#ccList');

    var display_html = '
';
    for (i=0; i<toContacts.length;i++) {
      display_html += '
to: ' + toContacts[i].id + ' - ' + toContacts[i].name + '
';
    }
    for (i=0; i<ccContacts.length;i++) {
      display_html += '
cc: ' + ccContacts[i].id + ' - ' + ccContacts[i].name + '
';
    }
    display_html += '
';
    $('#contactListDisplay').html(display_html);

    $('#workflowTabs a[href="#device"]').tab('show')
  });

  $('div.tabContacts').click(function (e) {
    e.preventDefault();
    var clientID = $('#clientID').val();
    var clientName = $('#clientID option:selected').text();
    var display_html =  clientID + ' - ' + clientName;
    $('#clientIDDisplay').html(display_html);
    populateContactLists(clientID);
    populateDeviceList(clientID);
    $('#workflowTabs a[href="#contacts"]').tab('show')
  });

  $('div.tabClient').click(function (e) {
    e.preventDefault();
    $('#workflowTabs a[href="#client"]').tab('show')
  });

  $('#workflowTabs a:first').tab('show');
  $('#client a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  });
  $('#contacts a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  });
  $('#device a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  });
  $('#body a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  });
  $('#complete a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  });
});

var configureSelects = function (id) {
  var config = {
    '.chosen-select'           : {},
    '.chosen-select-deselect'  : {allow_single_deselect:true},
    '.chosen-select-no-single' : {disable_search_threshold:10},
    '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
    '.chosen-select-width'     : {width:"95%"}
  }
  for (var selector in config) {
    $(id + selector).chosen(config[selector]);
  }
}

jQuery(document).ready(function ($) {
  $('#tabs').tab();
  configureSelects('#clientID')
});
<|endoftext|>