<commit_before>/*
 * Copyright (c) 2011-2013 by Animatron.
 * All rights are reserved.
 *
 * Animatron Player is licensed under the MIT License, see LICENSE.
 *
 * @VERSION
 */

(function() { // anonymous wrapper to exclude global context clash
  var C = anm.C;
  var _ResMan = __anm.resource_manager;

  C.MOD_AUDIO = 'audio';
  if (anm.M[C.MOD_AUDIO]) throw new Error('AUDIO module already enabled');

  anm.M[C.MOD_AUDIO] = {};

  var E = anm.Element;

  // Element functions
  // ----------------------------------------------------------------------------------------------------------------

  var _audio_customRender = function(gtime, ltime, ctx) {
    // TODO: remove
    return false;
  };

  var _onAudioStart = function(ltime, duration) {
    if (!this._audio_is_loaded || this._audio_is_playing) {
      return false;
    }

    this._audio_is_playing = true;
    this._audio.currentTime = this._audio_band_offset + ltime;
    this._audio.volume = 1;
    this._audio.play();
  };

  var _onAudioStop = function(ltime, duration) {
    if (this._audio_is_playing) {
      this._audio.pause();
      this._audio_is_playing = false;
      this._audio.volume = 0;
    }
  };

  E.prototype.importCustomData = function(object, type, importer) {
    if ((14 == type)/*ANM*/ ||
        ("0e" == type)/*ANM_INTACT*/) {
      if (importer == "ANM") {
        /** audio **/
        /*
         * array {
         *     14;                         // 0
         *     string;                     // 1, url
         *     number;                     // 2, band offset
         * } *audio_element*;
         */
        this._audio_url = this._audio_format_url(object[1]);
        this._audio_band_offset = object[2];
      } else if (importer == "ANM_INTACT") {
        this._audio_band_offset = object.bandOffset;
        this._audio_url = this._audio_format_url(object.url);
      }

      this.isAudio = true;
      this._audio = null;
      this._audio_is_loaded = false;
      this._audio_is_playing = false;
      this._audio_canPlay = false;

      this.on(C.X_START, _onAudioStart);
      this.on(C.X_STOP, _onAudioStop);
      this.on(C.S_STOP, _onAudioStop);
      this.on(C.S_PAUSE, _onAudioStop);

      // assign custom render function
      this.__frameProcessors.push(_audio_customRender);

      this._audio_load();
    }
  };

  E.prototype._audio_format_url = function(url) {
    return url + (this._mpeg_supported() ? ".mp3" : ".ogg");
  };

  E.__test_elm = null;
  E.prototype._mpeg_supported = function() {
    var a = E.__test_elm ? E.__test_elm : (E.__test_elm = document.createElement('audio'), E.__test_elm);
    return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
  }

  var prev__hasRemoteResources = E.prototype._hasRemoteResources;
  E.prototype._hasRemoteResources = function() {
    return prev__hasRemoteResources.call(this, arguments) || this.isAudio;
  }

  var prev__getRemoteResources = E.prototype._getRemoteResources;
  E.prototype._getRemoteResources = function() {
    var prev = prev__getRemoteResources.call(this, arguments);
    if (!this.isAudio && !prev) return null;
    if (!this.isAudio) return prev;
        // return [ this._audio_url ].concat(prev || [])
    return prev ? [ this._audio_url ].concat(prev) : [ this._audio_url ];
  }

  function audioErrProxy(src, pass_to) {
    return function(err) {
      // e_.MEDIA_ERR_ABORTED=1
      // e_.MEDIA_ERR_NETWORK=2
      // e_.MEDIA_ERR_DECODE=3
      // e_.MEDIA_ERR_SRC_NOT_SUPPORTED=4
      // e_.MEDIA_ERR_ENCRYPTED=5
      pass_to(new Error('Failed to load audio file from ' + src + ' with error code: ' +
                        err.currentTarget.error.code));
    }
  };
  E.prototype._audio_load = function() {
    var me = this;

    _ResMan.loadOrGet(me._audio_url,
      function(notify_success, notify_error) { // loader
          var el = document.createElement("audio");
          el.setAttribute("preload", "auto");

          var progressListener = function(e) {
            var buffered = el.buffered;
            if (buffered.length == 1) {
                var end = buffered.end(0);
                if (el.duration - end < 0.05) {
                  el.removeEventListener("progress", progressListener, false);
                  el.removeEventListener("canplay", canPlayListener, false);
                  notify_success(el);
                  return;
                }

                if (me._audio_canPlay && window.chrome) {
                  el.volume = 0;
                  el.currentTime = end;
                  el.play();
                  el.pause();
                }
            }
          };

          var canPlayListener = function(e) {
            me._audio_canPlay = true;
            progressListener(e);
          };

          el.addEventListener("progress", progressListener, false);
          el.addEventListener("canplay", canPlayListener, false);
          el.addEventListener("error", audioErrProxy(me._audio_url, notify_error), false);

          try {
            document.getElementsByTagName("body")[0].appendChild(el);
            el.src = me._audio_url;
          } catch(e) { notify_error(e); }
      },
      function(audio) { // oncomplete
          me._audio = audio;
          me._audio_is_loaded = true;
      },
      function(err) { __anm.console.error(err.message || err);
                      /* throw err; */ }); // onerror
  };

})();<commit_msg>fix windows firefox audio<commit_after>/*
 * Copyright (c) 2011-2013 by Animatron.
 * All rights are reserved.
 *
 * Animatron Player is licensed under the MIT License, see LICENSE.
 *
 * @VERSION
 */

(function() { // anonymous wrapper to exclude global context clash
  var C = anm.C;
  var _ResMan = __anm.resource_manager;

  C.MOD_AUDIO = 'audio';
  if (anm.M[C.MOD_AUDIO]) throw new Error('AUDIO module already enabled');

  anm.M[C.MOD_AUDIO] = {};

  var E = anm.Element;

  // Element functions
  // ----------------------------------------------------------------------------------------------------------------

  var _audio_customRender = function(gtime, ltime, ctx) {
    // TODO: remove
    return false;
  };

  var _onAudioStart = function(ltime, duration) {
    if (!this._audio_is_loaded || this._audio_is_playing) {
      return false;
    }

    this._audio_is_playing = true;
    this._audio.currentTime = this._audio_band_offset + ltime;
    this._audio.volume = 1;
    this._audio.play();
  };

  var _onAudioStop = function(ltime, duration) {
    if (this._audio_is_playing) {
      this._audio.pause();
      this._audio_is_playing = false;
      this._audio.volume = 0;
    }
  };

  E.prototype.importCustomData = function(object, type, importer) {
    if ((14 == type)/*ANM*/ ||
        ("0e" == type)/*ANM_INTACT*/) {
      if (importer == "ANM") {
        /** audio **/
        /*
         * array {
         *     14;                         // 0
         *     string;                     // 1, url
         *     number;                     // 2, band offset
         * } *audio_element*;
         */
        this._audio_url = object[1];
        this._audio_band_offset = object[2];
      } else if (importer == "ANM_INTACT") {
        this._audio_band_offset = object.bandOffset;
        this._audio_url = this._audio_format_url(object.url);
      }

      this.isAudio = true;
      this._audio = null;
      this._audio_is_loaded = false;
      this._audio_is_playing = false;
      this._audio_canPlay = false;

      this.on(C.X_START, _onAudioStart);
      this.on(C.X_STOP, _onAudioStop);
      this.on(C.S_STOP, _onAudioStop);
      this.on(C.S_PAUSE, _onAudioStop);

      // assign custom render function
      this.__frameProcessors.push(_audio_customRender);

      this._audio_load();
    }
  };

  E.prototype._audio_format_url = function(url) {
    return url + (this._mpeg_supported() ? ".mp3" : ".ogg");
  };

  E.__test_elm = null;
  E.prototype._mpeg_supported = function() {
    var a = E.__test_elm ? E.__test_elm : (E.__test_elm = document.createElement('audio'), E.__test_elm);
    return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
  }

  var prev__hasRemoteResources = E.prototype._hasRemoteResources;
  E.prototype._hasRemoteResources = function() {
    return prev__hasRemoteResources.call(this, arguments) || this.isAudio;
  }

  var prev__getRemoteResources = E.prototype._getRemoteResources;
  E.prototype._getRemoteResources = function() {
    var prev = prev__getRemoteResources.call(this, arguments);
    if (!this.isAudio && !prev) return null;
    if (!this.isAudio) return prev;
        // return [ this._audio_url ].concat(prev || [])
    return prev ? [ this._audio_url ].concat(prev) : [ this._audio_url ];
  }

  function audioErrProxy(src, pass_to) {
    return function(err) {
      // e_.MEDIA_ERR_ABORTED=1
      // e_.MEDIA_ERR_NETWORK=2
      // e_.MEDIA_ERR_DECODE=3
      // e_.MEDIA_ERR_SRC_NOT_SUPPORTED=4
      // e_.MEDIA_ERR_ENCRYPTED=5
      pass_to(new Error('Failed to load audio file from ' + src + ' with error code: ' +
                        err.currentTarget.error.code));
    }
  };
  E.prototype._audio_load = function() {
    var me = this;

    _ResMan.loadOrGet(me._audio_url,
      function(notify_success, notify_error) { // loader
          var el = document.createElement("audio");
          el.setAttribute("preload", "auto");

          var progressListener = function(e) {
            var buffered = el.buffered;
            if (buffered.length == 1) {
                var end = buffered.end(0);
                if (el.duration - end < 0.05) {
                  el.removeEventListener("progress", progressListener, false);
                  el.removeEventListener("canplay", canPlayListener, false);
                  notify_success(el);
                  return;
                }

                if (me._audio_canPlay && window.chrome) {
                  el.volume = 0;
                  el.currentTime = end;
                  el.play();
                  el.pause();
                }
            }
          };

          var canPlayListener = function(e) {
            me._audio_canPlay = true;
            progressListener(e);
          };

          el.addEventListener("progress", progressListener, false);
          el.addEventListener("canplay", canPlayListener, false);
          el.addEventListener("error", audioErrProxy(me._audio_url, notify_error), false);

          var addSource = function(audio, url, type) {
              var src = document.createElement("source");
              src.type = type;
              src.src = url;
              audio.appendChild(src);
          };

          try {
            document.getElementsByTagName("body")[0].appendChild(el);
            addSource(el, me._audio_url + ".mp3", "audio/mpeg");
            addSource(el, me._audio_url + ".ogg", "audio/ogg");
          } catch(e) { notify_error(e); }
      },
      function(audio) { // oncomplete
          me._audio = audio;
          me._audio_is_loaded = true;
      },
      function(err) { __anm.console.error(err.message || err);
                      /* throw err; */ }); // onerror
  };

})();<|endoftext|>


