<commit_before>/*
 * Module for REST API client
 */

import axios from 'axios';
import qs from 'qs';
import heartbeat from 'kolibri.heartbeat';
import logger from 'kolibri.lib.logging';
import store from 'kolibri.coreVue.vuex.store';
import errorCodes from '../disconnectionErrorCodes';
import clientFactory from './baseClient';

export const logging = logger.getLogger(__filename);

const baseClient = clientFactory();

// Disconnection handler interceptor
baseClient.interceptors.request.use(function(config) {
  if (!store.getters.connected) {
    // If the vuex state records that we are not currently connected then cancel all
    // outgoing requests.
    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    config.cancelToken = source.token;
    source.cancel('Request cancelled as currently disconnected from Kolibri');
  }
  return config;
});

// Login timeout detection interceptor and disconnection monitoring
baseClient.interceptors.response.use(
  response => response,
  function(error) {
    // If we receive a 403 response from the server, it is possible that the user
    // is attempting to access information they are not allowed to see.
    // However, more likely, it is because their login has timed out, but the frontend
    // client code is still trying to access data that they would be allowed to see
    // if they were logged in.
    if (error.response) {
      if (error.response.status === 403) {
        if (!store.state.core.session.id) {
          // Don't have any session information, so assume that this
          // page has just been reopened and the session has expired.
          // Redirect now!
          heartbeat.signOutDueToInactivity();
        } else {
          // In this case, we should check right now if they are still logged in
          heartbeat.pollSessionEndPoint();
        }
      }
      // On every error, check to see if the status code is one of our designated
      // disconnection status codes.
      if (errorCodes.includes(error.response.status)) {
        // If so, set our heartbeat module to start monitoring the disconnection state
        heartbeat.monitorDisconnect(error.response.status);
      }
    }
    return Promise.reject(error);
  }
);

const client = options => {
  if (
    options &&
    typeof options === 'object' &&
    !Array.isArray(options) &&
    (!options.method || options.method.toLowerCase() === 'get')
  ) {
    if (!options.params) {
      options.params = {};
    } else {
      options.params = Object.assign({}, options.params);
    }
    // Cache bust by default, but allow it to be turned off
    if (options.cacheBust || typeof options.cacheBust === 'undefined') {
      const cacheBust = new Date().getTime();
      options.params[cacheBust] = cacheBust;
    }
    if (options.path) {
      // Provide backwards compatibility with the previous Rest JS API.
      options.url = options.path;
      delete options.path;
      logging.warn('option path is deprecated, please use url option instead');
    }
  }
  if (typeof options === 'string') {
    options = { url: options };
    logging.warn(
      'passing the URL as the only argument is deprecated, please use url option instead'
    );
  }

  const headers = { ...(options.headers || {}) };
  if (options.multipart) {
    headers['Content-Type'] = 'multipart/form-data';
  }
  return baseClient
    .request({
      ...options,
      headers,
    })
    .then(response => {
      Object.defineProperty(response, 'entity', {
        get() {
          logging.warn(
            'entity is deprecated for accessing response data, please use the data key instead'
          );
          return response.data;
        },
      });
      return response;
    });
};

export default client;

export const httpClient = options => {
  return client({
    ...options,
    method: 'POST',
    headers: { 'content-type': 'application/x-www-form-urlencoded' },
    data: qs.stringify(options.data),
    url: options.url,
  });
};
<commit_msg>Using the right data payload<commit_after>/*
 * Module for REST API client
 */

import axios from 'axios';
import qs from 'qs';
import heartbeat from 'kolibri.heartbeat';
import logger from 'kolibri.lib.logging';
import store from 'kolibri.coreVue.vuex.store';
import errorCodes from '../disconnectionErrorCodes';
import clientFactory from './baseClient';

export const logging = logger.getLogger(__filename);

const baseClient = clientFactory();

// Disconnection handler interceptor
baseClient.interceptors.request.use(function(config) {
  if (!store.getters.connected) {
    // If the vuex state records that we are not currently connected then cancel all
    // outgoing requests.
    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    config.cancelToken = source.token;
    source.cancel('Request cancelled as currently disconnected from Kolibri');
  }
  return config;
});

// Login timeout detection interceptor and disconnection monitoring
baseClient.interceptors.response.use(
  response => response,
  function(error) {
    // If we receive a 403 response from the server, it is possible that the user
    // is attempting to access information they are not allowed to see.
    // However, more likely, it is because their login has timed out, but the frontend
    // client code is still trying to access data that they would be allowed to see
    // if they were logged in.
    if (error.response) {
      if (error.response.status === 403) {
        if (!store.state.core.session.id) {
          // Don't have any session information, so assume that this
          // page has just been reopened and the session has expired.
          // Redirect now!
          heartbeat.signOutDueToInactivity();
        } else {
          // In this case, we should check right now if they are still logged in
          heartbeat.pollSessionEndPoint();
        }
      }
      // On every error, check to see if the status code is one of our designated
      // disconnection status codes.
      if (errorCodes.includes(error.response.status)) {
        // If so, set our heartbeat module to start monitoring the disconnection state
        heartbeat.monitorDisconnect(error.response.status);
      }
    }
    return Promise.reject(error);
  }
);

const client = options => {
  if (
    options &&
    typeof options === 'object' &&
    !Array.isArray(options) &&
    (!options.method || options.method.toLowerCase() === 'get')
  ) {
    if (!options.params) {
      options.params = {};
    } else {
      options.params = Object.assign({}, options.params);
    }
    // Cache bust by default, but allow it to be turned off
    if (options.cacheBust || typeof options.cacheBust === 'undefined') {
      const cacheBust = new Date().getTime();
      options.params[cacheBust] = cacheBust;
    }
    if (options.path) {
      // Provide backwards compatibility with the previous Rest JS API.
      options.url = options.path;
      delete options.path;
      logging.warn('option path is deprecated, please use url option instead');
    }
  }
  if (typeof options === 'string') {
    options = { url: options };
    logging.warn(
      'passing the URL as the only argument is deprecated, please use url option instead'
    );
  }

  const headers = { ...(options.headers || {}) };
  if (options.multipart) {
    headers['Content-Type'] = 'multipart/form-data';
    const fd = new FormData();
    Object.assign(fd, options.data);
    options.data = fd;
  }
  return baseClient
    .request({
      ...options,
      headers,
    })
    .then(response => {
      Object.defineProperty(response, 'entity', {
        get() {
          logging.warn(
            'entity is deprecated for accessing response data, please use the data key instead'
          );
          return response.data;
        },
      });
      return response;
    });
};

export default client;

export const httpClient = options => {
  return client({
    ...options,
    method: 'POST',
    headers: { 'content-type': 'application/x-www-form-urlencoded' },
    data: qs.stringify(options.data),
    url: options.url,
  });
};
<|endoftext|>


<commit_before>/* global requestAnimationFrame */

export async function waitForGLTFAssets(gltfObjects) {
  const remaining = [];

  gltfObjects.scenes.forEach(scene => {
    scene.traverse(model => {
      Object.values(model.model.uniforms).forEach(uniform => {
        if (uniform.loaded === false) {
          remaining.push(uniform);
        }
      });
    });
  });

  return await waitWhileCondition(() => remaining.some(uniform => !uniform.loaded));
}

async function waitWhileCondition(condition) {
  while (condition()) {
    await new Promise(resolve => requestAnimationFrame(resolve));
  }
}
<commit_msg>Tweak to scenegraph layer fix (#4027)<commit_after>/* global requestAnimationFrame */

export async function waitForGLTFAssets(gltfObjects) {
  const remaining = [];

  gltfObjects.scenes.forEach(scene => {
    scene.traverse(model => {
      Object.values(model.model.getUniforms()).forEach(uniform => {
        if (uniform.loaded === false) {
          remaining.push(uniform);
        }
      });
    });
  });

  return await waitWhileCondition(() => remaining.some(uniform => !uniform.loaded));
}

async function waitWhileCondition(condition) {
  while (condition()) {
    await new Promise(resolve => requestAnimationFrame(resolve));
  }
}
<|endoftext|>


<commit_before>/*
 * Module for REST API client
 */

import interceptor from 'rest/interceptor';
import mime from 'rest/interceptor/mime';
import heartbeat from 'kolibri.heartbeat';
import store from 'kolibri.coreVue.vuex.store';
import errorCodes from '../disconnectionErrorCodes';
import baseClient from './baseClient';

const disconnectInterceptor = interceptor({
  request: function(request) {
    if (!store.getters.connected) {
      // If the vuex state records that we are not currently connected then cancel all
      // outgoing requests.
      if (request.cancel) {
        // If the request has a cancel method, call it.
        request.cancel();
      }
      // Set the request as canceled
      request.canceled = true;
    }
    return request;
  },
  response: function(response) {
    if (response.request && response.request.canceled) {
      // If a request has been canceled, reject the response and throw an error
      return Promise.reject(response);
    }
    return response;
  },
});

const loginTimeoutDetection = interceptor({
  error: function(response) {
    // If we receive a 403 response from the server, it is possible that the user
    // is attempting to access information they are not allowed to see.
    // However, more likely, it is because their login has timed out, but the frontend
    // client code is still trying to access data that they would be allowed to see
    // if they were logged in.
    if (response.status && response.status.code === 403) {
      if (!store.state.core.session.id) {
        // Don't have any session information, so assume that this
        // page has just been reopened and the session has expired.
        // Redirect now!
        heartbeat.signOutDueToInactivity();
      } else {
        // In this case, we should check right now if they are still logged in
        heartbeat.pollSessionEndPoint();
      }
    }
    return Promise.reject(response);
  },
});

const serverDisconnectDetection = interceptor({
  response: function(response) {
    // On every response, check to see if the status code is one of our designated
    // disconnection status codes.
    if (response.status && errorCodes.includes(response.status.code)) {
      // If so, set our heartbeat module to start monitoring the disconnection state
      heartbeat.monitorDisconnect(response.status.code);
      // Return an error
      return Promise.reject(response);
    }
    return response;
  },
});

const client = options => {
  if (
    options &&
    typeof options === 'object' &&
    !Array.isArray(options) &&
    (!options.method || options.method === 'GET')
  ) {
    if (!options.params) {
      options.params = {};
    } else {
      options.params = Object.assign({}, options.params);
    }
    // Cache bust by default, but allow it to be turned off
    if (options.cacheBust || typeof options.cacheBust === 'undefined') {
      const cacheBust = new Date().getTime();
      options.params[cacheBust] = cacheBust;
    }
  }
  let mimeType = 'application/json';
  // in case a File obj must be POSTed:
  if (options.entity !== 'undefined' && options.method === 'POST') {
    if (
      Object.values(options.entity).filter(function(a) {
        return typeof a === 'object';
      }).length > 0
    )
      mimeType = 'multipart/form-data';
  }
  return baseClient
    .wrap(disconnectInterceptor)
    .wrap(mime, { mime: mimeType })
    .wrap(loginTimeoutDetection)
    .wrap(serverDisconnectDetection)(options)
    .then(response => {
      if (response.request && response.request.canceled) {
        return Promise.reject(response);
      }
      return response;
    });
};

export default client;

export const httpClient = baseClient
  .wrap(disconnectInterceptor)
  .wrap(mime, {
    mime: 'application/x-www-form-urlencoded',
  })
  .wrap(loginTimeoutDetection)
  .wrap(serverDisconnectDetection);
<commit_msg>Update kolibri/core/assets/src/core-app/client.js<commit_after>/*
 * Module for REST API client
 */

import interceptor from 'rest/interceptor';
import mime from 'rest/interceptor/mime';
import heartbeat from 'kolibri.heartbeat';
import store from 'kolibri.coreVue.vuex.store';
import errorCodes from '../disconnectionErrorCodes';
import baseClient from './baseClient';

const disconnectInterceptor = interceptor({
  request: function(request) {
    if (!store.getters.connected) {
      // If the vuex state records that we are not currently connected then cancel all
      // outgoing requests.
      if (request.cancel) {
        // If the request has a cancel method, call it.
        request.cancel();
      }
      // Set the request as canceled
      request.canceled = true;
    }
    return request;
  },
  response: function(response) {
    if (response.request && response.request.canceled) {
      // If a request has been canceled, reject the response and throw an error
      return Promise.reject(response);
    }
    return response;
  },
});

const loginTimeoutDetection = interceptor({
  error: function(response) {
    // If we receive a 403 response from the server, it is possible that the user
    // is attempting to access information they are not allowed to see.
    // However, more likely, it is because their login has timed out, but the frontend
    // client code is still trying to access data that they would be allowed to see
    // if they were logged in.
    if (response.status && response.status.code === 403) {
      if (!store.state.core.session.id) {
        // Don't have any session information, so assume that this
        // page has just been reopened and the session has expired.
        // Redirect now!
        heartbeat.signOutDueToInactivity();
      } else {
        // In this case, we should check right now if they are still logged in
        heartbeat.pollSessionEndPoint();
      }
    }
    return Promise.reject(response);
  },
});

const serverDisconnectDetection = interceptor({
  response: function(response) {
    // On every response, check to see if the status code is one of our designated
    // disconnection status codes.
    if (response.status && errorCodes.includes(response.status.code)) {
      // If so, set our heartbeat module to start monitoring the disconnection state
      heartbeat.monitorDisconnect(response.status.code);
      // Return an error
      return Promise.reject(response);
    }
    return response;
  },
});

const client = options => {
  if (
    options &&
    typeof options === 'object' &&
    !Array.isArray(options) &&
    (!options.method || options.method === 'GET')
  ) {
    if (!options.params) {
      options.params = {};
    } else {
      options.params = Object.assign({}, options.params);
    }
    // Cache bust by default, but allow it to be turned off
    if (options.cacheBust || typeof options.cacheBust === 'undefined') {
      const cacheBust = new Date().getTime();
      options.params[cacheBust] = cacheBust;
    }
  }
  let mimeType = 'application/json';
  // in case a File obj must be POSTed:
  if (options.entity !== 'undefined' && options.method === 'POST') {
    if (
      Object.values(options.entity).filter(a => typeof a === 'object').length
    )
      mimeType = 'multipart/form-data';
  }
  return baseClient
    .wrap(disconnectInterceptor)
    .wrap(mime, { mime: mimeType })
    .wrap(loginTimeoutDetection)
    .wrap(serverDisconnectDetection)(options)
    .then(response => {
      if (response.request && response.request.canceled) {
        return Promise.reject(response);
      }
      return response;
    });
};

export default client;

export const httpClient = baseClient
  .wrap(disconnectInterceptor)
  .wrap(mime, {
    mime: 'application/x-www-form-urlencoded',
  })
  .wrap(loginTimeoutDetection)
  .wrap(serverDisconnectDetection);
<|endoftext|>


<commit_before>var securityws = (function(){

    "use strict";
    var $form ;

    var clearErrors = function(){
        $("#SecuritySuccessMsg").text('');
        $("#errorcashierlockpassword1").text('');
        $("#errorcashierlockpassword2").text('');
        $("#client_message_content").text('');
        $("#client_message_content").hide();

    };

    var init = function(){
        $form   = $("#changeCashierLock");
        $("#repasswordrow").show();
        $("#changeCashierLock").show();

        clearErrors();
        $form.find("button").attr("value","Update");

        $form.find("button").on("click", function(e){
            e.preventDefault();
            e.stopPropagation();
            if(validateForm() === false){
                return false;
            }
            if($(this).attr("value") === "Update"){
                BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "lock_password"}});
            }
            else{
                BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "unlock_password"}});
            }
        });
        BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "is_locked"}});
    };

    var validateForm = function(){
        var isValid = true;

        clearErrors();

        var pwd1 = $("#cashierlockpassword1").val();
        var pwd2 = $("#cashierlockpassword2").val();
        var isVisible = $("#repasswordrow").is(':visible');

        if(pwd1.length <= 0 ){
            $("#errorcashierlockpassword1").text(text.localize("Please enter a password."));
            isValid = false;
        }
        else if(pwd1.length > 25){
            $("#errorcashierlockpassword1").text(text.localize("password can't be longer than 25."));
            isValid = false;
        }else if(pwd1.length < 6 ){
            $("#errorcashierlockpassword1").text(text.localize("Your password should be at least 6 characters."));
            isValid = false;
        }

        if(isVisible === true){

            if(pwd2.length <= 0 ){
                $("#errorcashierlockpassword2").text(text.localize("Please enter a password."));
                isValid = false;
            }
            else if(pwd2.length > 25){
                $("#errorcashierlockpassword2").text(text.localize("password can't be longer than 25."));
                isValid = false;
            }else if(pwd2.length < 6 ){
                $("#errorcashierlockpassword2").text(text.localize("Your password should be at least 6 characters."));
                isValid = false;
            }else if(pwd1 !== pwd2 ){
                $("#errorcashierlockpassword2").text(text.localize("The two passwords that you entered do not match."));
                isValid = false;
            }
        }

        return isValid;
    };
    var isAuthorized =  function(response){
        if(response.echo_req.passthrough){
            var option= response.echo_req.passthrough.value ;
            var pwd = $("#cashierlockpassword1").val();

            switch(option){
                case   "lock_password" :
                        BinarySocket.send({
                            "cashier_password": "1",
                            "lock_password": pwd
                        });
                        break;
                case   "unlock_password" :
                        BinarySocket.send({
                            "cashier_password": "1",
                            "unlock_password": pwd
                        });
                        break;
                case   "is_locked" :
                        BinarySocket.send({
                            "cashier_password": "1",
                            "passthrough" : {"value" : "lock_status"}
                        });
                        break ;
            }
        }
    };
    var responseMessage = function(response){

       var resvalue;

       if(response.echo_req.passthrough && (response.echo_req.passthrough.value === "lock_status") ){
            var passthrough = response.echo_req.passthrough.value;
            resvalue = response.cashier_password;
            if(parseInt(resvalue) === 1){
                $("#repasswordrow").hide();
                $("legend").text(text.localize("Unlock Cashier"));
                $("#lockInfo").text(text.localize("Your cashier is locked as per your request - to unlock it, please enter the password."));
                $form.find("button").attr("value","Unlock Cashier");
                $form.find("button").html("Unlock Cashier");

            }
            else if(parseInt(resvalue) === 0){
                $("#repasswordrow").show();
                $("legend").text(text.localize("lock Cashier"));
                $("#lockInfo").text(text.localize("An additional password can be used to restrict access to the cashier."));
                $form.find("button").attr("value","Update");
                $form.find("button").html("Update");
            }

        }
        else{
            if("error" in response) {
                if("message" in response.error) {
                    $("#client_message_content").show();
                    $("#client_message_content").text(text.localize(response.error.message));
                }
                return false;
            }
            else{

                resvalue = response.echo_req.cashier_password;
                if(parseInt(resvalue) === 1){
                    $("#changeCashierLock").hide();
                    $("#client_message_content").hide();
                    $("#SecuritySuccessMsg").text(text.localize('Your settings have been updated successfully.'));
                }
                else{
                    $("#client_message_content").show();
                    $("#client_message_content").text(text.localize('Sorry, an error occurred while processing your account.'));

                    return false;
                }
            }
        }
        return;
    };
    var SecurityApiResponse = function(response){
        var type = response.msg_type;
        if (type === "cashier_password" || (type === "error" && "cashier_password" in response.echo_req)){
           responseMessage(response);

        }else if(type === "authorize" || (type === "error" && "authorize" in response.echo_req))
        {
            isAuthorized(response);
        }
    };

    return {
        init : init,
        SecurityApiResponse : SecurityApiResponse
    };
})();