<commit_before>var Jasmine = require('jasmine');
var SpecReporter = require('jasmine-spec-reporter');
var noop = function() {};

var jrunner = new Jasmine();
jrunner.configureDefaultReporter({print: noop});    // remove default reporter logs
jasmine.getEnv().addReporter(new SpecReporter());   // add jasmine-spec-reporter
jrunner.loadConfigFile();                           // load jasmine.json configuration
jrunner.execute();
<commit_msg>update jasmine-spec-reporter to version 3.0.0<commit_after>let Jasmine = require('jasmine');
let SpecReporter = require('jasmine-spec-reporter').SpecReporter;

let jrunner = new Jasmine();
jrunner.env.clearReporters();           // remove default reporter logs
jrunner.addReporter(new SpecReporter({  // add jasmine-spec-reporter
  spec: {
    displayPending: true
  }
}));
jrunner.loadConfigFile();               // load jasmine.json configuration
jrunner.execute();
<|endoftext|>


<commit_before>function component( args ) {
/*
base_component_id("export_editor_component")
control_type("SYSTEM")
load_once_from_file(true)
*/

    Vue.component("export_editor_component", {
      data: function () {
        return {
            text:                args.text,
            read_only:           false,
            errors:              null,
            dockerHost:         "host.docker.internal",
            dockerPort:         "1234",
            dockerLocalPort:     "80",
            dockerLocalHost:     location.hostname,
            dockerImageName:    "name/image"
        }
      },
      template:
`

        <slot style='box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);display: inline-block;' v-if='text' :text2="text">
        </slot>

            Export Options

Save App as Docker Container

                        <form onsubmit="return false;">

                                    Docker Image Name

                                <input  type="" class="form-control"
                                        v-model="dockerImageName"
                                        id="docker_image_name"
                                        placeholder="your_docker_id/image_name:version_tag" />

                                        Docker Server Host

                                    <input  type=""
                                            v-model="dockerHost"
                                            class="form-control" id="docker_server"
                                            placeholder="host.docker.internal" />

                                        Docker Port

                                    <input  v-model="dockerPort"
                                            class="form-control" id="docker_port" placeholder="1234" />

                            <button v-on:click="createDockerImage()"
                                    class="btn btn-primary">Create Docker Image
                            </button>
                        </form>

                                    App Local Host

                                <input  type=""
                                        readonly
                                        class="form-control"
                                        v-model="dockerLocalHost"
                                        id="docker_local_host"
                                        placeholder="80" />

                                    Docker Local App Port

                                <input  type=""
                                        class="form-control"
                                        v-model="dockerLocalPort"
                                        id="docker_local_port"
                                        placeholder="80" />

                                Shareable link:<input   readonly
                                                        style='flex:1;font-family:verdana;font-size: 13px;margin-left:10px;'
                                                        v-bind:value='location.protocol + "//" + location.hostname + ":" + dockerLocalPort '>

                    Download App as HTML file

                        <svg    xmlns="http://www.w3.org/2000/svg"
                                xmlns:xlink="http://www.w3.org/1999/xlink"
                                version="1.1" id="Capa_1"
                                viewBox="0 0 29.978 29.978"
                                style="enable-background:new 0 0 29.978 29.978;"
                                xml:space="preserve"
                                x="0px"
                                y="0px"
                                height="35px"
                                width="35px">

                            <path d="M25.462,19.105v6.848H4.515v-6.848H0.489v8.861c0,1.111,0.9,2.012,2.016,2.012h24.967c1.115,0,2.016-0.9,2.016-2.012   v-8.861H25.462z" fill="#006DF0" />
                            <path d="M14.62,18.426l-5.764-6.965c0,0-0.877-0.828,0.074-0.828s3.248,0,3.248,0s0-0.557,0-1.416c0-2.449,0-6.906,0-8.723   c0,0-0.129-0.494,0.615-0.494c0.75,0,4.035,0,4.572,0c0.536,0,0.524,0.416,0.524,0.416c0,1.762,0,6.373,0,8.742   c0,0.768,0,1.266,0,1.266s1.842,0,2.998,0c1.154,0,0.285,0.867,0.285,0.867s-4.904,6.51-5.588,7.193   C15.092,18.979,14.62,18.426,14.62,18.426z" fill="#006DF0" />
                        </svg>
                        Download app as HTML

`
     ,

     mounted: function() {
         var thisVueInstance = this
         args.text           = null

         if (isValidObject(thisVueInstance.text)) {
             this.read_only = saveHelper.getValueOfCodeString(thisVueInstance.text, "read_only")
         }

         if (this.read_only) {
         }

     },
     methods: {

        // -----------------------------------------------------
        //                      getText
        //
        // This is called to get the SQL definitions
        //
        //
        //
        // -----------------------------------------------------
        getText: async function() {
            if (!isValidObject(this.text)) {
                return null
            }

            return this.text
        }
        ,

        // -----------------------------------------------------
        //                      setText
        //
        // This is called to set the SQL
        //
        //
        //
        // -----------------------------------------------------
        setText: function(textValue) {
            var thisVueInstance = this
            this.text           =  textValue

            if (!isValidObject(this.text)) {
                return
            }

            //
            //
            //

            this.read_only = saveHelper.getValueOfCodeString(thisVueInstance.text, "read_only")
            if (this.read_only) {
            }

        }
        ,

        // -----------------------------------------------------
        //                      createDockerImage
        //
        // This is called to create the app as a Docker image
        //
        //
        //
        // -----------------------------------------------------
        createDockerImage: async function() {
            alert("Creating Docker image "  + this.dockerImageName + " at "+ this.dockerHost + ":" + this.dockerPort)
            var result = await callFunction(
                                {
                                    driver_name: "serverDockerStuff",
                                    method_name: "serverDockerStuff"  }
                                    ,{
                                        create:             true,
                                        image_name:         this.dockerImageName,
                                        host:               this.dockerHost,
                                        port:               this.dockerPort,
                                        docker_local_port:  this.dockerLocalPort
                                     })

           //alert(JSON.stringify(result.value,null,2))
           if (result.value) {
                alert(JSON.stringify(   result.value  ,  null  ,  2   ))

           }
       }

     }

    })

}
<commit_msg>Make the export options clearer<commit_after>function component( args ) {
/*
base_component_id("export_editor_component")
control_type("SYSTEM")
load_once_from_file(true)
*/

    Vue.component("export_editor_component", {
      data: function () {
        return {
            text:                args.text,
            read_only:           false,
            errors:              null,
            dockerHost:         "host.docker.internal",
            dockerPort:         "1234",
            dockerLocalPort:     "80",
            dockerLocalHost:     location.hostname,
            dockerImageName:    "name/image"
        }
      },
      template:
`

        <slot style='box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);display: inline-block;' v-if='text' :text2="text">
        </slot>

            Export Options

A) Export App as Docker Container

                        <form onsubmit="return false;">

                                    Docker Image Name

                                <input  type="" class="form-control"
                                        v-model="dockerImageName"
                                        id="docker_image_name"
                                        placeholder="your_docker_id/image_name:version_tag" />

                                        Docker Server Host

                                    <input  type=""
                                            v-model="dockerHost"
                                            class="form-control" id="docker_server"
                                            placeholder="host.docker.internal" />

                                        Docker Port

                                    <input  v-model="dockerPort"
                                            class="form-control" id="docker_port" placeholder="1234" />

                            <button v-on:click="createDockerImage()"
                                    class="btn btn-primary">Create Docker Image
                            </button>
                        </form>

                                    App Local Host

                                <input  type=""
                                        readonly
                                        class="form-control"
                                        v-model="dockerLocalHost"
                                        id="docker_local_host"
                                        placeholder="80" />

                                    Docker Local App Port

                                <input  type=""
                                        class="form-control"
                                        v-model="dockerLocalPort"
                                        id="docker_local_port"
                                        placeholder="80" />

                                Shareable link:<input   readonly
                                                        style='flex:1;font-family:verdana;font-size: 13px;margin-left:10px;'
                                                        v-bind:value='location.protocol + "//" + location.hostname + ":" + dockerLocalPort '>

                    b) Download app as HTML file

                        <svg    xmlns="http://www.w3.org/2000/svg"
                                xmlns:xlink="http://www.w3.org/1999/xlink"
                                version="1.1" id="Capa_1"
                                viewBox="0 0 29.978 29.978"
                                style="enable-background:new 0 0 29.978 29.978;"
                                xml:space="preserve"
                                x="0px"
                                y="0px"
                                height="35px"
                                width="35px">

                            <path d="M25.462,19.105v6.848H4.515v-6.848H0.489v8.861c0,1.111,0.9,2.012,2.016,2.012h24.967c1.115,0,2.016-0.9,2.016-2.012   v-8.861H25.462z" fill="#006DF0" />
                            <path d="M14.62,18.426l-5.764-6.965c0,0-0.877-0.828,0.074-0.828s3.248,0,3.248,0s0-0.557,0-1.416c0-2.449,0-6.906,0-8.723   c0,0-0.129-0.494,0.615-0.494c0.75,0,4.035,0,4.572,0c0.536,0,0.524,0.416,0.524,0.416c0,1.762,0,6.373,0,8.742   c0,0.768,0,1.266,0,1.266s1.842,0,2.998,0c1.154,0,0.285,0.867,0.285,0.867s-4.904,6.51-5.588,7.193   C15.092,18.979,14.62,18.426,14.62,18.426z" fill="#006DF0" />
                        </svg>
                        Download app as HTML

`
     ,

     mounted: function() {
         var thisVueInstance = this
         args.text           = null

         if (isValidObject(thisVueInstance.text)) {
             this.read_only = saveHelper.getValueOfCodeString(thisVueInstance.text, "read_only")
         }

         if (this.read_only) {
         }

     },
     methods: {

        // -----------------------------------------------------
        //                      getText
        //
        // This is called to get the SQL definitions
        //
        //
        //
        // -----------------------------------------------------
        getText: async function() {
            if (!isValidObject(this.text)) {
                return null
            }

            return this.text
        }
        ,

        // -----------------------------------------------------
        //                      setText
        //
        // This is called to set the SQL
        //
        //
        //
        // -----------------------------------------------------
        setText: function(textValue) {
            var thisVueInstance = this
            this.text           =  textValue

            if (!isValidObject(this.text)) {
                return
            }

            //
            //
            //

            this.read_only = saveHelper.getValueOfCodeString(thisVueInstance.text, "read_only")
            if (this.read_only) {
            }

        }
        ,

        // -----------------------------------------------------
        //                      createDockerImage
        //
        // This is called to create the app as a Docker image
        //
        //
        //
        // -----------------------------------------------------
        createDockerImage: async function() {
            alert("Creating Docker image "  + this.dockerImageName + " at "+ this.dockerHost + ":" + this.dockerPort)
            var result = await callFunction(
                                {
                                    driver_name: "serverDockerStuff",
                                    method_name: "serverDockerStuff"  }
                                    ,{
                                        create:             true,
                                        image_name:         this.dockerImageName,
                                        host:               this.dockerHost,
                                        port:               this.dockerPort,
                                        docker_local_port:  this.dockerLocalPort
                                     })

           //alert(JSON.stringify(result.value,null,2))
           if (result.value) {
                alert(JSON.stringify(   result.value  ,  null  ,  2   ))

           }
       }

     }

    })

}
<|endoftext|>


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