pjax_config_page("user/settings/securityws", function() {
    return {
        onLoad: function() {
        	if (!getCookieItem('login')) {
                window.location.href = page.url.url_for('login');
                return;
            }
            if((/VRT/.test($.cookie('loginid')))){
                window.location.href = ("/");
            }

        	BinarySocket.init({
                onmessage: function(msg){
                    var response = JSON.parse(msg.data);
                    if (response) {
                        securityws.SecurityApiResponse(response);

                    }
                }
            });

            securityws.init();
        }
    };
});<commit_msg>Adding aschii check<commit_after>var securityws = (function(){

    "use strict";
    var $form ;

    var clearErrors = function(){
        $("#SecuritySuccessMsg").text('');
        $("#errorcashierlockpassword1").text('');
        $("#errorcashierlockpassword2").text('');
        $("#client_message_content").text('');
        $("#client_message_content").hide();

    };

    var init = function(){
        $form   = $("#changeCashierLock");
        $("#repasswordrow").show();
        $("#changeCashierLock").show();

        clearErrors();
        $form.find("button").attr("value","Update");

        $form.find("button").on("click", function(e){
            e.preventDefault();
            e.stopPropagation();
            if(validateForm() === false){
                return false;
            }
            if($(this).attr("value") === "Update"){
                BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "lock_password"}});
            }
            else{
                BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "unlock_password"}});
            }
        });
        BinarySocket.send({"authorize": $.cookie('login'), "passthrough": {"value": "is_locked"}});
    };

    var validateForm = function(){
        var isValid = true;
        var regexp = new RegExp('^[ -~]+$');

        clearErrors();

        var pwd1 = $("#cashierlockpassword1").val();
        var pwd2 = $("#cashierlockpassword2").val();
        var isVisible = $("#repasswordrow").is(':visible');

        if(pwd1.length <= 0 ){
            $("#errorcashierlockpassword1").text(text.localize("Please enter a password."));
            isValid = false;
        }
        else if(pwd1.length > 25){
            $("#errorcashierlockpassword1").text(text.localize("password can't be longer than 25."));
            isValid = false;
        }else if(pwd1.length < 6 ){
            $("#errorcashierlockpassword1").text(text.localize("Your password should be at least 6 characters."));
            isValid = false;
        }else if(!regexp.test(pwd1)){
            $("#errorcashierlockpassword1").text(text.localize("Your password contains invalid characters."));
            isValid = false;
        }

        if(isVisible === true){

            if(pwd2.length <= 0 ){
                $("#errorcashierlockpassword2").text(text.localize("Please enter a password."));
                isValid = false;
            }
            else if(pwd2.length > 25){
                $("#errorcashierlockpassword2").text(text.localize("password can't be longer than 25."));
                isValid = false;
            }else if(pwd2.length < 6 ){
                $("#errorcashierlockpassword2").text(text.localize("Your password should be at least 6 characters."));
                isValid = false;
            }else if(pwd1 !== pwd2 ){
                $("#errorcashierlockpassword2").text(text.localize("The two passwords that you entered do not match."));
                isValid = false;
            }
        }

        return isValid;
    };
    var isAuthorized =  function(response){
        if(response.echo_req.passthrough){
            var option= response.echo_req.passthrough.value ;
            var pwd = $("#cashierlockpassword1").val();

            switch(option){
                case   "lock_password" :
                        BinarySocket.send({
                            "cashier_password": "1",
                            "lock_password": pwd
                        });
                        break;
                case   "unlock_password" :
                        BinarySocket.send({
                            "cashier_password": "1",
                            "unlock_password": pwd
                        });
                        break;
                case   "is_locked" :
                        BinarySocket.send({
                            "cashier_password": "1",
                            "passthrough" : {"value" : "lock_status"}
                        });
                        break ;
            }
        }
    };
    var responseMessage = function(response){

       var resvalue;

       if(response.echo_req.passthrough && (response.echo_req.passthrough.value === "lock_status") ){
            var passthrough = response.echo_req.passthrough.value;
            resvalue = response.cashier_password;
            if(parseInt(resvalue) === 1){
                $("#repasswordrow").hide();
                $("legend").text(text.localize("Unlock Cashier"));
                $("#lockInfo").text(text.localize("Your cashier is locked as per your request - to unlock it, please enter the password."));
                $form.find("button").attr("value","Unlock Cashier");
                $form.find("button").html("Unlock Cashier");

            }
            else if(parseInt(resvalue) === 0){
                $("#repasswordrow").show();
                $("legend").text(text.localize("lock Cashier"));
                $("#lockInfo").text(text.localize("An additional password can be used to restrict access to the cashier."));
                $form.find("button").attr("value","Update");
                $form.find("button").html("Update");
            }

        }
        else{
            if("error" in response) {
                if("message" in response.error) {
                    $("#client_message_content").show();
                    $("#client_message_content").text(text.localize(response.error.message));
                }
                return false;
            }
            else{

                resvalue = response.echo_req.cashier_password;
                if(parseInt(resvalue) === 1){
                    $("#changeCashierLock").hide();
                    $("#client_message_content").hide();
                    $("#SecuritySuccessMsg").text(text.localize('Your settings have been updated successfully.'));
                }
                else{
                    $("#client_message_content").show();
                    $("#client_message_content").text(text.localize('Sorry, an error occurred while processing your account.'));

                    return false;
                }
            }
        }
        return;
    };
    var SecurityApiResponse = function(response){
        var type = response.msg_type;
        if (type === "cashier_password" || (type === "error" && "cashier_password" in response.echo_req)){
           responseMessage(response);

        }else if(type === "authorize" || (type === "error" && "authorize" in response.echo_req))
        {
            isAuthorized(response);
        }
    };

    return {
        init : init,
        SecurityApiResponse : SecurityApiResponse
    };
})();

pjax_config_page("user/settings/securityws", function() {
    return {
        onLoad: function() {
        	if (!getCookieItem('login')) {
                window.location.href = page.url.url_for('login');
                return;
            }
            if((/VRT/.test($.cookie('loginid')))){
                window.location.href = ("/");
            }

        	BinarySocket.init({
                onmessage: function(msg){
                    var response = JSON.parse(msg.data);
                    if (response) {
                        securityws.SecurityApiResponse(response);

                    }
                }
            });

            securityws.init();
        }
    };
});<|endoftext|>


<commit_before>/**
 * @author Mat Groves http://matgroves.com/
 */

/**
 * A tiling sprite is a fast way of rendering a tiling image
 *
 * @class TilingSprite
 * @extends Sprite
 * @constructor
 * @param texture {Texture} the texture of the tiling sprite
 * @param width {Number}  the width of the tiling sprite
 * @param height {Number} the height of the tiling sprite
 */
PIXI.TilingSprite = function(texture, width, height)
{
    PIXI.Sprite.call( this, texture);

    /**
     * The with of the tiling sprite
     *
     * @property width
     * @type Number
     */
    this._width = width || 100;

    /**
     * The height of the tiling sprite
     *
     * @property height
     * @type Number
     */
    this._height = height || 100;

    /**
     * The scaling of the image that is being tiled
     *
     * @property tileScale
     * @type Point
     */
    this.tileScale = new PIXI.Point(1,1);

    /**
     * A point that represents the scale of the texture object
     *
     * @property tileScaleOffset
     * @type Point
     */
    this.tileScaleOffset = new PIXI.Point(1,1);

    /**
     * The offset position of the image that is being tiled
     *
     * @property tilePosition
     * @type Point
     */
    this.tilePosition = new PIXI.Point(0,0);

    /**
     * Whether this sprite is renderable or not
     *
     * @property renderable
     * @type Boolean
     * @default true
     */
    this.renderable = true;

    /**
     * The tint applied to the sprite. This is a hex value
     *
     * @property tint
     * @type Number
     * @default 0xFFFFFF
     */
    this.tint = 0xFFFFFF;

    /**
     * The blend mode to be applied to the sprite
     *
     * @property blendMode
     * @type Number
     * @default PIXI.blendModes.NORMAL;
     */
    this.blendMode = PIXI.blendModes.NORMAL;

};

// constructor
PIXI.TilingSprite.prototype = Object.create(PIXI.Sprite.prototype);
PIXI.TilingSprite.prototype.constructor = PIXI.TilingSprite;

/**
 * The width of the sprite, setting this will actually modify the scale to achieve the value set
 *
 * @property width
 * @type Number
 */
Object.defineProperty(PIXI.TilingSprite.prototype, 'width', {
    get: function() {
        return this._width;
    },
    set: function(value) {

        this._width = value;
    }
});

/**
 * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
 *
 * @property height
 * @type Number
 */
Object.defineProperty(PIXI.TilingSprite.prototype, 'height', {
    get: function() {
        return  this._height;
    },
    set: function(value) {
        this._height = value;
    }
});

PIXI.TilingSprite.prototype.setTexture = function(texture)
{
    if (this.texture === texture) return;

    this.texture = texture;

    this.refreshTexture = true;

    this.cachedTint = 0xFFFFFF;
};

/**
* Renders the object using the WebGL renderer
*
* @method _renderWebGL
* @param renderSession {RenderSession}
* @private
*/
PIXI.TilingSprite.prototype._renderWebGL = function(renderSession)
{
    if (this.visible === false || this.alpha === 0) return;
    var i,j;

    if (this._mask)
    {
        renderSession.spriteBatch.stop();
        renderSession.maskManager.pushMask(this.mask, renderSession);
        renderSession.spriteBatch.start();
    }

    if (this._filters)
    {
        renderSession.spriteBatch.flush();
        renderSession.filterManager.pushFilter(this._filterBlock);
    }

    if (!this.tilingTexture || this.refreshTexture)
    {
        this.generateTilingTexture(true);

        if (this.tilingTexture && this.tilingTexture.needsUpdate)
        {
            //TODO - tweaking
            PIXI.updateWebGLTexture(this.tilingTexture.baseTexture, renderSession.gl);
            this.tilingTexture.needsUpdate = false;
           // this.tilingTexture._uvs = null;
        }
    }
    else
    {
        renderSession.spriteBatch.renderTilingSprite(this);
    }
    // simple render children!
    for (i=0,j=this.children.length; i<j; i++)
    {
        this.children[i]._renderWebGL(renderSession);
    }

    renderSession.spriteBatch.stop();

    if (this._filters) renderSession.filterManager.popFilter();
    if (this._mask) renderSession.maskManager.popMask(renderSession);

    renderSession.spriteBatch.start();
};

/**
* Renders the object using the Canvas renderer
*
* @method _renderCanvas
* @param renderSession {RenderSession}
* @private
*/
PIXI.TilingSprite.prototype._renderCanvas = function(renderSession)
{
    if (this.visible === false || this.alpha === 0)return;

    var context = renderSession.context;

    if (this._mask)
    {
        renderSession.maskManager.pushMask(this._mask, context);
    }

    context.globalAlpha = this.worldAlpha;

    var transform = this.worldTransform;

    var i,j;

    context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx , transform.ty);

    if (!this.__tilePattern ||  this.refreshTexture)
    {
        this.generateTilingTexture(false);

        if (this.tilingTexture)
        {
            this.__tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat');
        }
        else
        {
            return;
        }
    }

    // check blend mode
    if (this.blendMode !== renderSession.currentBlendMode)
    {
        renderSession.currentBlendMode = this.blendMode;
        context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
    }

    var tilePosition = this.tilePosition;
    var tileScale = this.tileScale;

    tilePosition.x %= this.tilingTexture.baseTexture.width;
    tilePosition.y %= this.tilingTexture.baseTexture.height;

    // offset
    context.scale(tileScale.x,tileScale.y);
    context.translate(tilePosition.x, tilePosition.y);

    context.fillStyle = this.__tilePattern;

    // make sure to account for the anchor point..
    context.fillRect(-tilePosition.x + (this.anchor.x * -this._width),
                    -tilePosition.y + (this.anchor.y * -this._height),
                    this._width / tileScale.x,
                    this._height / tileScale.y);

    context.scale(1 / tileScale.x, 1 / tileScale.y);
    context.translate(-tilePosition.x, -tilePosition.y);

    if (this._mask)
    {
        renderSession.maskManager.popMask(renderSession.context);
    }

    for (i=0,j=this.children.length; i<j; i++)
    {
        this.children[i]._renderCanvas(renderSession);
    }
};

/**
* Returns the framing rectangle of the sprite as a PIXI.Rectangle object
*
* @method getBounds
* @return {Rectangle} the framing rectangle
*/
PIXI.TilingSprite.prototype.getBounds = function()
{
    var width = this._width;
    var height = this._height;

    var w0 = width * (1-this.anchor.x);
    var w1 = width * -this.anchor.x;

    var h0 = height * (1-this.anchor.y);
    var h1 = height * -this.anchor.y;

    var worldTransform = this.worldTransform;

    var a = worldTransform.a;
    var b = worldTransform.c;
    var c = worldTransform.b;
    var d = worldTransform.d;
    var tx = worldTransform.tx;
    var ty = worldTransform.ty;

    var x1 = a * w1 + c * h1 + tx;
    var y1 = d * h1 + b * w1 + ty;

    var x2 = a * w0 + c * h1 + tx;
    var y2 = d * h1 + b * w0 + ty;

    var x3 = a * w0 + c * h0 + tx;
    var y3 = d * h0 + b * w0 + ty;

    var x4 =  a * w1 + c * h0 + tx;
    var y4 =  d * h0 + b * w1 + ty;

    var maxX = -Infinity;
    var maxY = -Infinity;

    var minX = Infinity;
    var minY = Infinity;

    minX = x1 < minX ? x1 : minX;
    minX = x2 < minX ? x2 : minX;
    minX = x3 < minX ? x3 : minX;
    minX = x4 < minX ? x4 : minX;

    minY = y1 < minY ? y1 : minY;
    minY = y2 < minY ? y2 : minY;
    minY = y3 < minY ? y3 : minY;
    minY = y4 < minY ? y4 : minY;

    maxX = x1 > maxX ? x1 : maxX;
    maxX = x2 > maxX ? x2 : maxX;
    maxX = x3 > maxX ? x3 : maxX;
    maxX = x4 > maxX ? x4 : maxX;

    maxY = y1 > maxY ? y1 : maxY;
    maxY = y2 > maxY ? y2 : maxY;
    maxY = y3 > maxY ? y3 : maxY;
    maxY = y4 > maxY ? y4 : maxY;

    var bounds = this._bounds;

    bounds.x = minX;
    bounds.width = maxX - minX;

    bounds.y = minY;
    bounds.height = maxY - minY;

    // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
    this._currentBounds = bounds;

    return bounds;
};

/**
 * When the texture is updated, this event will fire to update the scale and frame
 *
 * @method onTextureUpdate
 * @param event
 * @private
 */
PIXI.TilingSprite.prototype.onTextureUpdate = function()
{
   // overriding the sprite version of this!
};

/**
*
* @method generateTilingTexture
*
* @param forcePowerOfTwo {Boolean} Whether we want to force the texture to be a power of two
*/
PIXI.TilingSprite.prototype.generateTilingTexture = function(forcePowerOfTwo)
{
    if (!this.texture.baseTexture.hasLoaded) return;

    var texture = this.texture;
    var frame = texture.frame;
    var targetWidth, targetHeight;

    //  Check that the frame is the same size as the base texture.
    var isFrame = frame.width !== texture.baseTexture.width || frame.height !== texture.baseTexture.height;

    var newTextureRequired = false;

    if (!forcePowerOfTwo)
    {
        if (isFrame)
        {
            targetWidth = frame.width;
            targetHeight = frame.height;

            newTextureRequired = true;
        }
    }
    else
    {
        targetWidth = PIXI.getNextPowerOfTwo(frame.width);
        targetHeight = PIXI.getNextPowerOfTwo(frame.height);

        if (frame.width !== targetWidth || frame.height !== targetHeight) newTextureRequired = true;
    }

    if (newTextureRequired)
    {
        var canvasBuffer;

        if (this.tilingTexture && this.tilingTexture.isTiling)
        {
            canvasBuffer = this.tilingTexture.canvasBuffer;
            canvasBuffer.resize(targetWidth, targetHeight);
            this.tilingTexture.baseTexture.width = targetWidth;
            this.tilingTexture.baseTexture.height = targetHeight;
            this.tilingTexture.needsUpdate = true;
        }
        else
        {
            canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight);

            this.tilingTexture = PIXI.Texture.fromCanvas(canvasBuffer.canvas);
            this.tilingTexture.canvasBuffer = canvasBuffer;
            this.tilingTexture.isTiling = true;
        }

        canvasBuffer.context.drawImage(texture.baseTexture.source,
                               texture.crop.x,
                               texture.crop.y,
                               texture.crop.width,
                               texture.crop.height,
                               0,
                               0,
                               targetWidth,
                               targetHeight);

        this.tileScaleOffset.x = frame.width / targetWidth;
        this.tileScaleOffset.y = frame.height / targetHeight;
    }
    else
    {
        //  TODO - switching?
        if (this.tilingTexture && this.tilingTexture.isTiling)
        {
            // destroy the tiling texture!
            // TODO could store this somewhere?
            this.tilingTexture.destroy(true);
        }

        this.tileScaleOffset.x = 1;
        this.tileScaleOffset.y = 1;
        this.tilingTexture = texture;
    }

    this.refreshTexture = false;
    this.tilingTexture.baseTexture._powerOf2 = true;
};<commit_msg>TilingSprite._renderWebGL: missing mask argument in renderSession.maskManager.popMask call<commit_after>/**
 * @author Mat Groves http://matgroves.com/
 */

/**
 * A tiling sprite is a fast way of rendering a tiling image
 *
 * @class TilingSprite
 * @extends Sprite
 * @constructor
 * @param texture {Texture} the texture of the tiling sprite
 * @param width {Number}  the width of the tiling sprite
 * @param height {Number} the height of the tiling sprite
 */
PIXI.TilingSprite = function(texture, width, height)
{
    PIXI.Sprite.call( this, texture);

    /**
     * The with of the tiling sprite
     *
     * @property width
     * @type Number
     */
    this._width = width || 100;

    /**
     * The height of the tiling sprite
     *
     * @property height
     * @type Number
     */
    this._height = height || 100;

    /**
     * The scaling of the image that is being tiled
     *
     * @property tileScale
     * @type Point
     */
    this.tileScale = new PIXI.Point(1,1);

    /**
     * A point that represents the scale of the texture object
     *
     * @property tileScaleOffset
     * @type Point
     */
    this.tileScaleOffset = new PIXI.Point(1,1);

    /**
     * The offset position of the image that is being tiled
     *
     * @property tilePosition
     * @type Point
     */
    this.tilePosition = new PIXI.Point(0,0);

    /**
     * Whether this sprite is renderable or not
     *
     * @property renderable
     * @type Boolean
     * @default true
     */
    this.renderable = true;

    /**
     * The tint applied to the sprite. This is a hex value
     *
     * @property tint
     * @type Number
     * @default 0xFFFFFF
     */
    this.tint = 0xFFFFFF;

    /**
     * The blend mode to be applied to the sprite
     *
     * @property blendMode
     * @type Number
     * @default PIXI.blendModes.NORMAL;
     */
    this.blendMode = PIXI.blendModes.NORMAL;

};