/*
 * =========================================================
 * data-tables extended function (Server-side Pagination)
 * =========================================================
 */

/**
 * @namespace $
 * The $ is just a function.
 * It is actually an alias for the function called jQuery.
 * For ex: $(this) means jQuery(this) and S.fn.x means jQuery.fn.x
 */

$.fn.datatables_extended_serverside_paging = function (settings , url, dataFilter,
                                                       columns, fnCreatedRow, fnDrawCallback, options) {
    var elem = $(this);

    // EMM related function
    if (InitiateViewOption) {
        $(".viewEnabledIcon").bind("click", InitiateViewOption);
    }

    var deviceType;
    var ownership;

    //--- End of EMM related codes

    $(elem).DataTable(
        $.extend({},{
            serverSide: true,
            processing: false,
            searching: true,
            ordering:  false,
            filter: false,
            bSortCellsTop: true,
            ajax : {
                url: "/emm/api/data-tables/invoker",
                data : function (params) {
                    var i;
                    var searchParams = {};
                    for (i = 0; i < params.columns.length; i++) {
                        searchParams[params.columns[i].data] = encodeURIComponent(params.columns[i].search.value);
                    }
                    if(options) {
                        searchParams[options.searchKey] = encodeURIComponent(params.search.value);
                    }
                    params.filter = JSON.stringify(searchParams);
                    params.offset = params.start;
                    params.limit = params.length;
                    // if(params.search.value){
                    //     params.filter = params.search.value;
                    // }
                    params.url = url;
                },
                dataFilter: dataFilter
            },
            columns: columns,
            responsive: false,
            autoWidth: false,
            dom:'<"dataTablesTop"' +
                'f' +
                '<"dataTables_toolbar">' +
                '>' +
                'rt' +
                '<"dataTablesBottom"' +
                'lip' +
                '>',
            language: {
                searchPlaceholder: options.placeholder,
                search: ''
            },
            fnCreatedRow: fnCreatedRow,
            "fnDrawCallback": fnDrawCallback,
            initComplete: function () {
                this.api().columns().every(function () {

                    var column = this;
                    var filterColumn = $('.filter-row th', elem);

                    /**
                     *  Create & add select/text filters to each column
                     */
                    if (filterColumn.eq(column.index()).hasClass('select-filter')) {
                        var select = $('<select class="form-control"><option value="">All</option></select>')
                            .appendTo(filterColumn.eq(column.index()).empty())
                            .on('change', function () {
                                var val = $.fn.dataTable.util.escapeRegex(
                                    $(this).val()
                                );

                                column
                                    //.search(val ? '^' + val + '$' : '', true, false)
                                    .search(val ? val : '', true, false)
                                    .draw();

                                if (filterColumn.eq(column.index()).hasClass('data-platform')) {
                                    deviceType = val;
                                    if (!deviceType || !ownership) {
                                        $("#operation-bar").addClass("hidden");
                                        $("#operation-guide").removeClass("hidden");
                                    } else {
                                        $("#operation-guide").addClass("hidden");
                                        $("#operation-bar").removeClass("hidden");
                                        //noinspection JSUnresolvedFunction
                                        if (deviceType && ownership) {
                                            loadOperationBar(deviceType, ownership);
                                        }
                                    }
                                }

                                if (filterColumn.eq(column.index()).hasClass('data-ownership')) {
                                    ownership = val;
                                    if (!deviceType || !ownership) {
                                        $("#operation-bar").addClass("hidden");
                                        $("#operation-guide").removeClass("hidden");
                                    } else {
                                        $("#operation-guide").addClass("hidden");
                                        $("#operation-bar").removeClass("hidden");
                                        //noinspection JSUnresolvedFunction
                                        if (deviceType && ownership) {
                                            loadOperationBar(deviceType, ownership);
                                        }
                                    }
                                }
                            });

                        $(column).each(function () {
                            if ($(column.nodes()).attr('data-search')) {
                                var titles = [];
                                column.nodes().unique().sort().each(function (d, j) {
                                    var title = $(d).attr('data-display');
                                    if ($.inArray(title, titles) < 0) {
                                        titles.push(title);
                                        if (title !== undefined) {
                                            select.append('<option value="' + title + '">' + title + '</option>')
                                        }
                                    }
                                });
                            } else {
                                column.data().unique().sort().each(function (d, j) {
                                    select.append('<option value="' + d + '">' + d + '</option>')
                                });
                            }
                        });
                    } else if (filterColumn.eq(column.index()).hasClass('text-filter')) {
                        var title = filterColumn.eq(column.index()).attr('data-for');
                        $(filterColumn.eq(column.index()).empty()).html('<input type="text" class="form-control" placeholder="Search ' + title + '" />');

                        //noinspection SpellCheckingInspection
                        filterColumn.eq(column.index()).find('input').on('keyup change', function () {
                            column.search($(this).val()).draw();
                        });
                    }

                });

                /**
                 *  search input default styles override
                 */
                var search_input = $(this).closest('.dataTables_wrapper').find('div[id$=_filter] input');
                search_input.before('').removeClass('input-sm');

                /**
                 *  create sorting dropdown menu for list table advance operations
                 */
                var dropdownmenu = $('

Sort by

');
                $('.sort-row th', elem).each(function () {
                    if (!$(this).hasClass('no-sort')) {
                        dropdownmenu.append('
' + $(this).html() + '
');
                    }
                });

                /**
                 *  append advance operations to list table toolbar
                 */
                $('.dataTable.list-table').closest('.dataTables_wrapper').find('.dataTablesTop .dataTables_toolbar').html('' +
                        '
' +
                        '
<button data-click-event="toggle-selectable" class="btn btn-default btn-primary select-enable-btn">Select
' +
                        '
<button data-click-event="toggle-selected" id="dt-select-all" class="btn btn-default btn-primary disabled">Select All
' +
                        '
<button data-click-event="toggle-list-view" data-view="grid" class="btn btn-default"></button>
' +
                        '
<button data-click-event="toggle-list-view" data-view="list" class="btn btn-default"></button>
' +
                        '
<button class="btn btn-default" data-toggle="dropdown"></button>' + dropdownmenu[0].outerHTML + '
' +
                        '
'
                );

                /**
                 *  sorting dropdown menu select function
                 */
                $('.dataTables_wrapper .sort-list li a').click(function () {
                    $(this).closest('li').siblings('li').find('a').removeClass('sorting_asc').removeClass('sorting_desc');

                    var thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();

                    if (!($(this).hasClass('sorting_asc')) && !($(this).hasClass('sorting_desc'))) {
                        $(this).addClass('sorting_asc');
                        thisTable.fnSort([[$(this).attr('data-column'), 'asc']]);
                    }
                    else if ($(this).hasClass('sorting_asc')) {
                        $(this).switchClass('sorting_asc', 'sorting_desc');
                        thisTable.fnSort([[$(this).attr('data-column'), 'desc']]);
                    }
                    else if ($(this).hasClass('sorting_desc')) {
                        $(this).switchClass('sorting_desc', 'sorting_asc');
                        thisTable.fnSort([[$(this).attr('data-column'), 'asc']]);
                    }
                });

                var rowSelectedClass = 'DTTT_selected selected';

                /**
                 *  Enable/Disable selection on rows
                 */
                $('.dataTables_wrapper [data-click-event=toggle-selectable]').click(function () {
                    var button = this,
                        thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();
                    if ($(button).html() == 'Select') {
                        thisTable.addClass("table-selectable");
                        $(button).addClass("active").html('Cancel');
                        $(button).parent().next().children("button").removeClass("disabled");
                        // EMM related code
                        $(".viewEnabledIcon").unbind("click");
                        //--- End of EMM related codes
                    } else if ($(button).html() == 'Cancel') {
                        thisTable.removeClass("table-selectable");
                        $(button).addClass("active").html('Select');
                        $(button).parent().next().children().addClass("disabled");
                        // EMM related function
                        $(".viewEnabledIcon").bind("click", InitiateViewOption);
                        //--- End of EMM related codes
                    }
                });
                /**
                 *  select/deselect all rows function
                 */
                $('.dataTables_wrapper [data-click-event=toggle-selected]').click(function () {
                    var button = this,
                        thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();
                    if (!$(button).hasClass('disabled')) {
                        if ($(button).html() == 'Select All') {
                            thisTable.api().rows().every(function () {
                                $(this.node()).addClass(rowSelectedClass);
                                $(button).html('Deselect All');
                            });
                        }
                        else if ($(button).html() == 'Deselect All') {
                            thisTable.api().rows().every(function () {
                                $(this.node()).removeClass(rowSelectedClass);
                                $(button).html('Select All');
                            });
                        }
                    }
                });

                /**
                 *  on row click select/deselect row function
                 */
                $('body').on('click', '[data-type=selectable]', function () {
                    var rowSelectedClass = 'DTTT_selected selected';
                    $(this).toggleClass(rowSelectedClass);
                    var button = this,
                        thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();

                    thisTable.api().rows().every(function () {
                        if (!$(this.node()).hasClass(rowSelectedClass)) {
                            $(button).closest('.dataTables_wrapper').find('[data-click-event=toggle-selected]').html('Select All');
                        }
                    });
                });

                /**
                 *  list table list/grid view toggle function
                 */
                var toggleButton = $('[data-click-event=toggle-list-view]');
                toggleButton.click(function () {
                    if ($(this).attr('data-view') == 'grid') {
                        $(this).closest('.dataTables_wrapper').find('.dataTable').addClass('grid-view');
                        //$(this).closest('li').hide();
                        //$(this).closest('li').siblings().show();
                    }
                    else {
                        $(this).closest('.dataTables_wrapper').find('.dataTable').removeClass('grid-view');
                        //$(this).closest('li').hide();
                        //$(this).closest('li').siblings().show();
                    }
                })
            }
        },settings)
    );
};
<commit_msg>FIX for JIRAS: https://wso2.org/jira/browse/EMM-1633<commit_after>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*
 * =========================================================
 * data-tables extended function (Server-side Pagination)
 * =========================================================
 */

/**
 * @namespace $
 * The $ is just a function.
 * It is actually an alias for the function called jQuery.
 * For ex: $(this) means jQuery(this) and S.fn.x means jQuery.fn.x
 */

$.fn.datatables_extended_serverside_paging = function (settings , url, dataFilter,
                                                       columns, fnCreatedRow, fnDrawCallback, options) {
    var elem = $(this);

    // EMM related function
    if (InitiateViewOption) {
        $(".viewEnabledIcon").bind("click", InitiateViewOption);
    }

    var deviceType;
    var ownership;

    //--- End of EMM related codes

    $(elem).DataTable(
        $.extend({},{
            serverSide: true,
            processing: false,
            searching: true,
            ordering:  false,
            filter: false,
            bSortCellsTop: true,
            ajax : {
                url: "/emm/api/data-tables/invoker",
                data : function (params) {
                    var i;
                    var searchParams = {};
                    for (i = 0; i < params.columns.length; i++) {
                        searchParams[params.columns[i].data] = encodeURIComponent(params.columns[i].search.value);
                    }
                    if(options) {
                        searchParams[options.searchKey] = encodeURIComponent(params.search.value);
                    }
                    params.filter = JSON.stringify(searchParams);
                    params.offset = params.start;
                    params.limit = params.length;
                    // if(params.search.value){
                    //     params.filter = params.search.value;
                    // }
                    params.url = url;
                },
                dataFilter: dataFilter
            },
            columns: columns,
            responsive: false,
            autoWidth: false,
            dom:'<"dataTablesTop"' +
                'f' +
                '<"dataTables_toolbar">' +
                '>' +
                'rt' +
                '<"dataTablesBottom"' +
                'lip' +
                '>',
            language: {
                searchPlaceholder: options.placeholder,
                search: ''
            },
            fnCreatedRow: fnCreatedRow,
            "fnDrawCallback": fnDrawCallback,
            initComplete: function () {
                this.api().columns().every(function () {

                    var column = this;
                    var filterColumn = $('.filter-row th', elem);

                    /**
                     *  Create & add select/text filters to each column
                     */
                    if (filterColumn.eq(column.index()).hasClass('select-filter')) {
                        var select = $('<select class="form-control"><option value="">All</option></select>')
                            .appendTo(filterColumn.eq(column.index()).empty())
                            .on('change', function () {
                                var val = $.fn.dataTable.util.escapeRegex(
                                    $(this).val()
                                );

                                column
                                    //.search(val ? '^' + val + '$' : '', true, false)
                                    .search(val ? val : '', true, false)
                                    .draw();

                                if (filterColumn.eq(column.index()).hasClass('data-platform')) {
                                    deviceType = val;
                                    if (!deviceType || !ownership) {
                                        $("#operation-bar").addClass("hidden");
                                        $("#operation-guide").removeClass("hidden");
                                    } else {
                                        $("#operation-guide").addClass("hidden");
                                        $("#operation-bar").removeClass("hidden");
                                        //noinspection JSUnresolvedFunction
                                        if (deviceType && ownership) {
                                            loadOperationBar(deviceType, ownership, operationBarModeConstants.BULK);
                                        }
                                    }
                                }

                                if (filterColumn.eq(column.index()).hasClass('data-ownership')) {
                                    ownership = val;
                                    if (!deviceType || !ownership) {
                                        $("#operation-bar").addClass("hidden");
                                        $("#operation-guide").removeClass("hidden");
                                    } else {
                                        $("#operation-guide").addClass("hidden");
                                        $("#operation-bar").removeClass("hidden");
                                        //noinspection JSUnresolvedFunction
                                        if (deviceType && ownership) {
                                            loadOperationBar(deviceType, ownership, operationBarModeConstants.BULK);
                                        }
                                    }
                                }
                            });

                        $(column).each(function () {
                            if ($(column.nodes()).attr('data-search')) {
                                var titles = [];
                                column.nodes().unique().sort().each(function (d, j) {
                                    var title = $(d).attr('data-display');
                                    if ($.inArray(title, titles) < 0) {
                                        titles.push(title);
                                        if (title !== undefined) {
                                            select.append('<option value="' + title + '">' + title + '</option>')
                                        }
                                    }
                                });
                            } else {
                                column.data().unique().sort().each(function (d, j) {
                                    select.append('<option value="' + d + '">' + d + '</option>')
                                });
                            }
                        });
                    } else if (filterColumn.eq(column.index()).hasClass('text-filter')) {
                        var title = filterColumn.eq(column.index()).attr('data-for');
                        $(filterColumn.eq(column.index()).empty()).html('<input type="text" class="form-control" placeholder="Search ' + title + '" />');

                        //noinspection SpellCheckingInspection
                        filterColumn.eq(column.index()).find('input').on('keyup change', function () {
                            column.search($(this).val()).draw();
                        });
                    }

                });

                /**
                 *  search input default styles override
                 */
                var search_input = $(this).closest('.dataTables_wrapper').find('div[id$=_filter] input');
                search_input.before('').removeClass('input-sm');

                /**
                 *  create sorting dropdown menu for list table advance operations
                 */
                var dropdownmenu = $('

Sort by

');
                $('.sort-row th', elem).each(function () {
                    if (!$(this).hasClass('no-sort')) {
                        dropdownmenu.append('
' + $(this).html() + '
');
                    }
                });

                /**
                 *  append advance operations to list table toolbar
                 */
                $('.dataTable.list-table').closest('.dataTables_wrapper').find('.dataTablesTop .dataTables_toolbar').html('' +
                        '
' +
                        '
<button data-click-event="toggle-selectable" class="btn btn-default btn-primary select-enable-btn">Select
' +
                        '
<button data-click-event="toggle-selected" id="dt-select-all" class="btn btn-default btn-primary disabled">Select All
' +
                        '
<button data-click-event="toggle-list-view" data-view="grid" class="btn btn-default"></button>
' +
                        '
<button data-click-event="toggle-list-view" data-view="list" class="btn btn-default"></button>
' +
                        '
<button class="btn btn-default" data-toggle="dropdown"></button>' + dropdownmenu[0].outerHTML + '
' +
                        '
'
                );

                /**
                 *  sorting dropdown menu select function
                 */
                $('.dataTables_wrapper .sort-list li a').click(function () {
                    $(this).closest('li').siblings('li').find('a').removeClass('sorting_asc').removeClass('sorting_desc');

                    var thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();

                    if (!($(this).hasClass('sorting_asc')) && !($(this).hasClass('sorting_desc'))) {
                        $(this).addClass('sorting_asc');
                        thisTable.fnSort([[$(this).attr('data-column'), 'asc']]);
                    }
                    else if ($(this).hasClass('sorting_asc')) {
                        $(this).switchClass('sorting_asc', 'sorting_desc');
                        thisTable.fnSort([[$(this).attr('data-column'), 'desc']]);
                    }
                    else if ($(this).hasClass('sorting_desc')) {
                        $(this).switchClass('sorting_desc', 'sorting_asc');
                        thisTable.fnSort([[$(this).attr('data-column'), 'asc']]);
                    }
                });

                var rowSelectedClass = 'DTTT_selected selected';

                /**
                 *  Enable/Disable selection on rows
                 */
                $('.dataTables_wrapper [data-click-event=toggle-selectable]').click(function () {
                    var button = this,
                        thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();
                    if ($(button).html() == 'Select') {
                        thisTable.addClass("table-selectable");
                        $(button).addClass("active").html('Cancel');
                        $(button).parent().next().children("button").removeClass("disabled");
                        // EMM related code
                        $(".viewEnabledIcon").unbind("click");
                        //--- End of EMM related codes
                    } else if ($(button).html() == 'Cancel') {
                        thisTable.removeClass("table-selectable");
                        $(button).addClass("active").html('Select');
                        $(button).parent().next().children().addClass("disabled");
                        // EMM related function
                        $(".viewEnabledIcon").bind("click", InitiateViewOption);
                        //--- End of EMM related codes
                    }
                });
                /**
                 *  select/deselect all rows function
                 */
                $('.dataTables_wrapper [data-click-event=toggle-selected]').click(function () {
                    var button = this,
                        thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();
                    if (!$(button).hasClass('disabled')) {
                        if ($(button).html() == 'Select All') {
                            thisTable.api().rows().every(function () {
                                $(this.node()).addClass(rowSelectedClass);
                                $(button).html('Deselect All');
                            });
                        }
                        else if ($(button).html() == 'Deselect All') {
                            thisTable.api().rows().every(function () {
                                $(this.node()).removeClass(rowSelectedClass);
                                $(button).html('Select All');
                            });
                        }
                    }
                });

                /**
                 *  on row click select/deselect row function
                 */
                $('body').on('click', '[data-type=selectable]', function () {
                    var rowSelectedClass = 'DTTT_selected selected';
                    $(this).toggleClass(rowSelectedClass);
                    var button = this,
                        thisTable = $(this).closest('.dataTables_wrapper').find('.dataTable').dataTable();

                    thisTable.api().rows().every(function () {
                        if (!$(this.node()).hasClass(rowSelectedClass)) {
                            $(button).closest('.dataTables_wrapper').find('[data-click-event=toggle-selected]').html('Select All');
                        }
                    });
                });

                /**
                 *  list table list/grid view toggle function
                 */
                var toggleButton = $('[data-click-event=toggle-list-view]');
                toggleButton.click(function () {
                    if ($(this).attr('data-view') == 'grid') {
                        $(this).closest('.dataTables_wrapper').find('.dataTable').addClass('grid-view');
                        //$(this).closest('li').hide();
                        //$(this).closest('li').siblings().show();
                    }
                    else {
                        $(this).closest('.dataTables_wrapper').find('.dataTable').removeClass('grid-view');
                        //$(this).closest('li').hide();
                        //$(this).closest('li').siblings().show();
                    }
                })
            }
        },settings)
    );
};
<|endoftext|>


<commit_before>//   (c) 2004-2006 by MulchProductions, www.mulchprod.de
//   (c) 2007-2014 by Kajona, www.kajona.de
//       Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt
//       $Id$

if (typeof KAJONA == "undefined") {
    var KAJONA = {
        util: {},
        portal: {
            lang: {}
        },
        admin: {
            lang: {}
        }
    };
}

/*
 * -------------------------------------------------------------------------
 * Global functions
 * -------------------------------------------------------------------------
 */

/**
 * Checks if the given array contains the given string
 *
 * @param {String} strNeedle
 * @param {String[]} arrHaystack
 */
KAJONA.util.inArray = function (strNeedle, arrHaystack) {
    for (var i = 0; i < arrHaystack.length; i++) {
        if (arrHaystack[i] == strNeedle) {
            return true;
        }
    }
    return false;
};

/**
 * Used to show/hide an html element
 *
 * @param {String} strElementId
 * @param {Function} objCallbackVisible
 * @param {Function} objCallbackInvisible
 */
KAJONA.util.fold = function (strElementId, objCallbackVisible, objCallbackInvisible) {
    var element = document.getElementById(strElementId);
    if (element.style.display == 'none') 	{
        element.style.display = 'block';
        if ($.isFunction(objCallbackVisible)) {
            objCallbackVisible();
        }
    }
    else {
        element.style.display = 'none';
        if ($.isFunction(objCallbackInvisible)) {
            objCallbackInvisible();
        }
    }
};

KAJONA.util.isTouchDevice = function() {
    return !!('ontouchstart' in window) ? 1 : 0;
};

/*
 * -------------------------------------------------------------------------
 * Portal-specific functions
 * -------------------------------------------------------------------------
 */

/**
 * Loads/Reloads the Kajona captcha image with the given element id
 *
 * @param {String} strCaptchaId
 * @param {Number} intWidth
 */
KAJONA.portal.loadCaptcha = function (strCaptchaId, intWidth) {
    var containerName = "kajonaCaptcha";
    var imgID = "kajonaCaptchaImg";

    if(strCaptchaId != null) {
        containerName += "_"+strCaptchaId;
        imgID += "_"+strCaptchaId;
    } else {
        //fallback for old templates (old function call)
        imgID = "kajonaCaptcha";
    }
    if (!intWidth) {
        var intWidth = 180;
    }

    var timeCode = new Date().getTime();
    if (document.getElementById(imgID) == undefined) {
        var objImg=document.createElement("img");
        objImg.setAttribute("id", imgID);
        objImg.setAttribute("src", KAJONA_WEBPATH+"/image.php?image=kajonaCaptcha&maxWidth="+intWidth+"&reload="+timeCode);
        document.getElementById(containerName).appendChild(objImg);
    } else {
        var objImg = document.getElementById(imgID);
        objImg.src = objImg.src + "&reload="+timeCode;
    }
};

/**
 * Tooltips
 *
 * originally based on Bubble Tooltips by Alessandro Fulciniti (http://pro.html.it - http://web-graphics.com)
 */
KAJONA.portal.tooltip = (function() {
    var container;
    var lastMouseX = 0;
    var lastMouseY = 0;

    function locate(e) {
        var posx = 0, posy = 0, c;
        if (e == null) {
            e = window.event;
        }
        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        } else if (e.clientX || e.clientY) {
            if (document.documentElement.scrollTop) {
                posx = e.clientX + document.documentElement.scrollLeft;
                posy = e.clientY + document.documentElement.scrollTop;
            } else {
                posx = e.clientX + document.body.scrollLeft;
                posy = e.clientY + document.body.scrollTop;
            }
        }

        //save current x and y pos (needed to show tooltip at right position if it's added by onclick)
        if (posx == 0 && posy == 0) {
            posx = lastMouseX;
            posy = lastMouseY;
        } else {
            lastMouseX = posx;
            lastMouseY = posy;
        }

        c = container;
        var left = (posx - c.offsetWidth);
        if (left - c.offsetWidth < 0) {
            left += c.offsetWidth;
        }
        c.style.top = (posy + 10) + "px";
        c.style.left = left + "px";
    }

    function add(objElement, strHtmlContent, bitOpacity) {
        var tooltip;

        if (strHtmlContent == null || strHtmlContent.length == 0) {
            try {
                strHtmlContent = objElement.getAttribute("title");
            } catch (e) {}
        }
        if (strHtmlContent == null || strHtmlContent.length == 0) {
            return;
        }

        //try to remove title
        try {
            objElement.removeAttribute("title");
        } catch (e) {}

        tooltip = document.createElement("span");
        tooltip.className = "kajonaTooltip";
        tooltip.style.display = "block";
        tooltip.innerHTML = strHtmlContent;

        if (bitOpacity != false) {
            tooltip.style.filter = "alpha(opacity:85)";
            tooltip.style.KHTMLOpacity = "0.85";
            tooltip.style.MozOpacity = "0.85";
            tooltip.style.opacity = "0.85";
        }

        //create tooltip container and save reference
        if (container == null) {
            var h = document.createElement("span");
            h.id = "kajonaTooltipContainer";
            h.setAttribute("id", "kajonaTooltipContainer");
            h.style.position = "absolute";
            h.style.zIndex = "2000";
            document.getElementsByTagName("body")[0].appendChild(h);
            container = h;
        }

        objElement.tooltip = tooltip;
        objElement.onmouseover = show;
        objElement.onmouseout = hide;
        objElement.onmousemove = locate;
        objElement.onmouseover(objElement);
    }

    function show(objEvent) {
        hide();
        container.appendChild(this.tooltip);
        locate(objEvent);
    }

    function hide() {
        try {
            var c = container;
            if (c.childNodes.length > 0) {
                c.removeChild(c.firstChild);
            }
        } catch (e) {}
    }

    //public variables and methods
    return {
        add : add,
        show : show,
        hide : hide
    }
}());

KAJONA.portal.loader = new KAJONA.util.Loader();

<commit_msg>BUG: module_system | kajona.js -> the captcha is only reloaded / added if the container is present<commit_after>//   (c) 2004-2006 by MulchProductions, www.mulchprod.de
//   (c) 2007-2014 by Kajona, www.kajona.de
//       Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt
//       $Id$

if (typeof KAJONA == "undefined") {
    var KAJONA = {
        util: {},
        portal: {
            lang: {}
        },
        admin: {
            lang: {}
        }
    };
}

/*
 * -------------------------------------------------------------------------
 * Global functions
 * -------------------------------------------------------------------------
 */

/**
 * Checks if the given array contains the given string
 *
 * @param {String} strNeedle
 * @param {String[]} arrHaystack
 */
KAJONA.util.inArray = function (strNeedle, arrHaystack) {
    for (var i = 0; i < arrHaystack.length; i++) {
        if (arrHaystack[i] == strNeedle) {
            return true;
        }
    }
    return false;
};

/**
 * Used to show/hide an html element
 *
 * @param {String} strElementId
 * @param {Function} objCallbackVisible
 * @param {Function} objCallbackInvisible
 */
KAJONA.util.fold = function (strElementId, objCallbackVisible, objCallbackInvisible) {
    var element = document.getElementById(strElementId);
    if (element.style.display == 'none') 	{
        element.style.display = 'block';
        if ($.isFunction(objCallbackVisible)) {
            objCallbackVisible();
        }
    }
    else {
        element.style.display = 'none';
        if ($.isFunction(objCallbackInvisible)) {
            objCallbackInvisible();
        }
    }
};

KAJONA.util.isTouchDevice = function() {
    return !!('ontouchstart' in window) ? 1 : 0;
};

/*
 * -------------------------------------------------------------------------
 * Portal-specific functions
 * -------------------------------------------------------------------------
 */

/**
 * Loads/Reloads the Kajona captcha image with the given element id
 *
 * @param {String} strCaptchaId
 * @param {Number} intWidth
 */
KAJONA.portal.loadCaptcha = function (strCaptchaId, intWidth) {
    var containerName = "kajonaCaptcha";
    var imgID = "kajonaCaptchaImg";

    if(strCaptchaId != null) {
        containerName += "_"+strCaptchaId;
        imgID += "_"+strCaptchaId;
    } else {
        //fallback for old templates (old function call)
        imgID = "kajonaCaptcha";
    }
    if (!intWidth) {
        var intWidth = 180;
    }

    var timeCode = new Date().getTime();
    if (document.getElementById(imgID) == undefined && document.getElementById(containerName) != null) {
        var objImg=document.createElement("img");
        objImg.setAttribute("id", imgID);
        objImg.setAttribute("src", KAJONA_WEBPATH+"/image.php?image=kajonaCaptcha&maxWidth="+intWidth+"&reload="+timeCode);
        document.getElementById(containerName).appendChild(objImg);
    } else if(document.getElementById(imgID) != undefined) {
        var objImg = document.getElementById(imgID);
        objImg.src = objImg.src + "&reload="+timeCode;
    }
};

/**
 * Tooltips
 *
 * originally based on Bubble Tooltips by Alessandro Fulciniti (http://pro.html.it - http://web-graphics.com)
 */
KAJONA.portal.tooltip = (function() {
    var container;
    var lastMouseX = 0;
    var lastMouseY = 0;

    function locate(e) {
        var posx = 0, posy = 0, c;
        if (e == null) {
            e = window.event;
        }
        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        } else if (e.clientX || e.clientY) {
            if (document.documentElement.scrollTop) {
                posx = e.clientX + document.documentElement.scrollLeft;
                posy = e.clientY + document.documentElement.scrollTop;
            } else {
                posx = e.clientX + document.body.scrollLeft;
                posy = e.clientY + document.body.scrollTop;
            }
        }

        //save current x and y pos (needed to show tooltip at right position if it's added by onclick)
        if (posx == 0 && posy == 0) {
            posx = lastMouseX;
            posy = lastMouseY;
        } else {
            lastMouseX = posx;
            lastMouseY = posy;
        }

        c = container;
        var left = (posx - c.offsetWidth);
        if (left - c.offsetWidth < 0) {
            left += c.offsetWidth;
        }
        c.style.top = (posy + 10) + "px";
        c.style.left = left + "px";
    }

    function add(objElement, strHtmlContent, bitOpacity) {
        var tooltip;

        if (strHtmlContent == null || strHtmlContent.length == 0) {
            try {
                strHtmlContent = objElement.getAttribute("title");
            } catch (e) {}
        }
        if (strHtmlContent == null || strHtmlContent.length == 0) {
            return;
        }

        //try to remove title
        try {
            objElement.removeAttribute("title");
        } catch (e) {}

        tooltip = document.createElement("span");
        tooltip.className = "kajonaTooltip";
        tooltip.style.display = "block";
        tooltip.innerHTML = strHtmlContent;

        if (bitOpacity != false) {
            tooltip.style.filter = "alpha(opacity:85)";
            tooltip.style.KHTMLOpacity = "0.85";
            tooltip.style.MozOpacity = "0.85";
            tooltip.style.opacity = "0.85";
        }

        //create tooltip container and save reference
        if (container == null) {
            var h = document.createElement("span");
            h.id = "kajonaTooltipContainer";
            h.setAttribute("id", "kajonaTooltipContainer");
            h.style.position = "absolute";
            h.style.zIndex = "2000";
            document.getElementsByTagName("body")[0].appendChild(h);
            container = h;
        }

        objElement.tooltip = tooltip;
        objElement.onmouseover = show;
        objElement.onmouseout = hide;
        objElement.onmousemove = locate;
        objElement.onmouseover(objElement);
    }

    function show(objEvent) {
        hide();
        container.appendChild(this.tooltip);
        locate(objEvent);
    }

    function hide() {
        try {
            var c = container;
            if (c.childNodes.length > 0) {
                c.removeChild(c.firstChild);
            }
        } catch (e) {}
    }

    //public variables and methods
    return {
        add : add,
        show : show,
        hide : hide
    }
}());

KAJONA.portal.loader = new KAJONA.util.Loader();

<|endoftext|>


<commit_before>const webpack = require("webpack");
const path = require("path");

const isProduction = process.env.NODE_ENV === "production";
module.exports = {
    entry: "./index",
    optimization: {
        minimize: isProduction
    },
    node: {
        fs: "empty"
    },
    output: {
        path: path.resolve("../../../admin/personaBar/scripts/exportables/Users"),
        filename: "UsersCommon.js",
        publicPath: isProduction ? "" : "http://localhost:8050/dist/"
    },
    module: {
        rules: [
            { test: /\.(js|jsx)$/, enforce: "pre", exclude: /node_modules/, loader: "eslint-loader", options: { fix: true } },
            { test: /\.(js|jsx)$/, exclude: /node_modules/, loaders: "babel-loader",
                options: {
                    presets: ['@babel/preset-env', '@babel/preset-react'],
                    "plugins": [
                        "@babel/plugin-transform-react-jsx",
                        "@babel/plugin-proposal-object-rest-spread"
                    ]
                }
            },
            { test: /\.(less|css)$/, loader: ["style-loader","css-loader","less-loader"] },
            { test: /\.(ttf|woff)$/, loader: "url-loader?limit=8192" },
            { test: /\.(gif|png)$/, loader: "url-loader?mimetype=image/png" },
            { test: /\.woff(2)?(\?v=[0-9].[0-9].[0-9])?$/, loader: "url-loader?mimetype=application/font-woff" },
            { test: /\.(ttf|eot|svg)(\?v=[0-9].[0-9].[0-9])?$/, loader: "file-loader?name=[name].[ext]" },
        ]
    },
    externals: require("@dnnsoftware/dnn-react-common/WebpackExternals"),
    resolve: {
        extensions: [".js", ".json", ".jsx"],
        modules: [
            path.resolve(__dirname, "./src"),
            path.resolve(__dirname, "../"),
            path.resolve(__dirname, "node_modules"),
            path.resolve(__dirname, "../../node_modules")
        ]
    },
    devtool: "source-map"
};
<commit_msg>add failback to yarn workspaces node_modules folder<commit_after>const webpack = require("webpack");
const path = require("path");

const isProduction = process.env.NODE_ENV === "production";
module.exports = {
    entry: "./index",
    optimization: {
        minimize: isProduction
    },
    node: {
        fs: "empty"
    },
    output: {
        path: path.resolve("../../../admin/personaBar/scripts/exportables/Users"),
        filename: "UsersCommon.js",
        publicPath: isProduction ? "" : "http://localhost:8050/dist/"
    },
    module: {
        rules: [
            { test: /\.(js|jsx)$/, enforce: "pre", exclude: /node_modules/, loader: "eslint-loader", options: { fix: true } },
            { test: /\.(js|jsx)$/, exclude: /node_modules/, loaders: "babel-loader",
                options: {
                    presets: ['@babel/preset-env', '@babel/preset-react'],
                    "plugins": [
                        "@babel/plugin-transform-react-jsx",
                        "@babel/plugin-proposal-object-rest-spread"
                    ]
                }
            },
            { test: /\.(less|css)$/, loader: ["style-loader","css-loader","less-loader"] },
            { test: /\.(ttf|woff)$/, loader: "url-loader?limit=8192" },
            { test: /\.(gif|png)$/, loader: "url-loader?mimetype=image/png" },
            { test: /\.woff(2)?(\?v=[0-9].[0-9].[0-9])?$/, loader: "url-loader?mimetype=application/font-woff" },
            { test: /\.(ttf|eot|svg)(\?v=[0-9].[0-9].[0-9])?$/, loader: "file-loader?name=[name].[ext]" },
        ]
    },
    externals: require("@dnnsoftware/dnn-react-common/WebpackExternals"),
    resolve: {
        extensions: [".js", ".json", ".jsx"],
        modules: [
            path.resolve(__dirname, "./src"),
            path.resolve(__dirname, "../"),
            path.resolve(__dirname, "node_modules"),
            path.resolve(__dirname, "../../node_modules"),
            path.resolve(__dirname, "../../../node_modules")
        ]
    },
    devtool: "source-map"
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var vzla = require('./index');
var program = require('commander');
var colors = require('colors');
var path = require('path');
var pkg = require(path.join(__dirname, 'package.json'));
var bandera = '    ' +
    colors.yellow.bold('• ') +
    colors.blue.bold('• ') +
    colors.red.bold('• ');
var respuesta;
var t1;
var t2;
var t3;
var t4;
var t5;

program
    .version(pkg.version)
    .usage('<estado|municipio|parroquia> [opciones]')
    .description(colors.yellow('Muestra información sobre el territorio Venezolano.'.bold))
    .option('-a, --ayuda', 'muestra cómo utilizar venezuela-js')
    .option('-c, --capital', 'muestra la información de la capital')
    .option('-m, --municipio', 'muestra la información de un municipio')
    .option('-p, --parroquia', 'muestra la información de una parroquia')
    .parse(process.argv);

program.on('--help', function(){
  console.log('  Ejemplos:');
  console.log('');
  console.log('    $ venezuela --parroquia "San Juan"');
  console.log('    $ venezuela --capital');
  console.log('    $ venezuela Bolívar');
  console.log('');
});

if ((!program.args.length && program.capital) || program.args[0] === 'caracas') {
    respuesta = JSON.stringify(vzla.capital, null, 4);
} else if (!program.args.length || program.ayuda) {
    return program.help();
} else if (program.capital) {
    if (vzla.parroquia(program.args[0]).capital) {
        respuesta = vzla.parroquia(program.args[0]).capital;
    } else if (vzla.municipio(program.args[0]).capital) {
        respuesta = vzla.municipio(program.args[0]).capital;
    } else if (vzla.estado(program.args[0]).capital) {
        respuesta = vzla.estado(program.args[0]).capital;
    } else {
        respuesta = program.args[0] + ' es un nombre inválido.';
    }
} else if (program.municipio) {
    respuesta = JSON.stringify(vzla.municipio(program.args[0]), null, 2);
} else if (program.parroquia) {
    respuesta = JSON.stringify(vzla.parroquia(program.args[0]), null, 2);
} else {
    if (!/Tal[ ]vez/.test(vzla.estado(program.args[0]))) {
        respuesta = vzla.estado(program.args[0])
        t1 = colors.white.bold('    ISO 31662     ');
        t2 = colors.white.bold('    ESTADO        ');
        t3 = colors.white.bold('    CAPITAL       ');
        t4 = colors.white.bold('    MUNICIPIOS    ');
        t5 = colors.white.bold('    PARROQUIAS    ');
        console.log('');
        console.log(bandera);
        console.log('');
        console.log(t1 + colors.yellow.bold(respuesta.iso_31662));
        console.log(t2 + colors.yellow.bold(respuesta.capital));
        console.log(t3 + colors.yellow.bold(respuesta.estado));
        console.log(t4 + colors.yellow.bold(respuesta.municipios));
        console.log(t5 + colors.yellow.bold(respuesta.parroquias));
        console.log('');
        return;
    } else if (!/Tal[ ]vez/.test(vzla.municipio(program.args[0]))) {
        respuesta = JSON.stringify(vzla.municipio(program.args[0]), null, 4);
    } else if (!/Tal[ ]vez/.test(vzla.parroquia(program.args[0]))) {
        respuesta = JSON.stringify(vzla.parroquia(program.args[0]), null, 4);
    } else {
        respuesta = program.args[0] + ' es un nombre inválido.';
    }
}

console.log('');
console.log(bandera);
console.log('');
console.log(colors.white.bold(respuesta));
console.log('');<commit_msg>Pequeños cambios de estilo :sparkles:<commit_after>#!/usr/bin/env node

var vzla = require('./index');
var program = require('commander');
var colors = require('colors');
var path = require('path');
var pkg = require(path.join(__dirname, 'package.json'));
var bandera = '    ' +
    colors.yellow.bold('• ') +
    colors.blue.bold('• ') +
    colors.red.bold('• ');
var respuesta;
var t1;
var t2;
var t3;
var t4;
var t5;

program
    .version(pkg.version)
    .usage('<estado|municipio|parroquia> [opciones]')
    .description(colors.yellow('Muestra información sobre el territorio Venezolano.'.bold))
    .option('-a, --ayuda', 'muestra cómo utilizar venezuela-js')
    .option('-c, --capital', 'muestra la información de la capital')
    .option('-m, --municipio', 'muestra la información de un municipio')
    .option('-p, --parroquia', 'muestra la información de una parroquia')
    .parse(process.argv);

program.on('--help', function(){
  console.log('  Ejemplos:');
  console.log('');
  console.log('    $ venezuela --parroquia "San Juan"');
  console.log('    $ venezuela --capital');
  console.log('    $ venezuela Bolívar');
  console.log('');
});

if ((!program.args.length && program.capital) || program.args[0] === 'caracas') {
    respuesta = JSON.stringify(vzla.capital, null, 4);
} else if (!program.args.length || program.ayuda) {
    return program.help();
} else if (program.capital) {
    if (vzla.parroquia(program.args[0]).capital) {
        respuesta = vzla.parroquia(program.args[0]).capital;
    } else if (vzla.municipio(program.args[0]).capital) {
        respuesta = vzla.municipio(program.args[0]).capital;
    } else if (vzla.estado(program.args[0]).capital) {
        respuesta = vzla.estado(program.args[0]).capital;
    } else {
        respuesta = program.args[0] + ' es un nombre inválido.';
    }
} else if (program.municipio) {
    respuesta = JSON.stringify(vzla.municipio(program.args[0]), null, 2);
} else if (program.parroquia) {
    respuesta = JSON.stringify(vzla.parroquia(program.args[0]), null, 2);
} else {
    if (!/Tal[ ]vez/.test(vzla.estado(program.args[0]))) {
        respuesta = vzla.estado(program.args[0])
        t1 = colors.white.bold('     ISO 31662    ');
        t2 = colors.white.bold('        ESTADO    ');
        t3 = colors.white.bold('       CAPITAL    ');
        t4 = colors.white.bold('    MUNICIPIOS    ');
        t5 = colors.white.bold('    PARROQUIAS    ');
        console.log('');
        console.log(bandera);
        console.log('');
        console.log(t1 + colors.yellow.bold(respuesta.iso_31662));
        console.log(t2 + colors.yellow.bold(respuesta.capital));
        console.log(t3 + colors.yellow.bold(respuesta.estado));
        console.log(t4 + colors.yellow.bold(respuesta.municipios));
        console.log(t5 + colors.yellow.bold(respuesta.parroquias));
        console.log('');
        return;
    } else if (!/Tal[ ]vez/.test(vzla.municipio(program.args[0]))) {
        respuesta = JSON.stringify(vzla.municipio(program.args[0]), null, 4);
    } else if (!/Tal[ ]vez/.test(vzla.parroquia(program.args[0]))) {
        respuesta = JSON.stringify(vzla.parroquia(program.args[0]), null, 4);
    } else {
        respuesta = program.args[0] + ' es un nombre inválido.';
    }
}

console.log('');
console.log(bandera);
console.log('');
console.log(colors.white.bold(respuesta));
console.log('');<|endoftext|>


<commit_before>(function() {

var RoutableState = require('../lib/routable_state'), router = require('../lib/router');

describe('RoutableState', function() {
  beforeEach(function() {
    this.statechart = RoutableState.define(function() {
      this.state('index', function() {
        this.route('/foos', {default: true});
      });

      this.state('show', function() {
        this.route('/foos/:id');
      });

      this.state('other', function() {
        this.route('/bars/:id');
      });

      this.state('noroute', function() {
      });
    });

    this.window = {
      addEventListener: function() {},
      removeEventListener: function() {},
      history: {
        replaceState: jasmine.createSpy('replaceState'),
        pushState: jasmine.createSpy('pushState')
      },
      location: {pathname: '/', search: ''}
    };

    this.statechart.start({window: this.window});
    router.flush();
  });

  afterEach(function() {
    router.reset();
  });

  describe('#route', function() {
    it('throws an exception when a route has already been defined on the state', function() {
      var state = this.statechart.resolve('/index');
      expect(function() {
        state.route('/abc');
      }).toThrow(new Error('RoutableState#route: a route has already been defined on ' + state));
    });

    it('throws an exception when given a state string that does not resolve', function() {
      expect(function() {
        RoutableState.define(function() {
          this.route('/foo/bar', './foo/bar');
        });
      }).toThrow(new Error('RoutableState#route: invalid state: ./foo/bar'));
    });

    it('registers the route with the router when the state is attached', function() {
      spyOn(router, 'define');
      RoutableState.define(function() {
        this.state('a', function() {
          this.route('/aaa');
        });
      });

      expect(router.define).toHaveBeenCalled();
      expect(router.define.calls.mostRecent().args[0]).toEqual('/aaa');
    });

    it('does not register the route with the router when the state is not attached', function() {
      spyOn(router, 'define');
      new RoutableState('foo', function() {
        this.route('/foo');
      });
      expect(router.define).not.toHaveBeenCalled();
    });
  });

  describe('RoutableState#didAttach', function() {
    it('registers the pending route with the router', function() {
      var s = RoutableState.define(), a;

      spyOn(router, 'define');

      a = new RoutableState('a', function() {
        this.route('/aaa');
      });

      expect(router.define).not.toHaveBeenCalled();
      s.state(a);
      expect(router.define).toHaveBeenCalled();
    });
  });

  describe('on popstate events', function() {
    it('triggers a transition to the state with the matching route', function() {
      router._handleLocationChange('/foos/1', '');
      router.flush();
      expect(this.statechart.current()).toEqual(['/show']);
      router._handleLocationChange('/foos', '');
      router.flush();
      expect(this.statechart.current()).toEqual(['/index']);
    });

    it('triggers a transition to the default route when the path is the root path', function() {
      router._handleLocationChange('/foos/1', '');
      router.flush();
      expect(this.statechart.current()).toEqual(['/show']);
      router._handleLocationChange('/', '');
      router.flush();
      expect(this.statechart.current()).toEqual(['/index']);
    });

    describe('with routes defined with a state string', function() {
      beforeEach(function() {
        this.statechart = RoutableState.define(function() {
          this.state('start');
          this.state('A');
          this.state('B');
          this.state('C');

          this.route('/a', './A');
          this.route('/b', './B');
          this.route('/c', './C');
        });

        this.statechart.goto('/start');
      });

      it('triggers a transition to the state with the matching route', function() {
        expect(this.statechart.current()).toEqual(['/start']);
        router._handleLocationChange('/a', '');
        router.flush();
        expect(this.statechart.current()).toEqual(['/A']);
        router._handleLocationChange('/b', '');
        router.flush();
        expect(this.statechart.current()).toEqual(['/B']);
        router._handleLocationChange('/c', '');
        router.flush();
        expect(this.statechart.current()).toEqual(['/C']);
      });
    });
  });

  describe('upon entering a state with a defined route', function() {
    it('updates the current location', function() {
      this.statechart.goto('/show', {context: {id: 9}});
      router.flush();
      expect(this.window.history.pushState).toHaveBeenCalledWith({}, null, '/foos/9');

      this.statechart.goto('/index');
      router.flush();
      expect(this.window.history.pushState).toHaveBeenCalledWith({}, null, '/foos');
    });
  });

  describe('upon state exit', function() {
    it("clears the route params from the router's params", function() {
      this.statechart.goto('/show', {context: {id: 3}});
      expect(router.params()).toEqual({id: 3});
      this.statechart.goto('/index');
      expect(router.params()).toEqual({});
    });
  });

  describe('#urlFor', function() {
    it('throws an error when given an invalid path', function() {
      var statechart = this.statechart;
      expect(function() {
        statechart.urlFor('/foo/bar');
      }).toThrow(new Error('RoutableState#urlFor: could not resolve path `/foo/bar`'));
    });

    it("throws an error when given a path to a state that doesn't have a define route", function() {
      var statechart = this.statechart;
      expect(function() {
        statechart.urlFor('/noroute');
      }).toThrow(new Error('RoutableState#urlFor: state `/noroute` does not have a route defined'));
    });

    it('returns a URL for the indicated state', function() {
      expect(this.statechart.urlFor('/index')).toBe('/foos');
      expect(this.statechart.urlFor('/show', {id: 4})).toBe('/foos/4');
    });
  });
});

}());
<commit_msg>Adds failing unit spec for bug where route still gets changed when a transition is prevented.<commit_after>(function() {

var RoutableState = require('../lib/routable_state'), router = require('../lib/router');

describe('RoutableState', function() {
  beforeEach(function() {
    this.statechart = RoutableState.define(function() {
      this.state('index', function() {
        this.route('/foos', {default: true});
      });

      this.state('show', function() {
        this.route('/foos/:id');
      });

      this.state('other', function() {
        this.route('/bars/:id');
      });

      this.state('noroute', function() {
      });
    });

    this.window = {
      addEventListener: function() {},
      removeEventListener: function() {},
      history: {
        replaceState: jasmine.createSpy('replaceState'),
        pushState: jasmine.createSpy('pushState')
      },
      location: {pathname: '/', search: ''}
    };

    this.statechart.start({window: this.window});
    router.flush();
  });

  afterEach(function() {
    router.reset();
  });

  describe('#route', function() {
    it('throws an exception when a route has already been defined on the state', function() {
      var state = this.statechart.resolve('/index');
      expect(function() {
        state.route('/abc');
      }).toThrow(new Error('RoutableState#route: a route has already been defined on ' + state));
    });

    it('throws an exception when given a state string that does not resolve', function() {
      expect(function() {
        RoutableState.define(function() {
          this.route('/foo/bar', './foo/bar');
        });
      }).toThrow(new Error('RoutableState#route: invalid state: ./foo/bar'));
    });

    it('registers the route with the router when the state is attached', function() {
      spyOn(router, 'define');
      RoutableState.define(function() {
        this.state('a', function() {
          this.route('/aaa');
        });
      });

      expect(router.define).toHaveBeenCalled();
      expect(router.define.calls.mostRecent().args[0]).toEqual('/aaa');
    });

    it('does not register the route with the router when the state is not attached', function() {
      spyOn(router, 'define');
      new RoutableState('foo', function() {
        this.route('/foo');
      });
      expect(router.define).not.toHaveBeenCalled();
    });
  });

  describe('RoutableState#didAttach', function() {
    it('registers the pending route with the router', function() {
      var s = RoutableState.define(), a;

      spyOn(router, 'define');

      a = new RoutableState('a', function() {
        this.route('/aaa');
      });

      expect(router.define).not.toHaveBeenCalled();
      s.state(a);
      expect(router.define).toHaveBeenCalled();
    });
  });

  describe('on popstate events', function() {
    it('triggers a transition to the state with the matching route', function() {
      router._handleLocationChange('/foos/1', '');
      router.flush();
      expect(this.statechart.current()).toEqual(['/show']);
      router._handleLocationChange('/foos', '');
      router.flush();
      expect(this.statechart.current()).toEqual(['/index']);
    });

    it('triggers a transition to the default route when the path is the root path', function() {
      router._handleLocationChange('/foos/1', '');
      router.flush();
      expect(this.statechart.current()).toEqual(['/show']);
      router._handleLocationChange('/', '');
      router.flush();
      expect(this.statechart.current()).toEqual(['/index']);
    });

    describe('with routes defined with a state string', function() {
      beforeEach(function() {
        this.statechart = RoutableState.define(function() {
          this.state('start');
          this.state('A');
          this.state('B');
          this.state('C');

          this.route('/a', './A');
          this.route('/b', './B');
          this.route('/c', './C');
        });

        this.statechart.goto('/start');
      });

      it('triggers a transition to the state with the matching route', function() {
        expect(this.statechart.current()).toEqual(['/start']);
        router._handleLocationChange('/a', '');
        router.flush();
        expect(this.statechart.current()).toEqual(['/A']);
        router._handleLocationChange('/b', '');
        router.flush();
        expect(this.statechart.current()).toEqual(['/B']);
        router._handleLocationChange('/c', '');
        router.flush();
        expect(this.statechart.current()).toEqual(['/C']);
      });
    });

    describe('with a route with a canExit handler that returns false', function() {
      beforeEach(function() {
        this.statechart = RoutableState.define(function() {
          this.state('A', function() {
            this.route('/a');
            this.canExit = function() { return false; };
          });

          this.state('B', function() {
            this.route('/b');
          });
        });

        this.statechart.goto('/A');
      });

      it('does not change the current state', function() {
        expect(this.statechart.current()).toEqual(['/A']);
        router._handleLocationChange('/b', '');
        router.flush();
        expect(this.statechart.current()).toEqual(['/A']);
      });

      it('does not change the current route', function() {
        expect(router.route().pattern).toEqual('/a');
        router._handleLocationChange('/b', '');
        router.flush();
        expect(router.route().pattern).toEqual('/a');
      });
    });
  });

  describe('upon entering a state with a defined route', function() {
    it('updates the current location', function() {
      this.statechart.goto('/show', {context: {id: 9}});
      router.flush();
      expect(this.window.history.pushState).toHaveBeenCalledWith({}, null, '/foos/9');

      this.statechart.goto('/index');
      router.flush();
      expect(this.window.history.pushState).toHaveBeenCalledWith({}, null, '/foos');
    });
  });

  describe('upon state exit', function() {
    it("clears the route params from the router's params", function() {
      this.statechart.goto('/show', {context: {id: 3}});
      expect(router.params()).toEqual({id: 3});
      this.statechart.goto('/index');
      expect(router.params()).toEqual({});
    });
  });

  describe('#urlFor', function() {
    it('throws an error when given an invalid path', function() {
      var statechart = this.statechart;
      expect(function() {
        statechart.urlFor('/foo/bar');
      }).toThrow(new Error('RoutableState#urlFor: could not resolve path `/foo/bar`'));
    });

    it("throws an error when given a path to a state that doesn't have a define route", function() {
      var statechart = this.statechart;
      expect(function() {
        statechart.urlFor('/noroute');
      }).toThrow(new Error('RoutableState#urlFor: state `/noroute` does not have a route defined'));
    });

    it('returns a URL for the indicated state', function() {
      expect(this.statechart.urlFor('/index')).toBe('/foos');
      expect(this.statechart.urlFor('/show', {id: 4})).toBe('/foos/4');
    });
  });
});

}());
<|endoftext|>