// constructor
PIXI.TilingSprite.prototype = Object.create(PIXI.Sprite.prototype);
PIXI.TilingSprite.prototype.constructor = PIXI.TilingSprite;

/**
 * The width of the sprite, setting this will actually modify the scale to achieve the value set
 *
 * @property width
 * @type Number
 */
Object.defineProperty(PIXI.TilingSprite.prototype, 'width', {
    get: function() {
        return this._width;
    },
    set: function(value) {

        this._width = value;
    }
});

/**
 * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
 *
 * @property height
 * @type Number
 */
Object.defineProperty(PIXI.TilingSprite.prototype, 'height', {
    get: function() {
        return  this._height;
    },
    set: function(value) {
        this._height = value;
    }
});

PIXI.TilingSprite.prototype.setTexture = function(texture)
{
    if (this.texture === texture) return;

    this.texture = texture;

    this.refreshTexture = true;

    this.cachedTint = 0xFFFFFF;
};

/**
* Renders the object using the WebGL renderer
*
* @method _renderWebGL
* @param renderSession {RenderSession}
* @private
*/
PIXI.TilingSprite.prototype._renderWebGL = function(renderSession)
{
    if (this.visible === false || this.alpha === 0) return;
    var i,j;

    if (this._mask)
    {
        renderSession.spriteBatch.stop();
        renderSession.maskManager.pushMask(this.mask, renderSession);
        renderSession.spriteBatch.start();
    }

    if (this._filters)
    {
        renderSession.spriteBatch.flush();
        renderSession.filterManager.pushFilter(this._filterBlock);
    }

    if (!this.tilingTexture || this.refreshTexture)
    {
        this.generateTilingTexture(true);

        if (this.tilingTexture && this.tilingTexture.needsUpdate)
        {
            //TODO - tweaking
            PIXI.updateWebGLTexture(this.tilingTexture.baseTexture, renderSession.gl);
            this.tilingTexture.needsUpdate = false;
           // this.tilingTexture._uvs = null;
        }
    }
    else
    {
        renderSession.spriteBatch.renderTilingSprite(this);
    }
    // simple render children!
    for (i=0,j=this.children.length; i<j; i++)
    {
        this.children[i]._renderWebGL(renderSession);
    }

    renderSession.spriteBatch.stop();

    if (this._filters) renderSession.filterManager.popFilter();
    if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession);

    renderSession.spriteBatch.start();
};

/**
* Renders the object using the Canvas renderer
*
* @method _renderCanvas
* @param renderSession {RenderSession}
* @private
*/
PIXI.TilingSprite.prototype._renderCanvas = function(renderSession)
{
    if (this.visible === false || this.alpha === 0)return;

    var context = renderSession.context;

    if (this._mask)
    {
        renderSession.maskManager.pushMask(this._mask, context);
    }

    context.globalAlpha = this.worldAlpha;

    var transform = this.worldTransform;

    var i,j;

    context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx , transform.ty);

    if (!this.__tilePattern ||  this.refreshTexture)
    {
        this.generateTilingTexture(false);

        if (this.tilingTexture)
        {
            this.__tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat');
        }
        else
        {
            return;
        }
    }

    // check blend mode
    if (this.blendMode !== renderSession.currentBlendMode)
    {
        renderSession.currentBlendMode = this.blendMode;
        context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
    }

    var tilePosition = this.tilePosition;
    var tileScale = this.tileScale;

    tilePosition.x %= this.tilingTexture.baseTexture.width;
    tilePosition.y %= this.tilingTexture.baseTexture.height;

    // offset
    context.scale(tileScale.x,tileScale.y);
    context.translate(tilePosition.x, tilePosition.y);

    context.fillStyle = this.__tilePattern;

    // make sure to account for the anchor point..
    context.fillRect(-tilePosition.x + (this.anchor.x * -this._width),
                    -tilePosition.y + (this.anchor.y * -this._height),
                    this._width / tileScale.x,
                    this._height / tileScale.y);

    context.scale(1 / tileScale.x, 1 / tileScale.y);
    context.translate(-tilePosition.x, -tilePosition.y);

    if (this._mask)
    {
        renderSession.maskManager.popMask(renderSession.context);
    }

    for (i=0,j=this.children.length; i<j; i++)
    {
        this.children[i]._renderCanvas(renderSession);
    }
};

/**
* Returns the framing rectangle of the sprite as a PIXI.Rectangle object
*
* @method getBounds
* @return {Rectangle} the framing rectangle
*/
PIXI.TilingSprite.prototype.getBounds = function()
{
    var width = this._width;
    var height = this._height;

    var w0 = width * (1-this.anchor.x);
    var w1 = width * -this.anchor.x;

    var h0 = height * (1-this.anchor.y);
    var h1 = height * -this.anchor.y;

    var worldTransform = this.worldTransform;

    var a = worldTransform.a;
    var b = worldTransform.c;
    var c = worldTransform.b;
    var d = worldTransform.d;
    var tx = worldTransform.tx;
    var ty = worldTransform.ty;

    var x1 = a * w1 + c * h1 + tx;
    var y1 = d * h1 + b * w1 + ty;

    var x2 = a * w0 + c * h1 + tx;
    var y2 = d * h1 + b * w0 + ty;

    var x3 = a * w0 + c * h0 + tx;
    var y3 = d * h0 + b * w0 + ty;

    var x4 =  a * w1 + c * h0 + tx;
    var y4 =  d * h0 + b * w1 + ty;

    var maxX = -Infinity;
    var maxY = -Infinity;

    var minX = Infinity;
    var minY = Infinity;

    minX = x1 < minX ? x1 : minX;
    minX = x2 < minX ? x2 : minX;
    minX = x3 < minX ? x3 : minX;
    minX = x4 < minX ? x4 : minX;

    minY = y1 < minY ? y1 : minY;
    minY = y2 < minY ? y2 : minY;
    minY = y3 < minY ? y3 : minY;
    minY = y4 < minY ? y4 : minY;

    maxX = x1 > maxX ? x1 : maxX;
    maxX = x2 > maxX ? x2 : maxX;
    maxX = x3 > maxX ? x3 : maxX;
    maxX = x4 > maxX ? x4 : maxX;

    maxY = y1 > maxY ? y1 : maxY;
    maxY = y2 > maxY ? y2 : maxY;
    maxY = y3 > maxY ? y3 : maxY;
    maxY = y4 > maxY ? y4 : maxY;

    var bounds = this._bounds;

    bounds.x = minX;
    bounds.width = maxX - minX;

    bounds.y = minY;
    bounds.height = maxY - minY;

    // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
    this._currentBounds = bounds;

    return bounds;
};

/**
 * When the texture is updated, this event will fire to update the scale and frame
 *
 * @method onTextureUpdate
 * @param event
 * @private
 */
PIXI.TilingSprite.prototype.onTextureUpdate = function()
{
   // overriding the sprite version of this!
};

/**
*
* @method generateTilingTexture
*
* @param forcePowerOfTwo {Boolean} Whether we want to force the texture to be a power of two
*/
PIXI.TilingSprite.prototype.generateTilingTexture = function(forcePowerOfTwo)
{
    if (!this.texture.baseTexture.hasLoaded) return;

    var texture = this.texture;
    var frame = texture.frame;
    var targetWidth, targetHeight;

    //  Check that the frame is the same size as the base texture.
    var isFrame = frame.width !== texture.baseTexture.width || frame.height !== texture.baseTexture.height;

    var newTextureRequired = false;

    if (!forcePowerOfTwo)
    {
        if (isFrame)
        {
            targetWidth = frame.width;
            targetHeight = frame.height;

            newTextureRequired = true;
        }
    }
    else
    {
        targetWidth = PIXI.getNextPowerOfTwo(frame.width);
        targetHeight = PIXI.getNextPowerOfTwo(frame.height);

        if (frame.width !== targetWidth || frame.height !== targetHeight) newTextureRequired = true;
    }

    if (newTextureRequired)
    {
        var canvasBuffer;

        if (this.tilingTexture && this.tilingTexture.isTiling)
        {
            canvasBuffer = this.tilingTexture.canvasBuffer;
            canvasBuffer.resize(targetWidth, targetHeight);
            this.tilingTexture.baseTexture.width = targetWidth;
            this.tilingTexture.baseTexture.height = targetHeight;
            this.tilingTexture.needsUpdate = true;
        }
        else
        {
            canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight);

            this.tilingTexture = PIXI.Texture.fromCanvas(canvasBuffer.canvas);
            this.tilingTexture.canvasBuffer = canvasBuffer;
            this.tilingTexture.isTiling = true;
        }

        canvasBuffer.context.drawImage(texture.baseTexture.source,
                               texture.crop.x,
                               texture.crop.y,
                               texture.crop.width,
                               texture.crop.height,
                               0,
                               0,
                               targetWidth,
                               targetHeight);

        this.tileScaleOffset.x = frame.width / targetWidth;
        this.tileScaleOffset.y = frame.height / targetHeight;
    }
    else
    {
        //  TODO - switching?
        if (this.tilingTexture && this.tilingTexture.isTiling)
        {
            // destroy the tiling texture!
            // TODO could store this somewhere?
            this.tilingTexture.destroy(true);
        }

        this.tileScaleOffset.x = 1;
        this.tileScaleOffset.y = 1;
        this.tilingTexture = texture;
    }

    this.refreshTexture = false;
    this.tilingTexture.baseTexture._powerOf2 = true;
};
<|endoftext|>


<commit_before>$(document).foundation();

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
}

function lowerCaseKeys(dict) {
    var key, keys = Object.keys(dict);
    var n = keys.length;
    var new_dict={}
    while (n--) {
        key = keys[n];
        new_dict[key.toLowerCase()] = dict[key];
    }
    return new_dict;
}

// convert date format specification from the django/php syntax to the js
// datepicker spec
function django2datepicker(django_format) {
    var translation_dict = {
        'y': 'yy',
        'Y': 'yyyy',
        'n': 'm',
        'm': 'mm',
        'j': 'd',
        'd': 'dd',
        'h': 'hh',
        'H': 'hh',
        'G': 'h',
        'g': 'h',
        'i': 'ii',
        'a': 'aa',
        'A': 'AA',
        'P': 'hh:ii aa'
    }

    var datepicker_format = '';
    for (var i = 0, len = django_format.length; i < len; i++) {
        if (django_format[i] in translation_dict) {
            datepicker_format += translation_dict[django_format[i]];
        }
        else {
            datepicker_format += django_format[i];
        }
    }

    return datepicker_format;
}

function inlineWidget(css_class, template, dict, list_separator) {
    $('.inline-widget.' + css_class).html(function(i, content) {
        var has_link = false;
        var text = $(content).text();
        var result = "";
        if ($(content).attr('href')) {
            text = $(content).children(':first').text();
            has_link = true;
        }

        var text_list = [text];
        if (list_separator) {
            text_list = text.split(list_separator);
        }

        for (i = 0; i < text_list.length; i++)
        {
            var item = text_list[i];
            if (list_separator) {
                item += list_separator;
            }

            if (!dict) {
                item = template.replaceAll('{{ key }}', text_list[i]);
            }
            else {
                var lower_dict = lowerCaseKeys(dict);
                var lower_text_item = text_list[i].toLowerCase();

                if (lower_text_item in lower_dict) {
                    item = template.replaceAll('{{ value }}', lower_dict[lower_text_item]);
                    item = item.replaceAll('{{ key }}', text_list[i]);
                }
            }
            result += item;
        }

        if (has_link) {
            result = $(content).empty().append(result);
        }

        return result;
    });
}

function set_input_widgets() {
    var s = $('.js-selectize');
    if ( s.size() ) {
        s.selectize(
            {
                allowEmptyOption: true,
                highlight: false,
                plugins: ['remove_button']
            }
        );
    }

    var s_tags = $('.js-selectize-tags');
    if (s_tags.size()) {
        s_tags.selectize({
            delimiter: ',',
            persist: false,
            plugins: ['remove_button'],
            create: function(input) {
                return {
                    value: input,
                    text: input
                }
            }
        });
    }

    s.on( 'initialize', initializethis );
    s_tags.on( 'initialize', initializethis );

    var initializethis = function() { alert('js-selectize is initialized') };

    $('.js-datepicker').each(function(index) {
        $(this).datepicker({
            todayButton: true,
            language: 'en',
            startDate: new Date($(this).attr("date")),
        	dateFormat: django2datepicker(DATE_FORMAT)
        });
    });

    $('.js-timepicker').each(function(index) {
        $(this).datepicker({
            onlyTimepicker: true,
            language: 'en',
            startDate: new Date($(this).attr("date")),
        	timeFormat: django2datepicker(TIME_FORMAT),
            timepicker: true
        });
    });

    $('.js-datetimepicker').each(function(index) {
        $(this).datepicker({
            language: 'en',
            todayButton: true,
            startDate: new Date($(this).attr("date")),
        	dateFormat: django2datepicker(DATE_FORMAT),
            timeFormat: django2datepicker(TIME_FORMAT),
            timepicker: true
        });
    });
}

// jquery stuff goes here
$(document).ready(function() {

    // Toggle menu hamburger to cross
    $('#menu-button').click(function (e) {
        $('#menu-button').toggleClass('is-active');
        // e.preventDefault();
    });

    // Toggle back menu button into hamburger when clicking overlay
    $('.js-off-canvas-exit').click(function(e) {
        $('#menu-button').removeClass('is-active');
        // e.preventDefault();
    });

    // Stepper input
    var $stepperInput = $('.stepper-input input');

    function incrementStepperInput(amount) {
        $stepperInput.val((parseInt($stepperInput.val()) || 0) + amount);
    }

    var stepperInputDecrement = $('.stepper-input button')[0];
    $(stepperInputDecrement).click(function() {
        incrementStepperInput(-1);
    });

    var stepperInputIncrement = $('.stepper-input button')[1];
    $(stepperInputIncrement).click(function() {
        incrementStepperInput(1);
    });

    var dirty_check = $('form.dirty-check');
    if (dirty_check.size()) {
        dirty_check.areYouSure();

        $('form').on('dirty.areYouSure', function() {
            var tab = $('.tabs-title.is-active a')[0];
            if (tab) {
                tab.text = '● ' + tab.text;
            }
            document.title = '● ' + document.title;
        });

        $('form').on('clean.areYouSure', function() {
            var tab = $('.tabs-title.is-active a')[0];
            if (tab) {
                tab.text = tab.text.slice(2);
            }
            document.title = document.title.slice(2);
        });
    }

    set_input_widgets();
});<commit_msg>not areyousure within iframe<commit_after>$(document).foundation();

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
}

function lowerCaseKeys(dict) {
    var key, keys = Object.keys(dict);
    var n = keys.length;
    var new_dict={}
    while (n--) {
        key = keys[n];
        new_dict[key.toLowerCase()] = dict[key];
    }
    return new_dict;
}

// convert date format specification from the django/php syntax to the js
// datepicker spec
function django2datepicker(django_format) {
    var translation_dict = {
        'y': 'yy',
        'Y': 'yyyy',
        'n': 'm',
        'm': 'mm',
        'j': 'd',
        'd': 'dd',
        'h': 'hh',
        'H': 'hh',
        'G': 'h',
        'g': 'h',
        'i': 'ii',
        'a': 'aa',
        'A': 'AA',
        'P': 'hh:ii aa'
    }

    var datepicker_format = '';
    for (var i = 0, len = django_format.length; i < len; i++) {
        if (django_format[i] in translation_dict) {
            datepicker_format += translation_dict[django_format[i]];
        }
        else {
            datepicker_format += django_format[i];
        }
    }

    return datepicker_format;
}

function inlineWidget(css_class, template, dict, list_separator) {
    $('.inline-widget.' + css_class).html(function(i, content) {
        var has_link = false;
        var text = $(content).text();
        var result = "";
        if ($(content).attr('href')) {
            text = $(content).children(':first').text();
            has_link = true;
        }

        var text_list = [text];
        if (list_separator) {
            text_list = text.split(list_separator);
        }

        for (i = 0; i < text_list.length; i++)
        {
            var item = text_list[i];
            if (list_separator) {
                item += list_separator;
            }

            if (!dict) {
                item = template.replaceAll('{{ key }}', text_list[i]);
            }
            else {
                var lower_dict = lowerCaseKeys(dict);
                var lower_text_item = text_list[i].toLowerCase();

                if (lower_text_item in lower_dict) {
                    item = template.replaceAll('{{ value }}', lower_dict[lower_text_item]);
                    item = item.replaceAll('{{ key }}', text_list[i]);
                }
            }
            result += item;
        }

        if (has_link) {
            result = $(content).empty().append(result);
        }

        return result;
    });
}

function set_input_widgets() {
    var s = $('.js-selectize');
    if ( s.size() ) {
        s.selectize(
            {
                allowEmptyOption: true,
                highlight: false,
                plugins: ['remove_button']
            }
        );
    }

    var s_tags = $('.js-selectize-tags');
    if (s_tags.size()) {
        s_tags.selectize({
            delimiter: ',',
            persist: false,
            plugins: ['remove_button'],
            create: function(input) {
                return {
                    value: input,
                    text: input
                }
            }
        });
    }

    s.on( 'initialize', initializethis );
    s_tags.on( 'initialize', initializethis );

    var initializethis = function() { alert('js-selectize is initialized') };

    $('.js-datepicker').each(function(index) {
        $(this).datepicker({
            todayButton: true,
            language: 'en',
            startDate: new Date($(this).attr("date")),
        	dateFormat: django2datepicker(DATE_FORMAT)
        });
    });

    $('.js-timepicker').each(function(index) {
        $(this).datepicker({
            onlyTimepicker: true,
            language: 'en',
            startDate: new Date($(this).attr("date")),
        	timeFormat: django2datepicker(TIME_FORMAT),
            timepicker: true
        });
    });

    $('.js-datetimepicker').each(function(index) {
        $(this).datepicker({
            language: 'en',
            todayButton: true,
            startDate: new Date($(this).attr("date")),
        	dateFormat: django2datepicker(DATE_FORMAT),
            timeFormat: django2datepicker(TIME_FORMAT),
            timepicker: true
        });
    });
}

// jquery stuff goes here
$(document).ready(function() {

    // Toggle menu hamburger to cross
    $('#menu-button').click(function (e) {
        $('#menu-button').toggleClass('is-active');
        // e.preventDefault();
    });

    // Toggle back menu button into hamburger when clicking overlay
    $('.js-off-canvas-exit').click(function(e) {
        $('#menu-button').removeClass('is-active');
        // e.preventDefault();
    });

    // Stepper input
    var $stepperInput = $('.stepper-input input');

    function incrementStepperInput(amount) {
        $stepperInput.val((parseInt($stepperInput.val()) || 0) + amount);
    }

    var stepperInputDecrement = $('.stepper-input button')[0];
    $(stepperInputDecrement).click(function() {
        incrementStepperInput(-1);
    });

    var stepperInputIncrement = $('.stepper-input button')[1];
    $(stepperInputIncrement).click(function() {
        incrementStepperInput(1);
    });

    var dirty_check = $('form.dirty-check');
    if (dirty_check.size() && !window.parent != window ) {
        dirty_check.areYouSure();

        $('form').on('dirty.areYouSure', function() {
            var tab = $('.tabs-title.is-active a')[0];
            if (tab) {
                tab.text = '● ' + tab.text;
            }
            document.title = '● ' + document.title;
        });

        $('form').on('clean.areYouSure', function() {
            var tab = $('.tabs-title.is-active a')[0];
            if (tab) {
                tab.text = tab.text.slice(2);
            }
            document.title = document.title.slice(2);
        });
    }

    set_input_widgets();
});<|endoftext|>


<commit_before>import React from 'react';
import Select from 'react-select';
import ReactDOM from 'react-dom';
import AutoComplete from 'material-ui/AutoComplete';

class SearchForActivity extends React.Component {

	handleUpdateInput = value => {

		this.props.onFilterChange(value);
	};

	render () {
		return (

				<AutoComplete
					searchText={this.props.searchForFilter}
					hintText={this.props.placeholderText}
					dataSource={this.props.activitiesName}
					filter={AutoComplete.fuzzyFilter}
					maxSearchResults={10}
					onUpdateInput={this.handleUpdateInput}
					fullWidth={true}
				/>

		);
	}
}

SearchForActivity.propTypes = {
	onFilterChange: React.PropTypes.func.isRequired,
	placeholderText: React.PropTypes.string,
	activitiesName: React.PropTypes.array.isRequired,
	searchForFilter: React.PropTypes.string.isRequired,

};

export default SearchForActivity;

<commit_msg>added floating input with placeholder text for search input field<commit_after>import React from 'react';
import Select from 'react-select';
import ReactDOM from 'react-dom';
import AutoComplete from 'material-ui/AutoComplete';
import SearchIcon from 'material-ui/svg-icons/action/search';

class SearchForActivity extends React.Component {

	handleUpdateInput = value => {
		this.props.onFilterChange(value);
	};

	render () {
		return (

				<AutoComplete
					floatingLabelText={
<SearchIcon/> Søk etter en aktivitet...
}
					searchText={this.props.searchForFilter}
					hintText={this.props.placeholderText}
					dataSource={this.props.activitiesName}
					filter={AutoComplete.fuzzyFilter}
					maxSearchResults={10}
					onUpdateInput={this.handleUpdateInput}
					fullWidth={true}
				/>

		);
	}
}

SearchForActivity.propTypes = {
	onFilterChange: React.PropTypes.func.isRequired,
	placeholderText: React.PropTypes.string,
	activitiesName: React.PropTypes.array.isRequired,
	searchForFilter: React.PropTypes.string.isRequired,

};

export default SearchForActivity;

<|endoftext|>


<commit_before>let addClass = require('./classes').addClass;
let hasClass = require('./classes').hasClass;
let removeClass = require('./classes').removeClass;

// Main variables
let
    _form         = document.querySelector('form.feedback-contact'),
    _submitButton = _form.querySelector('.submit-feedback'),
    _name         = _form.querySelector('input[type="text"]'),
    _email        = _form.querySelector('input[type="email"]');

// validate form function
// ================
let validateForm = (e, filter, inputField, invalidText, validClass, invalidClass) => {
  let testing = filter.test(inputField.value);  // returning boolean value from testing
  let _para = document.createElement('p');      // creating paragraph
      _para.textContent = invalidText;          // and adding text content for invalid input value

  if (inputField.value.length) {                // if input not empty
    if (!testing) {                             // and if it DIDN'T pass test
      e.preventDefault();                       // prevent form from submission
      if (hasClass(inputField, validClass)) {   // if it has 'valid-input-value' class
        removeClass(inputField, validClass);    // remove it (green border)
      }

      if (!hasClass(inputField, invalidClass)) {                           // if it doesn't have 'invalid-input-value' class
        addClass(inputField, invalidClass);                                // add it (red border)
        inputField.parentNode.insertBefore(_para, inputField.nextSibling); // and add notify message
      }

    } else {                                                                       // if it DID pass test

      if (inputField.parentNode.children.length === 3) {                           // and if it already have notify message
        inputField.parentNode.removeChild(inputField.parentNode.lastElementChild); // remove message
        removeClass(inputField, 'invalid-input-value');                            // and remove 'invalid-input-value' class
      }

      addClass(inputField, validClass);                                            // and add 'valid-input-value' class (green border)

    }

  }

};

// name validation function
let validateName = () => {
  let validateNameFilter = /^[a-zA-Z а-яА-Я ]{4,30}$/;
  validateForm(event, validateNameFilter, _name, 'Invalid name', 'valid-input-value', 'invalid-input-value');
};

// email validation function
let validateEmail = () => {
  let validateEmailFilter = /^(([^<>+()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  validateForm(event, validateEmailFilter, _email, 'Invalid email', 'valid-input-value', 'invalid-input-value');
};

_submitButton.addEventListener('click', validateName, false);  // adding event on 'name' input submit
_submitButton.addEventListener('click', validateEmail, false); // adding event on 'email' input submit
<commit_msg>use in validation form new addEvent function<commit_after>// imports
const addClass = require('./classes').addClass;
const hasClass = require('./classes').hasClass;
const removeClass = require('./classes').removeClass;
const addEvent = require('./events').addEvent;

// Main variables
const
    _form         = document.querySelector('form.feedback-contact'),
    _submitButton = _form.querySelector('.submit-feedback'),
    _name         = _form.querySelector('input[type="text"]'),
    _email        = _form.querySelector('input[type="email"]');

// validate form function
// ================
const validateForm = (e, filter, inputField, invalidText, validClass, invalidClass) => {
  const testing = filter.test(inputField.value);  // returning boolean value from testing
  const _para = document.createElement('p');      // creating paragraph
      _para.textContent = invalidText;          // and adding text content for invalid input value

  if (inputField.value.length) {                // if input not empty
    if (!testing) {                             // and if it DIDN'T pass test
      e.preventDefault();                       // prevent form from submission
      if (hasClass(inputField, validClass)) {   // if it has 'valid-input-value' class
        removeClass(inputField, validClass);    // remove it (green border)
      }
      if (!hasClass(inputField, invalidClass)) {                           // if it doesn't have 'invalid-input-value' class
        addClass(inputField, invalidClass);                                // add it (red border)
        inputField.parentNode.insertBefore(_para, inputField.nextSibling); // and add notify message
      }
    } else {                                                                       // if it DID pass test
      if (inputField.parentNode.children.length === 3) {                           // and if it already have notify message
        inputField.parentNode.removeChild(inputField.parentNode.lastElementChild); // remove message
        removeClass(inputField, 'invalid-input-value');                            // and remove 'invalid-input-value' class
      }
      addClass(inputField, validClass);                                            // and add 'valid-input-value' class (green border)
    }
  }
};

// name validation function
const validateName = () => {
  const validateNameFilter = /^[a-zA-Z а-яА-Я ]{4,30}$/;
  validateForm(event, validateNameFilter, _name, 'Invalid name', 'valid-input-value', 'invalid-input-value');
};

// email validation function
const validateEmail = () => {
  const validateEmailFilter = /^(([^<>+()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  validateForm(event, validateEmailFilter, _email, 'Invalid email', 'valid-input-value', 'invalid-input-value');
};

addEvent(_submitButton, 'click', validateName);  // adding event on 'name' input submit
addEvent(_submitButton, 'click', validateEmail); // adding event on 'email' input submit
<|endoftext|>


<commit_before>;(function($) {

    var pluginName = 'uxSwitcher';

    $.uxSwitcher = function(element, options) {

        var defaults = {
                classes : {
                opened : 'is-opened',
                closed : 'is-closed',
                popups : null
            },
            onOpened : function() {},
            onClosed : function() {}
        };

        var plugin = this;

        plugin.settings = {}
        plugin.elem = $(element);

        var $element = $(element);

        plugin.init = function() {
            plugin.settings = $.extend({}, defaults, options);
            plugin.bindEvents();
        };

        plugin.bindEvents = function() {

            $element.on('click' + '.' + pluginName, function(event) {

                event.preventDefault();
                event.stopPropagation();

                if ($element.hasClass(plugin.settings.classes.opened)) {
                    plugin.close(this);
                } else {
                    plugin.open(this);
                }
            });

            $(document).on('click' + '.' + pluginName, plugin.close);

            $(document).on('keydown' + '.' + pluginName, function(event) {
                if (event.keyCode == 27) {
                    plugin.close();
                }
            });
        };

        plugin.unBindEvents = function() {
            $element.off('.' + pluginName);
            $(document).off('.' + pluginName);
        };

        plugin.open = function(element) {
            $element
                .removeClass(plugin.settings.classes.closed)
                .addClass(plugin.settings.classes.opened);

            plugin.settings.onOpened.call(plugin.elem);
        };

        plugin.close = function(element) {
            $element
                .addClass(plugin.settings.classes.closed)
                .removeClass(plugin.settings.classes.opened);

            plugin.settings.onClosed.call(plugin.elem);
        };

        plugin.destroy = function() {
            plugin.unBindEvents();
            //$element.removeData(pluginName);
        }

        plugin.init();

    }

     // add the plugin to the jQuery.fn object
     $.fn.uxSwitcher = function(options) {

        return this.each(function() {

            if (undefined == $(this).data(pluginName)) {
                var plugin = new $.uxSwitcher(this, options);
                $(this).data(pluginName, plugin);
            }

        });

    }

})(jQuery);
<commit_msg>Добавление классов состояния инициализации и уничтожения плагина<commit_after>;(function($) {

    var pluginName = 'uxSwitcher';

    $.uxSwitcher = function(element, options) {

        var defaults = {
                classes : {
                opened : 'is-opened',
                closed : 'is-closed',
                popups : null
            },
            onOpened : function() {},
            onClosed : function() {}
        };

        var plugin = this;

        plugin.settings = {}
        plugin.elem = $(element);

        var $element = $(element);

        plugin.init = function() {
            plugin.settings = $.extend({}, defaults, options);
            plugin.bindEvents();

            $element.addClass('js-uxSwitcher js-uxSwitcher--enabled');
        };

        plugin.bindEvents = function() {

            $element.on('click' + '.' + pluginName, function(event) {

                event.preventDefault();
                event.stopPropagation();

                if ($element.hasClass(plugin.settings.classes.opened)) {
                    plugin.close(this);
                } else {
                    plugin.open(this);
                }
            });

            $(document).on('click' + '.' + pluginName, plugin.close);

            $(document).on('keydown' + '.' + pluginName, function(event) {
                if (event.keyCode == 27) {
                    plugin.close();
                }
            });
        };

        plugin.unBindEvents = function() {
            $element.off('.' + pluginName);
            $(document).off('.' + pluginName);
        };

        plugin.open = function(element) {
            $element
                .removeClass(plugin.settings.classes.closed)
                .addClass(plugin.settings.classes.opened);

            plugin.settings.onOpened.call(plugin.elem);
        };

        plugin.close = function(element) {
            $element
                .addClass(plugin.settings.classes.closed)
                .removeClass(plugin.settings.classes.opened);

            plugin.settings.onClosed.call(plugin.elem);
        };

        plugin.destroy = function() {

            plugin.unBindEvents();

            $element
                .removeClass('js-uxSwitcher--enabled')
                .addClass('js-uxSwitcher--destroyed');
            //$element.removeData(pluginName);
        }

        plugin.init();

    }

     // add the plugin to the jQuery.fn object
     $.fn.uxSwitcher = function(options) {

        return this.each(function() {

            if (undefined == $(this).data(pluginName)) {
                var plugin = new $.uxSwitcher(this, options);
                $(this).data(pluginName, plugin);
            }

        });

    }

})(jQuery);
<|endoftext|>


<commit_before>$A.bind(window, 'load', function(){

	// Modal AccDC Object

	var modalId = $A.setModal(
					{
					// Set a role for screen reader users
					role: 'Login',
					// Set a triggering element
					trigger: 'button.lightbox',
					source: 'files/overlays.html #lightbox1',
					// Run configuration script after the AccDC Object finishes loading
					runAfter: function(dc){

						// Configure form functionality

						$A.bind('#lbForm', 'submit', function(ev){
							if (!this.uname.value){
								alert('Woops! You forgot your username...');
								this.uname.focus();
							}

							else if (!this.pass.value){
								alert('Woops! You forgot your password...');
								this.pass.focus();
							}

							else{
								alert('WOW!');
								dc.close();
							}
							ev.preventDefault();
						});

						// Add a background div for the filtered opasity
						dc.backdrop = $A.createEl('div', null, null, 'modalBackdrop', document.createTextNode(' '));
						dc.accDCObj.parentNode.insertBefore(dc.backdrop, dc.accDCObj);
					},
					runAfterClose: function(dc){
						if (dc.backdrop)
							dc.backdrop.parentNode.removeChild(dc.backdrop);
					}
					});

	// Set a banner to be loaded, and save a public reference to the ID

	window.bannerId = $A.setBanner(
					{

					// Specify the path and ID of the banner content to be loaded
					source: 'files/overlays.html #ad-1',

					// Disable automatic positioning
					autoFix: 0,

					// Specify that the banner should open as soon as the page loads
					autoStart: true,

					// Set a class name for the banner top level container element
					className: 'banner',

// Specify that the textual content of the banner should automatically be announced to screen reader users when opened
					announce: true,

					// Choose the container element where the banner will be inserted
					isStatic: 'body',
					// Choose to prepend the banner instead of replacing the content within the container element
					prepend: true,

					// Set a hidden close link to appear for screen reader users
					showHiddenClose: true,
					// Remove the hidden close link from the tab order so it doesn't appear when tabbing
					displayHiddenClose: false,

					// Run a script after the banner finishes loading
					runAfter: function(dc){

						// Set a submit handler on the form within the banner
						$A.bind('div.banner form', 'submit', function(ev){

							// Prevent the page from refreshing
							ev.preventDefault();

							// Get a reference to the email edit field, and check for an entry
							var email = $A.getEl('email').value;

							if (email)
								alert('Do something with ' + email);

							// Get a reference to the Banner AccDC Object using its ID
							var dc = $A.reg[bannerId];
							// Then close the banner
							dc.close();
						});
					}

					// Other AccDC API properties and methods can go here as well.

					});

	// Tooltip AccDC Object
	var tooltipId = $A.setTooltip(
					{
					trigger: 'a.helpIcon',
					source: 'files/overlays.html #tooltip1'
					});

	// Popup AccDC Object
	var popupId = $A.setPopup(
					{
					role: 'Excerpt',
					trigger: 'a.excerpt',
					source: 'files/overlays.html #popup1',
					// Move the AccDC Object 10px to the right, and 20px up when opened
					offsetLeft: 10,
					offsetTop: -20
					});
});<commit_msg>Updated the Modal setup files to show how auto announcement can be enabled or disabled for screen reader users when the modal is first rendered via the 'announce' property.<commit_after>$A.bind(window, 'load', function(){

	// Modal AccDC Object

	var modalId = $A.setModal(
					{
					// Set a role for screen reader users
					role: 'Login',
					// Set a triggering element
					trigger: 'button.lightbox',
					source: 'files/overlays.html #lightbox1',
					// Run configuration script after the AccDC Object finishes loading
					runAfter: function(dc){

						// Configure form functionality

						$A.bind('#lbForm', 'submit', function(ev){
							if (!this.uname.value){
								alert('Woops! You forgot your username...');
								this.uname.focus();
							}

							else if (!this.pass.value){
								alert('Woops! You forgot your password...');
								this.pass.focus();
							}

							else{
								alert('WOW!');
								dc.close();
							}
							ev.preventDefault();
						});

						// Add a background div for the filtered opasity
						dc.backdrop = $A.createEl('div', null, null, 'modalBackdrop', document.createTextNode(' '));
						dc.accDCObj.parentNode.insertBefore(dc.backdrop, dc.accDCObj);
					},
					runAfterClose: function(dc){
						if (dc.backdrop)
							dc.backdrop.parentNode.removeChild(dc.backdrop);
					},

					// Announce the dialog content for screen reader users when first rendered
					announce: true
					});

	// Set a banner to be loaded, and save a public reference to the ID

	window.bannerId = $A.setBanner(
					{

					// Specify the path and ID of the banner content to be loaded
					source: 'files/overlays.html #ad-1',

					// Disable automatic positioning
					autoFix: 0,

					// Specify that the banner should open as soon as the page loads
					autoStart: true,

					// Set a class name for the banner top level container element
					className: 'banner',

// Specify that the textual content of the banner should automatically be announced to screen reader users when opened
					announce: true,

					// Choose the container element where the banner will be inserted
					isStatic: 'body',
					// Choose to prepend the banner instead of replacing the content within the container element
					prepend: true,

					// Set a hidden close link to appear for screen reader users
					showHiddenClose: true,
					// Remove the hidden close link from the tab order so it doesn't appear when tabbing
					displayHiddenClose: false,

					// Run a script after the banner finishes loading
					runAfter: function(dc){

						// Set a submit handler on the form within the banner
						$A.bind('div.banner form', 'submit', function(ev){

							// Prevent the page from refreshing
							ev.preventDefault();

							// Get a reference to the email edit field, and check for an entry
							var email = $A.getEl('email').value;

							if (email)
								alert('Do something with ' + email);

							// Get a reference to the Banner AccDC Object using its ID
							var dc = $A.reg[bannerId];
							// Then close the banner
							dc.close();
						});
					}

					// Other AccDC API properties and methods can go here as well.

					});

	// Tooltip AccDC Object
	var tooltipId = $A.setTooltip(
					{
					trigger: 'a.helpIcon',
					source: 'files/overlays.html #tooltip1'
					});

	// Popup AccDC Object
	var popupId = $A.setPopup(
					{
					role: 'Excerpt',
					trigger: 'a.excerpt',
					source: 'files/overlays.html #popup1',
					// Move the AccDC Object 10px to the right, and 20px up when opened
					offsetLeft: 10,
					offsetTop: -20
					});
});<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */
var surveysPolicy = require('../policies/surveys.server.policy'),
	surveys = require('../controllers/surveys.server.controller');

module.exports = function (app) {
	// Groups collection routes
	app.route('/api/surveys')
		.all(surveysPolicy.isAllowed)
		.get(surveys.list);

	// Single survey routes
	app.route('/api/surveys/:surveyId')
		.all(surveysPolicy.isAllowed)
		.get(surveys.read)
		.post(surveys.submit);

	// Finish by binding the survey middleware
	app.param('surveyId', surveys.surveyByID);
};<commit_msg>Fix docs in surveys module<commit_after>'use strict';

/**
 * Module dependencies
 */
var surveysPolicy = require('../policies/surveys.server.policy'),
	surveys = require('../controllers/surveys.server.controller');

module.exports = function (app) {
	// Surveys collection routes
	app.route('/api/surveys')
		.all(surveysPolicy.isAllowed)
		.get(surveys.list);

	// Single survey routes
	app.route('/api/surveys/:surveyId')
		.all(surveysPolicy.isAllowed)
		.get(surveys.read)
		.post(surveys.submit);

	// Finish by binding the survey middleware
	app.param('surveyId', surveys.surveyByID);
};
<|endoftext|>