<commit_before>/* global ActiveXObject */

import http from './wrapper';

var RE_contentType = /([^\/]+)\/([^+]+\+)?([^;]*)/;
function parseContentType(contentType) {
  var matches = contentType && contentType.match(RE_contentType);
  return matches ? matches[3] : 'text';
}

function headerToCamelCase(text) {
  var key = text[0].toLowerCase() + text.substr(1);
  return key.replace(/([a-z])-([a-zA-Z])/g, function (match, lower, upper) {
    return lower + upper.toUpperCase();
  });
}

http.useRequest( (window.fetch ? function () {

  function getFetchResponse (response, config) {
    var headers = {},
        iterator = response.headers.entries(),
        entry = iterator.next();

    while( entry && !entry.done ) {
      headers[headerToCamelCase(entry.value[0])] = entry.value[1];
      entry = iterator.next();
    }

    var type = parseContentType(headers.contentType);

    return ( response[config.format || type] ? response[config.format || type]() : response.text() ).then(function (data) {
      return {
        config: config,
        status: response.status,
        statusText: response.statusText,
        data: data,
        headers: headers,
      };
    });
  }

  function fetchRequest (config, resolve, reject) {
    var options = { headers: new Headers(config.headers), redirect: 'follow', credentials: 'same-origin' };
    if( config.withCredentials ) options.credentials = 'include';
    if( config.credentials ) options.credentials = config.credentials;

    fetch(config.url, options).then(function (response) {
      getFetchResponse(response, config).then(resolve);
    }, function (response) {
      getFetchResponse(response, config).then(reject);
    });
  }

  return fetchRequest;

} : function () {

  var parseData = {
    json: function (data) {
      return JSON.parse(data);
    }
  };

  function _getXMLHeaders (request) {
    var headers = {};
    request.getAllResponseHeaders().split('\n').forEach(function (headerLine) {
      var matched = headerLine.match(/(.*?):(.*)/);
      if( matched ) {
        headers[headerToCamelCase(matched[1])] = matched[2].trim();
      }
    });

    return headers;
  }

  function xmlRequest (config, resolve, reject) {

    var request = null;

    try { // Firefox, Opera 8.0+, Safari
      request = new XMLHttpRequest();
    } catch (e) { // Internet Explorer
      try { request = new ActiveXObject('Msxml2.XMLHTTP'); }  // jshint ignore:line
      catch (er) { request = new ActiveXObject('Microsoft.XMLHTTP'); }  // jshint ignore:line
    }
    if( request === null ) { throw 'Browser does not support HTTP Request'; }

    if( config.withCredentials || config.credentials === 'include' ) request.withCredentials = true;

    request.onreadystatechange = function() {
      if( request.readyState === 'complete' || request.readyState === 4 ) {
        // var type = parseContentType( request.getResponseHeader('Content-Type') ),
        var headers = _getXMLHeaders(request),
            type = parseContentType( headers.contentType ),
            response = {
              config: config,
              status: request.status,
              statusText: request.statusText,
              headers: headers,
              data: type === 'xml' ? request.responseXML : (parseData[type] ? parseData[type](request.responseText) : request.responseText),
            };

        if( request.status >= 200 && request.status < 400 ) {
          resolve( response );
        } else {
          reject( response );
        }
      }
    };

    request.open(config.method, config.url, true);

    if( config.headers ) {
      for( var key in config.headers ) {
        request.setRequestHeader( key, config.headers[key] );
      }
    }

    request.send( config.body );
  }

  return xmlRequest;

})() );

export default http;
<commit_msg>better http.useRequest<commit_after>/* global ActiveXObject */

import http from './wrapper';

var RE_contentType = /([^\/]+)\/([^+]+\+)?([^;]*)/;
function parseContentType(contentType) {
  var matches = contentType && contentType.match(RE_contentType);
  return matches ? matches[3] : 'text';
}

function headerToCamelCase(text) {
  var key = text[0].toLowerCase() + text.substr(1);
  return key.replace(/([a-z])-([a-zA-Z])/g, function (match, lower, upper) {
    return lower + upper.toUpperCase();
  });
}

var useRequest = http.useRequest,
    requests = {
      fetch: function () {

        function getFetchResponse (response, config) {
          var headers = {},
              iterator = response.headers.entries(),
              entry = iterator.next();

          while( entry && !entry.done ) {
            headers[headerToCamelCase(entry.value[0])] = entry.value[1];
            entry = iterator.next();
          }

          var type = parseContentType(headers.contentType);

          return ( response[config.format || type] ? response[config.format || type]() : response.text() ).then(function (data) {
            return {
              config: config,
              status: response.status,
              statusText: response.statusText,
              data: data,
              headers: headers,
            };
          });
        }

        function fetchRequest (config, resolve, reject) {
          var options = { headers: new Headers(config.headers), redirect: 'follow', credentials: 'same-origin' };
          if( config.withCredentials ) options.credentials = 'include';
          if( config.credentials ) options.credentials = config.credentials;

          fetch(config.url, options).then(function (response) {
            getFetchResponse(response, config).then(resolve);
          }, function (response) {
            getFetchResponse(response, config).then(reject);
          });
        }

        return fetchRequest;

      },
      xml: function () {

        var parseData = {
          json: function (data) {
            return JSON.parse(data);
          }
        };

        function _getXMLHeaders (request) {
          var headers = {};
          request.getAllResponseHeaders().split('\n').forEach(function (headerLine) {
            var matched = headerLine.match(/(.*?):(.*)/);
            if( matched ) {
              headers[headerToCamelCase(matched[1])] = matched[2].trim();
            }
          });

          return headers;
        }

        function xmlRequest (config, resolve, reject) {

          var request = null;

          try { // Firefox, Opera 8.0+, Safari
            request = new XMLHttpRequest();
          } catch (e) { // Internet Explorer
            try { request = new ActiveXObject('Msxml2.XMLHTTP'); }  // jshint ignore:line
            catch (er) { request = new ActiveXObject('Microsoft.XMLHTTP'); }  // jshint ignore:line
          }
          if( request === null ) { throw 'Browser does not support HTTP Request'; }

          if( config.withCredentials || config.credentials === 'include' ) request.withCredentials = true;

          request.onreadystatechange = function() {
            if( request.readyState === 'complete' || request.readyState === 4 ) {
              // var type = parseContentType( request.getResponseHeader('Content-Type') ),
              var headers = _getXMLHeaders(request),
                  type = parseContentType( headers.contentType ),
                  response = {
                    config: config,
                    status: request.status,
                    statusText: request.statusText,
                    headers: headers,
                    data: type === 'xml' ? request.responseXML : (parseData[type] ? parseData[type](request.responseText) : request.responseText),
                  };

              if( request.status >= 200 && request.status < 400 ) {
                resolve( response );
              } else {
                reject( response );
              }
            }
          };

          request.open(config.method, config.url, true);

          if( config.headers ) {
            for( var key in config.headers ) {
              request.setRequestHeader( key, config.headers[key] );
            }
          }

          request.send( config.body );
        }

        return xmlRequest;
      }
    };

http.useRequest = function (request) {
  if( typeof request === 'string' ) {
    if( !requests[request] ) throw new Error('request type `' + request + '` missing');
    useRequest( requests[request]() );
  } else if( !Function.prototype.isPrototypeOf(request) ) throw new Error('request should be a function');
  else useRequest( request );
};

useRequest( (window.fetch ? requests.fetch : requests.xml)() );

export default http;
<|endoftext|>


<commit_before>// The scripts for the TSUGI runtime
// Needs to be loaded at the end after JQuery is loaded

// Send the CRF token on all of the non-ajax() calls
$.ajaxSetup({
    cache: false,
    headers : {
        'X-CSRF-Token' : CSRF_TOKEN
    }
});

function doHeartBeat() {
    window.console && console.log('Calling heartbeat to extend session');
    $.getJSON(HEARTBEAT_URL, function(data) {
        window.console && console.log(data);
        if ( data.lti || data.cookie ) {
            // No problem
        } else {
            clearInterval(HEARTBEAT_INTERVAL);
            HEARTBEAT_INTERVAL = false;
            alert('Your session has expired');
            window.location.href = "about:blank";
        }
    });
}

var DE_BOUNCE_LTI_FRAME_RESIZE_TIMER = false;
var DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT = false;

// Adapted from Lumen Learning / Bracken Mosbacker
// element_id is the id of the frame in the parent document
function lti_frameResize(new_height, element_id) {
    if ( self == top ) return;

    if ( !new_height ) {
        new_height = $(document).height() + 10;
    }
    if ( new_height < 100 ) new_height = 100;
    if ( new_height > 5000 ) new_height = 5000;

    if ( DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT ) {
        delta = new_height - DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT;
        if ( new_height == 5000 && DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT >= 5000 ) {
            console.log("maximum lti_frameResize 5000 exceeded");
            return;
        } else if ( new_height > (DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT + 10) ) {
            // Do the resize for small increases
        } else if ( new_height < (DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT - 30) ) {
            // Do the resize for large decreases
        } else {
            console.log("lti_frameResize delta "+delta+" is too small, ignored");
            return;
        }
    }

    if ( DE_BOUNCE_LTI_FRAME_RESIZE_TIMER ) {
        clearTimeout(DE_BOUNCE_LTI_FRAME_RESIZE_TIMER);
        DE_BOUNCE_LTI_FRAME_RESIZE_TIMER = false;
    }

    DE_BOUNCE_LTI_FRAME_RESIZE_TIMER = setTimeout(
        function () { lti_frameResizeNow(new_height, element_id); },
        1000
    );
}

function lti_frameResizeNow(new_height, element_id) {
    parms = {
      subject: "lti.frameResize",
      height: new_height
    }
    if ( element_id ) {
        parms.element_id = element_id;
    }
    var parm_str = JSON.stringify(parms);

    console.log("sending "+parm_str);
    parent.postMessage(parm_str, "*");

    DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT = new_height;
}

function lti_hideLMSNavigation() {
    parent.postMessage(JSON.stringify({
      subject: "lti.hideModuleNavigation",
      show: false
    }), "*");
}

function lti_showLMSNavigation() {
    parent.postMessage(JSON.stringify({
      subject: "lti.showModuleNavigation",
      show: true
    }), "*");
}

// tell the parent iframe to scroll to top
function lti_scrollParentToTop() {
    parent.postMessage(JSON.stringify({
      subject: "lti.scrollToTop"
    }), "*");
}

// Straight Outta Github (with adaptations)
// https://github.com/lumenlearning/candela/blob/master/wp-content/plugins/candela-utility/themes/bombadil/js/iframe_resizer.js
/**
 * Listen for a window post message to resize an embedded iframe
 * Needs to be an json stringified object that identifies the id of
 * the element to resize like this:
   parent.postMessage(JSON.stringify({
      subject: "lti.frameResize",
      height: default_height,
      element_id: "lumen_assessment_1"
  }), "*");
 * The element_id needed is passed as a query parameter `iframe_resize_id`
 */

// Unlike candela, we always do this - even if we are in an iframe - Inception
// console.log(window.location.href + "setting up listener");
window.addEventListener('message', function (e) {
    // console.log(window.location.href + " got message");
    // console.log(e.data);
    try {
        var message = JSON.parse(e.data);
        switch (message.subject) {
            case 'lti.frameResize':
                var height = message.height;
                if (height >= 5000) height = 5000;
                if (height <= 0) height = 1;
                if ( message.element_id ) {
                    var $iframe = jQuery('#' + message.element_id);
                    $iframe.css('height', height + 'px');
                    console.log("window.location.href set "+message.element_id+" height="+height);
                } else { // Must loop through all of them - best if there is one
                    $('.lti_frameResize').each(function(i, obj) {
                        $(this).css('height', height + 'px');
                        console.log("window.location.href set height="+height);
                    });
                }
                break;
        }
    } catch (err) {
        console.log('invalid message received from ', e.origin);
        console.log(e.data);
        console.log('Exception: '+err)
    }
});

// If we are not the top frame - immediately communicate our size and jack into the JQuery resize
// Debounce happens in lti_frameResize()
if ( ! (self == top) ) {
    if ( typeof LTI_PARENT_IFRAME_ID === 'undefined' ) {
        lti_frameResize();
        $(window).on('resize', function() { lti_frameResize(); });
    } else {
        lti_frameResize(false, LTI_PARENT_IFRAME_ID);
        $(window).on('resize', function() { lti_frameResize(false, LTI_PARENT_IFRAME_ID); });
    }
}

// From Sakai
// Return the breakpoint between small and medium sized displays - for morpheus currently the same
function portalSmallBreakPoint() { return 800; }
function portalMediumBreakPoint() { return 800; }

// Return the correct width for a modal dialog.
function modalDialogWidth() {
    var wWidth = $(window).width();
    var pbr = portalSmallBreakPoint();
    var dWidth = wWidth * 0.8;
    if ( wWidth <= pbr ) {
        dWidth = pbr * 0.8;
        if ( dWidth > (wWidth * 0.95) ) {
            dWidth = wWidth * 0.95;
        }
    }
    if ( dWidth < 300 ) dWidth = 300; // Should not happen
    return Math.round(dWidth);
}

// If the enclosing modal is content from the background document
function showModal(title, modalId) {
    console.log("showModal "+modalId);
    $("#"+modalId).dialog({
        title: title,
        width: modalDialogWidth(),
        position: { my: "center top+30px", at: "center top+30px", of: window },
        modal: true,
        draggable: false
    });

    // In order to float above the BootStrap navigation
    $('.ui-dialog').css('z-index',9999);

    $(window).resize(function() {
        $("#"+modalId).dialog("option", "width", modalDialogWidth());
    });
}

// If the enclosing modal contains an iframe
function showModalIframe(title, modalId, iframeId, spinnerUrl, refreshParentOnClose) {
    console.log("showModalIframe "+modalId);
    $("#"+modalId).css('zIndex',9999);
    $("#"+modalId).dialog({
        title: title,
        width: modalDialogWidth(),
        position: { my: "center top+30px", at: "center top+30px", of: window },
        modal: true,
        draggable: false,
        open: function() {
            $('#'+iframeId).width('95%');
        },
        close: function() {
            if ( spinnerUrl ) {
                $('#'+iframeId).attr('src',spinnerUrl);
            }
            if ( refreshParentOnClose ) {
                location.reload();
            }
        }
    });

    // In order to float above the BootStrap navigation
    $('.ui-dialog').css('z-index',9999);

    $(window).resize(function() {
        $("#"+modalId).dialog("option", "width", modalDialogWidth());
        $('#'+iframeId).width('95%');
    });
}

/* Light YouTube Embeds by @labnol */
/* Web: http://labnol.org/?p=27941 */

$(document).ready(
// document.addEventListener("DOMContentLoaded",
    function() {
        var div, n,
            v = document.getElementsByClassName("youtube-player");
        for (n = 0; n < v.length; n++) {
            div = document.createElement("div");
            div.setAttribute("data-id", v[n].dataset.id);
            div.innerHTML = labnolThumb(v[n].dataset.id);
            div.onclick = labnolIframe;
            v[n].appendChild(div);
        }
    }
);

function labnolThumb(id) {
    var thumb = '',
        play = '

';
    return thumb.replace("ID", id) + play;
}

function labnolIframe() {
    // Reset any currently active players...
    var v = document.getElementsByClassName("generated-youtube-frame");
    for (n = 0; n < v.length; n++) {
        div = document.createElement("div");
        div.setAttribute("data-id", v[n].dataset.id);
        div.innerHTML = labnolThumb(v[n].dataset.id);
        div.onclick = labnolIframe;
        v[n].parentNode.replaceChild(div, v[n]);
    }

    var iframe = document.createElement("iframe");
    var embed = "https://www.youtube.com/embed/ID?autoplay=1";
    iframe.setAttribute("src", embed.replace("ID", this.dataset.id));
    iframe.setAttribute("frameborder", "0");
    iframe.setAttribute("class", "generated-youtube-frame");
    iframe.setAttribute("data-id", this.dataset.id);
    iframe.setAttribute("allowfullscreen", "1");
    iframe.setAttribute("webkitAllowFullScreen", "1");
    iframe.setAttribute("mozallowfullscreen", "1");
    this.parentNode.replaceChild(iframe, this);
}

var TSUGI_TEMPLATES = {};

function tsugiHandlebarsRender(name, context) {

    if ( ! (name in TSUGI_TEMPLATES ) ) {
        window.console && console.log("Compiling "+name);
        var source  = $("#template-"+name).html();
        var compile = Handlebars.compile(source);
        TSUGI_TEMPLATES[name] = compile;
    }
    window.console && console.log("Rendering "+name);
    var template = TSUGI_TEMPLATES[name];
    return template(context);
}

function tsugiHandlebarsToDiv(div, name, context) {
    $('#'+div).empty().append(tsugiHandlebarsRender(name, context));
}

// Straight outta W3Schools
// https://www.w3schools.com/js/js_cookies.asp
function tsugiSetCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

// Setup the menu
function tsugiEmbedMenu() {
    $('#tsugi-embed-menu').delay(1000).fadeIn(1000);
    $TSUGI_EMBED_TIMEOUT = setTimeout(function(){
        $('#tsugi-embed-menu').fadeOut(1000);
    }
    , 15000);
}

<commit_msg>One more function<commit_after>// The scripts for the TSUGI runtime
// Needs to be loaded at the end after JQuery is loaded

// Send the CRF token on all of the non-ajax() calls
$.ajaxSetup({
    cache: false,
    headers : {
        'X-CSRF-Token' : CSRF_TOKEN
    }
});

function doHeartBeat() {
    window.console && console.log('Calling heartbeat to extend session');
    $.getJSON(HEARTBEAT_URL, function(data) {
        window.console && console.log(data);
        if ( data.lti || data.cookie ) {
            // No problem
        } else {
            clearInterval(HEARTBEAT_INTERVAL);
            HEARTBEAT_INTERVAL = false;
            alert('Your session has expired');
            window.location.href = "about:blank";
        }
    });
}

var DE_BOUNCE_LTI_FRAME_RESIZE_TIMER = false;
var DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT = false;

// Adapted from Lumen Learning / Bracken Mosbacker
// element_id is the id of the frame in the parent document
function lti_frameResize(new_height, element_id) {
    if ( self == top ) return;

    if ( !new_height ) {
        new_height = $(document).height() + 10;
    }
    if ( new_height < 100 ) new_height = 100;
    if ( new_height > 5000 ) new_height = 5000;

    if ( DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT ) {
        delta = new_height - DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT;
        if ( new_height == 5000 && DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT >= 5000 ) {
            console.log("maximum lti_frameResize 5000 exceeded");
            return;
        } else if ( new_height > (DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT + 10) ) {
            // Do the resize for small increases
        } else if ( new_height < (DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT - 30) ) {
            // Do the resize for large decreases
        } else {
            console.log("lti_frameResize delta "+delta+" is too small, ignored");
            return;
        }
    }

    if ( DE_BOUNCE_LTI_FRAME_RESIZE_TIMER ) {
        clearTimeout(DE_BOUNCE_LTI_FRAME_RESIZE_TIMER);
        DE_BOUNCE_LTI_FRAME_RESIZE_TIMER = false;
    }

    DE_BOUNCE_LTI_FRAME_RESIZE_TIMER = setTimeout(
        function () { lti_frameResizeNow(new_height, element_id); },
        1000
    );
}

function lti_frameResizeNow(new_height, element_id) {
    parms = {
      subject: "lti.frameResize",
      height: new_height
    }
    if ( element_id ) {
        parms.element_id = element_id;
    }
    var parm_str = JSON.stringify(parms);

    console.log("sending "+parm_str);
    parent.postMessage(parm_str, "*");

    DE_BOUNCE_LTI_FRAME_RESIZE_HEIGHT = new_height;
}

function lti_hideLMSNavigation() {
    parent.postMessage(JSON.stringify({
      subject: "lti.hideModuleNavigation",
      show: false
    }), "*");
}

function lti_showLMSNavigation() {
    parent.postMessage(JSON.stringify({
      subject: "lti.showModuleNavigation",
      show: true
    }), "*");
}

// tell the parent iframe to scroll to top
function lti_scrollParentToTop() {
    parent.postMessage(JSON.stringify({
      subject: "lti.scrollToTop"
    }), "*");
}

// Straight Outta Github (with adaptations)
// https://github.com/lumenlearning/candela/blob/master/wp-content/plugins/candela-utility/themes/bombadil/js/iframe_resizer.js
/**
 * Listen for a window post message to resize an embedded iframe
 * Needs to be an json stringified object that identifies the id of
 * the element to resize like this:
   parent.postMessage(JSON.stringify({
      subject: "lti.frameResize",
      height: default_height,
      element_id: "lumen_assessment_1"
  }), "*");
 * The element_id needed is passed as a query parameter `iframe_resize_id`
 */

// Unlike candela, we always do this - even if we are in an iframe - Inception
// console.log(window.location.href + "setting up listener");
window.addEventListener('message', function (e) {
    // console.log(window.location.href + " got message");
    // console.log(e.data);
    try {
        var message = JSON.parse(e.data);
        switch (message.subject) {
            case 'lti.frameResize':
                var height = message.height;
                if (height >= 5000) height = 5000;
                if (height <= 0) height = 1;
                if ( message.element_id ) {
                    var $iframe = jQuery('#' + message.element_id);
                    $iframe.css('height', height + 'px');
                    console.log("window.location.href set "+message.element_id+" height="+height);
                } else { // Must loop through all of them - best if there is one
                    $('.lti_frameResize').each(function(i, obj) {
                        $(this).css('height', height + 'px');
                        console.log("window.location.href set height="+height);
                    });
                }
                break;
        }
    } catch (err) {
        console.log('invalid message received from ', e.origin);
        console.log(e.data);
        console.log('Exception: '+err)
    }
});

// If we are not the top frame - immediately communicate our size and jack into the JQuery resize
// Debounce happens in lti_frameResize()
if ( ! (self == top) ) {
    if ( typeof LTI_PARENT_IFRAME_ID === 'undefined' ) {
        lti_frameResize();
        $(window).on('resize', function() { lti_frameResize(); });
    } else {
        lti_frameResize(false, LTI_PARENT_IFRAME_ID);
        $(window).on('resize', function() { lti_frameResize(false, LTI_PARENT_IFRAME_ID); });
    }
}

// From Sakai
// Return the breakpoint between small and medium sized displays - for morpheus currently the same
function portalSmallBreakPoint() { return 800; }
function portalMediumBreakPoint() { return 800; }

// Return the correct width for a modal dialog.
function modalDialogWidth() {
    var wWidth = $(window).width();
    var pbr = portalSmallBreakPoint();
    var dWidth = wWidth * 0.8;
    if ( wWidth <= pbr ) {
        dWidth = pbr * 0.8;
        if ( dWidth > (wWidth * 0.95) ) {
            dWidth = wWidth * 0.95;
        }
    }
    if ( dWidth < 300 ) dWidth = 300; // Should not happen
    return Math.round(dWidth);
}

// If the enclosing modal is content from the background document
function showModal(title, modalId) {
    console.log("showModal "+modalId);
    $("#"+modalId).dialog({
        title: title,
        width: modalDialogWidth(),
        position: { my: "center top+30px", at: "center top+30px", of: window },
        modal: true,
        draggable: false
    });

    // In order to float above the BootStrap navigation
    $('.ui-dialog').css('z-index',9999);

    $(window).resize(function() {
        $("#"+modalId).dialog("option", "width", modalDialogWidth());
    });
}

// If the enclosing modal contains an iframe
function showModalIframe(title, modalId, iframeId, spinnerUrl, refreshParentOnClose) {
    console.log("showModalIframe "+modalId);
    $("#"+modalId).css('zIndex',9999);
    $("#"+modalId).dialog({
        title: title,
        width: modalDialogWidth(),
        position: { my: "center top+30px", at: "center top+30px", of: window },
        modal: true,
        draggable: false,
        open: function() {
            $('#'+iframeId).width('95%');
        },
        close: function() {
            if ( spinnerUrl ) {
                $('#'+iframeId).attr('src',spinnerUrl);
            }
            if ( refreshParentOnClose ) {
                location.reload();
            }
        }
    });

    // In order to float above the BootStrap navigation
    $('.ui-dialog').css('z-index',9999);

    $(window).resize(function() {
        $("#"+modalId).dialog("option", "width", modalDialogWidth());
        $('#'+iframeId).width('95%');
    });
}

/* Light YouTube Embeds by @labnol */
/* Web: http://labnol.org/?p=27941 */

$(document).ready(
// document.addEventListener("DOMContentLoaded",
    function() {
        var div, n,
            v = document.getElementsByClassName("youtube-player");
        for (n = 0; n < v.length; n++) {
            div = document.createElement("div");
            div.setAttribute("data-id", v[n].dataset.id);
            div.innerHTML = labnolThumb(v[n].dataset.id);
            div.onclick = labnolIframe;
            v[n].appendChild(div);
        }
    }
);

function labnolThumb(id) {
    var thumb = '',
        play = '

';
    return thumb.replace("ID", id) + play;
}

function labnolIframe() {
    // Reset any currently active players...
    var v = document.getElementsByClassName("generated-youtube-frame");
    for (n = 0; n < v.length; n++) {
        div = document.createElement("div");
        div.setAttribute("data-id", v[n].dataset.id);
        div.innerHTML = labnolThumb(v[n].dataset.id);
        div.onclick = labnolIframe;
        v[n].parentNode.replaceChild(div, v[n]);
    }

    var iframe = document.createElement("iframe");
    var embed = "https://www.youtube.com/embed/ID?autoplay=1";
    iframe.setAttribute("src", embed.replace("ID", this.dataset.id));
    iframe.setAttribute("frameborder", "0");
    iframe.setAttribute("class", "generated-youtube-frame");
    iframe.setAttribute("data-id", this.dataset.id);
    iframe.setAttribute("allowfullscreen", "1");
    iframe.setAttribute("webkitAllowFullScreen", "1");
    iframe.setAttribute("mozallowfullscreen", "1");
    this.parentNode.replaceChild(iframe, this);
}

var TSUGI_TEMPLATES = {};

function tsugiHandlebarsRender(name, context) {

    if ( ! (name in TSUGI_TEMPLATES ) ) {
        window.console && console.log("Compiling "+name);
        var source  = $("#template-"+name).html();
        var compile = Handlebars.compile(source);
        TSUGI_TEMPLATES[name] = compile;
    }
    window.console && console.log("Rendering "+name);
    var template = TSUGI_TEMPLATES[name];
    return template(context);
}

function tsugiHandlebarsToDiv(div, name, context) {
    $('#'+div).empty().append(tsugiHandlebarsRender(name, context));
}

// Straight outta W3Schools
// https://www.w3schools.com/js/js_cookies.asp
function tsugiSetCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

$TSUGI_EMBED_TIMEOUT = false;
// Setup the menu
function tsugiEmbedMenu() {
    $('#tsugi-embed-menu').delay(1000).fadeIn(1000);
    $TSUGI_EMBED_TIMEOUT = setTimeout(function(){
        $('#tsugi-embed-menu').fadeOut(1000);
        $TSUGI_EMBED_TIMEOUT = false;
    }
    , 15000);
}

function tsugiEmbedKeep() {
    if ( $TSUGI_EMBED_TIMEOUT ) clearTimeout($TSUGI_EMBED_TIMEOUT);
    $TSUGI_EMBED_TIMEOUT = false;
}

<|endoftext|>


<commit_before>var chai = require('chai');
var Future = require('../lib/future');
var spies = require('chai-spies');

chai.use(spies);
var expect = chai.expect;

var future;

var SUCCESS = 'success';
var ERROR = 'error';

var LEFT = 'left';
var RIGHT = 'right';

var ZERO = 0;
var ONE = 1;

describe('Future API', function() {
  beforeEach(function() {
    future = new Future();
  });

  describe('#isCompleted', function() {
    it('should have isCompleted', function() {
      expect(future).to.have.property('isCompleted');
    });

    it('should work as expected', function() {
      expect(future.isCompleted()).to.be.false;
      future.fulfill(SUCCESS);
      expect(future.isCompleted()).to.be.true;
    });
  })

  describe('#onComplete', function() {
    it('should have onComplete', function() {
      expect(future).to.have.property('onComplete');
    });

    it('should call on success', function(done) {
      future.onComplete(function(value) {
        expect(value).to.eql(SUCCESS);
        done();
      });
      future.fulfill(SUCCESS);
    });

    it('should call on error', function(done) {
      future.onComplete(function(value) {
        expect(value).to.eql(ERROR);
        done();
      });
      future.reject(ERROR);
    });
  });

  describe('#ready', function() {
    it('should have ready', function() {
      expect(future).to.have.property('ready');
    });

    it('should be called with value if it succeeds on time', function(done) {
      var readied = future.ready(1000);

      readied.then(function(value) {
        expect(value).to.eql(SUCCESS);
        done();
      });

      future.fulfill(SUCCESS);
    });

    it('should be called with error if it does not succeed', function(done) {
      var readied = future.ready(10);
      var spy = chai.spy(function() {});

      readied.then(null, spy);
      readied.then(null, function() {
        expect(spy).to.have.been.called;
        done();
      });
    });
  });

  describe('#value', function() {
    it('should not have value before being fulfilled', function() {
      expect(future).to.not.have.property('value');
    });

    it('should have value', function() {
      future.fulfill(SUCCESS);
      expect(future).to.have.property('value');
    });
  });

  it('should have failed', function() {
    expect(future).to.have.property('failed');
  });

  describe('#fallbackTo', function() {
    it('should have fallbackTo', function() {
      expect(future).to.have.property('fallbackTo');
    });

    it('should return the value of left if left succeeds', function(done) {
      var other = new Future();
      var fallen = future.fallbackTo(other);

      fallen.then(function(value) {
        expect(value).to.eql(LEFT);
        done();
      });

      future.fulfill(LEFT);
      other.reject(ERROR);
    });

    it('should return the value of left if left succeeds even if right succeeds', function(done) {
      var other = new Future();
      var fallen = future.fallbackTo(other);

      fallen.then(function(value) {
        expect(value).to.eql(LEFT);
        done();
      });

      future.fulfill(LEFT);
      other.fulfill(RIGHT);
    });

    it('should return the value of right if left fails', function(done) {
      var other = new Future();
      var fallen = future.fallbackTo(other);

      fallen.then(function(value) {
        expect(value).to.eql(RIGHT);
        done();
      });

      future.reject(ERROR);
      other.fulfill(RIGHT);
    });

    it('should not be called if both fail', function(done) {
      var other = new Future();
      var fallen = future.fallbackTo(other);
      var spy = chai.spy(function() {});

      fallen.then(spy);

      future.then(null, function() {
        expect(spy).to.have.been.not_called;
        done();
      });

      future.reject(ERROR);
      other.reject(ERROR);
    });
  });

  describe('#filter', function() {
    it('should have filter', function() {
      expect(future).to.have.property('filter');
    });

    it('should be called if the predicate is true', function(done) {
      var filtered = future.filter(function(value) {
        return value === SUCCESS;
      });

      filtered.then(function(value) {
        expect(value).to.eql(SUCCESS);
        done();
      });

      future.fulfill(SUCCESS);
    });

    it('should be rejected if the value is not true', function(done) {
      var filtered = future.filter(function(value) {
        return value !== SUCCESS;
      });
      var spy = chai.spy(function() {});

      filtered.then(null, spy);
      filtered.then(null, function() {
        expect(spy).to.have.been.called;
        done();
      });

      future.fulfill(SUCCESS);
    });

    it('should be rejected if the parent future is', function(done) {
      var filtered = future.filter(function(value) {
        return value === SUCCESS;
      });

      filtered.then(null, function(reason) {
        expect(reason).to.eql(ERROR);
        done();
      });

      future.reject(ERROR);
    });
  });

  describe('#map', function() {
    it('should have map', function() {
      expect(future).to.have.property('map');
    });

    it('should work on success', function(done) {
      var mapped = future.map(function(value) {
        return value + 1;
      });

      mapped.then(function(value) {
        expect(value).to.eql(ONE);
        done();
      });

      future.fulfill(ZERO);
    });

    it('should not be called on error', function(done) {
      var spy = chai.spy(function() {});
      var mapped = future.map(spy);

      future.then(null, function() {
        expect(spy).to.have.been.not_called;
        done();
      });

      future.reject(ERROR);
    });
  });

  describe('#onFailure', function() {
    it('should have onFailure', function() {
      expect(future).to.have.property('onFailure');
    });

    it('should be called on reject', function(done) {
      future.onFailure(function(reason) {
        expect(reason).to.eql(ERROR);
        done();
      });

      future.reject(ERROR);
    });

    it('should not be called on success', function(done) {
      var spy = chai.spy(function() {});

      future.onFailure(spy);

      future.then(function() {
        expect(spy).to.have.been.not_called;
        done();
      });

      future.fulfill(SUCCESS);
    });
  });

  describe('#onSuccess', function() {
    it('should have onSuccess', function() {
      expect(future).to.have.property('onSuccess');
    });

    it('should be called on success', function(done) {
      future.onSuccess(function(value) {
        expect(value).to.eql(SUCCESS);
        done();
      });

      future.fulfill(SUCCESS);
    });

    it('should not be called on error', function(done) {
      var spy = chai.spy(function() {});

      future.onSuccess(spy);

      future.then(null, function() {
        expect(spy).to.have.been.not_called;
        done();
      });

      future.reject(ERROR);
    });
  });

  it('should have recover', function() {
    expect(future).to.have.property('recover');
  });

  it('should have recoverWith', function() {
    expect(future).to.have.property('recoverWith');
  });

  describe('#transform', function() {
    it('should have transform', function() {
      expect(future).to.have.property('transform');
    });

    it('should be called on success', function(done) {
      var spy = chai.spy(function() {});

      var transformed = future.then(function(value) {
        expect(value).to.eql(SUCCESS);
        expect(spy).to.have.been.not_called;
        done();
      }, spy);

      future.fulfill(SUCCESS);
    });

    it('should be called on failure', function(done) {
      var spy = chai.spy(function() {});

      var transformed = future.then(spy, function(reason) {
        expect(reason).to.eql(ERROR);
        expect(spy).to.have.been.not_called;
        done();
      });

      future.reject(ERROR);
    });
  });

  describe('#zip', function() {
    it('should have zip', function() {
      expect(future).to.have.property('zip');
    });

    it('should combine two futures into a tuple', function(done) {
      var other = new Future();
      var zipped = future.zip(other);

      zipped.then(function(tuple) {
        expect(tuple).to.eql([LEFT, RIGHT]);
        done();
      });

      future.fulfill(LEFT);
      other.fulfill(RIGHT);
    });

    it('should not be called if the left future fails', function(done) {
      var other = new Future();
      var zipped = future.zip(other);
      var spy = chai.spy(function() {});

      zipped.then(spy);

      future.then(null, function() {
        expect(spy).to.have.been.not_called;
        done();
      });

      future.reject(ERROR);
      other.fulfill(SUCCESS);
    });

    it('should not be called if the right future fails', function(done) {
      var other = new Future();
      var zipped = future.zip(other);
      var spy = chai.spy(function() {});

      zipped.then(spy);

      other.then(null, function() {
        expect(spy).to.have.been.not_called;
        done();
      });

      future.fulfill(SUCCESS);
      other.reject(ERROR);
    });
  });
});<commit_msg>Removing #recoverWith<commit_after>var chai = require('chai');
var Future = require('../lib/future');
var spies = require('chai-spies');

chai.use(spies);
var expect = chai.expect;

var future;

var SUCCESS = 'success';
var ERROR = 'error';

var LEFT = 'left';
var RIGHT = 'right';

var ZERO = 0;
var ONE = 1;

describe('Future API', function() {
  beforeEach(function() {
    future = new Future();
  });

  describe('#isCompleted', function() {
    it('should have isCompleted', function() {
      expect(future).to.have.property('isCompleted');
    });

    it('should work as expected', function() {
      expect(future.isCompleted()).to.be.false;
      future.fulfill(SUCCESS);
      expect(future.isCompleted()).to.be.true;
    });
  })

  describe('#onComplete', function() {
    it('should have onComplete', function() {
      expect(future).to.have.property('onComplete');
    });

    it('should call on success', function(done) {
      future.onComplete(function(value) {
        expect(value).to.eql(SUCCESS);
        done();
      });
      future.fulfill(SUCCESS);
    });

    it('should call on error', function(done) {
      future.onComplete(function(value) {
        expect(value).to.eql(ERROR);
        done();
      });
      future.reject(ERROR);
    });
  });

  describe('#ready', function() {
    it('should have ready', function() {
      expect(future).to.have.property('ready');
    });

    it('should be called with value if it succeeds on time', function(done) {
      var readied = future.ready(1000);

      readied.then(function(value) {
        expect(value).to.eql(SUCCESS);
        done();
      });

      future.fulfill(SUCCESS);
    });

    it('should be called with error if it does not succeed', function(done) {
      var readied = future.ready(10);
      var spy = chai.spy(function() {});

      readied.then(null, spy);
      readied.then(null, function() {
        expect(spy).to.have.been.called;
        done();
      });
    });
  });

  describe('#value', function() {
    it('should not have value before being fulfilled', function() {
      expect(future).to.not.have.property('value');
    });

    it('should have value', function() {
      future.fulfill(SUCCESS);
      expect(future).to.have.property('value');
    });
  });

  it('should have failed', function() {
    expect(future).to.have.property('failed');
  });

  describe('#fallbackTo', function() {
    it('should have fallbackTo', function() {
      expect(future).to.have.property('fallbackTo');
    });

    it('should return the value of left if left succeeds', function(done) {
      var other = new Future();
      var fallen = future.fallbackTo(other);

      fallen.then(function(value) {
        expect(value).to.eql(LEFT);
        done();
      });

      future.fulfill(LEFT);
      other.reject(ERROR);
    });

    it('should return the value of left if left succeeds even if right succeeds', function(done) {
      var other = new Future();
      var fallen = future.fallbackTo(other);

      fallen.then(function(value) {
        expect(value).to.eql(LEFT);
        done();
      });

      future.fulfill(LEFT);
      other.fulfill(RIGHT);
    });

    it('should return the value of right if left fails', function(done) {
      var other = new Future();
      var fallen = future.fallbackTo(other);

      fallen.then(function(value) {
        expect(value).to.eql(RIGHT);
        done();
      });

      future.reject(ERROR);
      other.fulfill(RIGHT);
    });

    it('should not be called if both fail', function(done) {
      var other = new Future();
      var fallen = future.fallbackTo(other);
      var spy = chai.spy(function() {});

      fallen.then(spy);

      future.then(null, function() {
        expect(spy).to.have.been.not_called;
        done();
      });

      future.reject(ERROR);
      other.reject(ERROR);
    });
  });

  describe('#filter', function() {
    it('should have filter', function() {
      expect(future).to.have.property('filter');
    });

    it('should be called if the predicate is true', function(done) {
      var filtered = future.filter(function(value) {
        return value === SUCCESS;
      });

      filtered.then(function(value) {
        expect(value).to.eql(SUCCESS);
        done();
      });

      future.fulfill(SUCCESS);
    });

    it('should be rejected if the value is not true', function(done) {
      var filtered = future.filter(function(value) {
        return value !== SUCCESS;
      });
      var spy = chai.spy(function() {});

      filtered.then(null, spy);
      filtered.then(null, function() {
        expect(spy).to.have.been.called;
        done();
      });

      future.fulfill(SUCCESS);
    });

    it('should be rejected if the parent future is', function(done) {
      var filtered = future.filter(function(value) {
        return value === SUCCESS;
      });

      filtered.then(null, function(reason) {
        expect(reason).to.eql(ERROR);
        done();
      });

      future.reject(ERROR);
    });
  });

  describe('#map', function() {
    it('should have map', function() {
      expect(future).to.have.property('map');
    });

    it('should work on success', function(done) {
      var mapped = future.map(function(value) {
        return value + 1;
      });

      mapped.then(function(value) {
        expect(value).to.eql(ONE);
        done();
      });

      future.fulfill(ZERO);
    });

    it('should not be called on error', function(done) {
      var spy = chai.spy(function() {});
      var mapped = future.map(spy);

      future.then(null, function() {
        expect(spy).to.have.been.not_called;
        done();
      });

      future.reject(ERROR);
    });
  });

  describe('#onFailure', function() {
    it('should have onFailure', function() {
      expect(future).to.have.property('onFailure');
    });

    it('should be called on reject', function(done) {
      future.onFailure(function(reason) {
        expect(reason).to.eql(ERROR);
        done();
      });

      future.reject(ERROR);
    });

    it('should not be called on success', function(done) {
      var spy = chai.spy(function() {});

      future.onFailure(spy);

      future.then(function() {
        expect(spy).to.have.been.not_called;
        done();
      });

      future.fulfill(SUCCESS);
    });
  });

  describe('#onSuccess', function() {
    it('should have onSuccess', function() {
      expect(future).to.have.property('onSuccess');
    });

    it('should be called on success', function(done) {
      future.onSuccess(function(value) {
        expect(value).to.eql(SUCCESS);
        done();
      });

      future.fulfill(SUCCESS);
    });

    it('should not be called on error', function(done) {
      var spy = chai.spy(function() {});

      future.onSuccess(spy);

      future.then(null, function() {
        expect(spy).to.have.been.not_called;
        done();
      });

      future.reject(ERROR);
    });
  });

  it('should have recover', function() {
    expect(future).to.have.property('recover');
  });

  describe('#transform', function() {
    it('should have transform', function() {
      expect(future).to.have.property('transform');
    });

    it('should be called on success', function(done) {
      var spy = chai.spy(function() {});

      var transformed = future.then(function(value) {
        expect(value).to.eql(SUCCESS);
        expect(spy).to.have.been.not_called;
        done();
      }, spy);

      future.fulfill(SUCCESS);
    });

    it('should be called on failure', function(done) {
      var spy = chai.spy(function() {});

      var transformed = future.then(spy, function(reason) {
        expect(reason).to.eql(ERROR);
        expect(spy).to.have.been.not_called;
        done();
      });

      future.reject(ERROR);
    });
  });

  describe('#zip', function() {
    it('should have zip', function() {
      expect(future).to.have.property('zip');
    });

    it('should combine two futures into a tuple', function(done) {
      var other = new Future();
      var zipped = future.zip(other);

      zipped.then(function(tuple) {
        expect(tuple).to.eql([LEFT, RIGHT]);
        done();
      });

      future.fulfill(LEFT);
      other.fulfill(RIGHT);
    });

    it('should not be called if the left future fails', function(done) {
      var other = new Future();
      var zipped = future.zip(other);
      var spy = chai.spy(function() {});

      zipped.then(spy);

      future.then(null, function() {
        expect(spy).to.have.been.not_called;
        done();
      });

      future.reject(ERROR);
      other.fulfill(SUCCESS);
    });

    it('should not be called if the right future fails', function(done) {
      var other = new Future();
      var zipped = future.zip(other);
      var spy = chai.spy(function() {});

      zipped.then(spy);

      other.then(null, function() {
        expect(spy).to.have.been.not_called;
        done();
      });

      future.fulfill(SUCCESS);
      other.reject(ERROR);
    });
  });
});<|endoftext|>


<commit_before>/**
 * HTTP Headers.
 */

import { each, trim, toLower } from '../util';

export default class Headers {

    constructor(headers) {

        this.map = {};

        each(headers, (value, name) => this.append(name, value));
    }

    has(name) {
        return getName(this.map, name) !== null;
    }

    get(name) {

        var list = this.map[getName(this.map, name)];

        return list ? list[0] : null;
    }

    getAll(name) {
        return this.map[getName(this.map, name)] || [];
    }

    set(name, value) {
        this.map[normalizeName(getName(this.map, name) || name)] = [trim(value)];
    }

    append(name, value){

        var list = this.getAll(name);

        if (list.length) {
            list.push(trim(value));
        } else {
            this.set(name, value);
        }
    }

    delete(name){
        delete this.map[getName(this.map, name)];
    }

    deleteAll(){
        this.map = {};
    }

    forEach(callback, thisArg) {
        each(this.map, (list, name) => {
            each(list, value => callback.call(thisArg, value, name, this));
        });
    }

}

function getName(map, name) {
    return Object.keys(map).reduce((prev, curr) => {
        return toLower(name) === toLower(curr) ? curr : prev;
    }, null);
}

function normalizeName(name) {

    if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
        throw new TypeError('Invalid character in header field name');
    }

    return trim(name);
}
<commit_msg>update headers<commit_after>/**
 * HTTP Headers.
 */

import { each, trim, toLower } from '../util';

export default class Headers {

    constructor(headers) {

        this.map = {};

        each(headers, (value, name) => this.append(name, value));
    }

    has(name) {
        return getName(this.map, name) !== null;
    }

    get(name) {

        var list = this.map[getName(this.map, name)];

        return list ? list.join() : null;
    }

    getAll(name) {
        return this.map[getName(this.map, name)] || [];
    }

    set(name, value) {
        this.map[normalizeName(getName(this.map, name) || name)] = [trim(value)];
    }

    append(name, value){

        var list = this.map[getName(this.map, name)];

        if (list) {
            list.push(trim(value));
        } else {
            this.set(name, value);
        }
    }

    delete(name){
        delete this.map[getName(this.map, name)];
    }

    deleteAll(){
        this.map = {};
    }

    forEach(callback, thisArg) {
        each(this.map, (list, name) => {
            each(list, value => callback.call(thisArg, value, name, this));
        });
    }

}

function getName(map, name) {
    return Object.keys(map).reduce((prev, curr) => {
        return toLower(name) === toLower(curr) ? curr : prev;
    }, null);
}

function normalizeName(name) {

    if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
        throw new TypeError('Invalid character in header field name');
    }

    return trim(name);
}
<|endoftext|>


<commit_before>// Wizard Helper JavaScript class to communicate with the WizardHelper PHP class

function WizardHelper(sClass)
{
	this.m_oData = { 'm_sClass' : '',
					 'm_oFieldsMap': {},
					 'm_aCurrentValues': [],
					 'm_aDefaultValueRequested': [],
					 'm_aAllowedValuesRequested': [],
					 'm_aDefaultValue': [],
					 'm_aAllowedValues': [],
					 'm_iFieldsCount' : 0,
					};
	this.m_oData.m_sClass = sClass;

	// Methods
	this.SetFieldsMap = function (oFieldsMap)
	{
		this.m_oData.m_oFieldsMap = oFieldsMap;

	}
	this.SetFieldsCount = function (count)
	{
		this.m_oData.m_iFieldsCount = count;

	}

	this.RequestDefaultValue = function (sFieldName)
	{
		currentValue = this.UpdateCurrentValue(sFieldName);
		sFieldId = this.m_oData.m_oFieldsMap[sFieldName];
		if (currentValue == null)
		{
			this.m_oData.m_aDefaultValueRequested.push(sFieldName);
		}
	}
	this.RequestAllowedValues = function (sFieldName)
	{
		this.m_oData.m_aAllowedValuesRequested.push(sFieldName);
	}
	this.SetCurrentValue = function (sFieldName, currentValue)
	{
		this.m_oData.m_aCurrentValues[this.m_oData.m_oFieldsMap[sFieldName]] = currentValue;
	}

	this.ToJSON = function ()
	{
		return JSON.stringify(this.m_oData);
	}

	this.FromJSON = function (sJSON)
	{
		//console.log('Parsing JSON:'+sJSON);
		this.m_oData = JSON.parse(sJSON);
	}

	this.ResetQuery = function ()
	{
		this.m_oData.m_aDefaultValueRequested = [];
		this.m_oData.m_aDefaultValue = [];
		this.m_oData.m_aAllowedValuesRequested = [];
		this.m_oData.m_aAllowedValues = [];
	}

	this.UpdateFields = function ()
	{
		//console.log('** UpdateFields **');
		//console.log(this.m_oData);
		for(i=0; i< this.m_oData.m_aAllowedValuesRequested.length; i++)
		{
			sAttCode = this.m_oData.m_aAllowedValuesRequested[i];
			sFieldId = this.m_oData.m_oFieldsMap[sAttCode];
			$('#field_'+sFieldId).html(this.m_oData.m_aAllowedValues[sFieldId]);
		}
		for(i=0; i< this.m_oData.m_aDefaultValueRequested.length; i++)
		{
			sAttCode = this.m_oData.m_aDefaultValueRequested[i];
			sFieldId = this.m_oData.m_oFieldsMap[sAttCode];
			defaultValue = this.m_oData.m_aDefaultValue[sFieldId];
			//console.log('Setting field:'+sFieldId+' ('+sAttCode+') to: '+defaultValue);
			var oElement = document.getElementById('att_'+sFieldId);
			oElement.value = defaultValue;
			//console.log('att_'+sFieldId+', set to '+defaultValue);
		}
	}

	this.UpdateWizard = function ()
	{
		//console.log('** UpdateWizard **')
		for(i=0; i< this.m_oData.m_iFieldsCount; i++)
		{
			value = $('#att_'+i).val();
			if (value == '')
			{
				value = null;
			}
			this.m_oData.m_aCurrentValues[i] = value;
		}
	}

	this.AjaxQueryServer = function ()
	{
		//console.log('data sent:', this.ToJSON());
		//console.log('oWizard:', this);
		$.get('ajax.render.php?json_obj=' + this.ToJSON(),
		   { operation: 'wizard_helper' },
			function(html){
				$('body').append(html);
				//console.log('data received:', oWizardHelper);
				//oWizardHelper.FromJSON(json_data);
				//oWizardHelper.UpdateFields(); // Is done directly in the html provided by ajax.render.php
				//console.log(oWizardHelper);
				$('#wizStep'+ G_iCurrentStep).unblock( {fadeOut: 0} );
			});
	}

	this.Preview = function (divId)
	{
		//console.log('data sent:', this.ToJSON());
		//console.log('oWizard:', this);
		$('#'+divId).load('ajax.render.php?operation=wizard_helper_preview',
		   	{'json_obj': this.ToJSON()},
			function(responseText, textStatus, XMLHttpRequest){
				$('#wizStep'+ G_iCurrentStep).unblock( {fadeOut: 0} );
			});
	}

	this.UpdateCurrentValue = function (sFieldName)
	{
		sFieldId = this.m_oData.m_oFieldsMap[sFieldName];
		var oElement = document.getElementById('att_'+sFieldId);
		value = oElement.value;
		if (value == '')
		{
			value = null;
		}
		this.m_oData.m_aCurrentValues[sFieldId] = value;
		return value;
	}
}
<commit_msg>- Fix for Internet Explorer: Arrays must be properly closed!<commit_after>// Wizard Helper JavaScript class to communicate with the WizardHelper PHP class
function WizardHelper(sClass)
{
	this.m_oData = { 'm_sClass' : '',
					 'm_oFieldsMap': {},
					 'm_aCurrentValues': [],
					 'm_aDefaultValueRequested': [],
					 'm_aAllowedValuesRequested': [],
					 'm_aDefaultValue': [],
					 'm_aAllowedValues': [],
					 'm_iFieldsCount' : 0
					};
	this.m_oData.m_sClass = sClass;

	// Methods
	this.SetFieldsMap = function (oFieldsMap)
	{
		this.m_oData.m_oFieldsMap = oFieldsMap;

	}
	this.SetFieldsCount = function (count)
	{
		this.m_oData.m_iFieldsCount = count;

	}

	this.RequestDefaultValue = function (sFieldName)
	{
		currentValue = this.UpdateCurrentValue(sFieldName);
		sFieldId = this.m_oData.m_oFieldsMap[sFieldName];
		if (currentValue == null)
		{
			this.m_oData.m_aDefaultValueRequested.push(sFieldName);
		}
	}
	this.RequestAllowedValues = function (sFieldName)
	{
		this.m_oData.m_aAllowedValuesRequested.push(sFieldName);
	}
	this.SetCurrentValue = function (sFieldName, currentValue)
	{
		this.m_oData.m_aCurrentValues[this.m_oData.m_oFieldsMap[sFieldName]] = currentValue;
	}

	this.ToJSON = function ()
	{
		return JSON.stringify(this.m_oData);
	}

	this.FromJSON = function (sJSON)
	{
		//console.log('Parsing JSON:'+sJSON);
		this.m_oData = JSON.parse(sJSON);
	}

	this.ResetQuery = function ()
	{
		this.m_oData.m_aDefaultValueRequested = [];
		this.m_oData.m_aDefaultValue = [];
		this.m_oData.m_aAllowedValuesRequested = [];
		this.m_oData.m_aAllowedValues = [];
	}

	this.UpdateFields = function ()
	{
		//console.log('** UpdateFields **');
		//console.log(this.m_oData);
		for(i=0; i< this.m_oData.m_aAllowedValuesRequested.length; i++)
		{
			sAttCode = this.m_oData.m_aAllowedValuesRequested[i];
			sFieldId = this.m_oData.m_oFieldsMap[sAttCode];
			$('#field_'+sFieldId).html(this.m_oData.m_aAllowedValues[sFieldId]);
		}
		for(i=0; i< this.m_oData.m_aDefaultValueRequested.length; i++)
		{
			sAttCode = this.m_oData.m_aDefaultValueRequested[i];
			sFieldId = this.m_oData.m_oFieldsMap[sAttCode];
			defaultValue = this.m_oData.m_aDefaultValue[sFieldId];
			//console.log('Setting field:'+sFieldId+' ('+sAttCode+') to: '+defaultValue);
			var oElement = document.getElementById('att_'+sFieldId);
			oElement.value = defaultValue;
			//console.log('att_'+sFieldId+', set to '+defaultValue);
		}
	}

	this.UpdateWizard = function ()
	{
		//console.log('** UpdateWizard **')
		for(i=0; i< this.m_oData.m_iFieldsCount; i++)
		{
			value = $('#att_'+i).val();
			if (value == '')
			{
				value = null;
			}
			this.m_oData.m_aCurrentValues[i] = value;
		}
	}

	this.AjaxQueryServer = function ()
	{
		//console.log('data sent:', this.ToJSON());
		//console.log('oWizard:', this);
		$.get('ajax.render.php?json_obj=' + this.ToJSON(),
		   { operation: 'wizard_helper' },
			function(html){
				$('body').append(html);
				//console.log('data received:', oWizardHelper);
				//oWizardHelper.FromJSON(json_data);
				//oWizardHelper.UpdateFields(); // Is done directly in the html provided by ajax.render.php
				//console.log(oWizardHelper);
				$('#wizStep'+ G_iCurrentStep).unblock( {fadeOut: 0} );
			});
	}

	this.Preview = function (divId)
	{
		//console.log('data sent:', this.ToJSON());
		//console.log('oWizard:', this);
		$('#'+divId).load('ajax.render.php?operation=wizard_helper_preview',
		   	{'json_obj': this.ToJSON()},
			function(responseText, textStatus, XMLHttpRequest){
				$('#wizStep'+ G_iCurrentStep).unblock( {fadeOut: 0} );
			});
	}

	this.UpdateCurrentValue = function (sFieldName)
	{
		sFieldId = this.m_oData.m_oFieldsMap[sFieldName];
		var oElement = document.getElementById('att_'+sFieldId);
		value = oElement.value;
		if (value == '')
		{
			value = null;
		}
		this.m_oData.m_aCurrentValues[sFieldId] = value;
		return value;
	}
}
<|endoftext|>


<commit_before>/*#ifndef(UMD)*/
"use strict";
/*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*global _gpfA*/ // gpf.attributes
/*global _gpfDefAttr*/ // gpf.define for attributes
/*global _gpfI*/ // gpf.interfaces
/*global _gpfDefIntrf*/ // gpf.define for interfaces
/*global _gpfIsArrayLike*/ // Return true if the parameter looks like an array
/*global _gpfIgnore*/ // Helper to remove unused parameter warning
/*global _gpfEventsFire*/ // gpf.events.fire (internal, parameters must match)
/*global _GPF_EVENT_END_OF_DATA*/ // gpf.events.EVENT_END_OF_DATA
/*exported _gpfArrayEnumerator*/
/*#endif*/

_gpfErrorDeclare("i_enumerator", {
    EnumerableInvalidMember:
        "$Enumerator can be associated to arrays only"
});

/**
 * Enumerable interface
 *
 * @class gpf.interfaces.IEnumerator
 * @extends gpf.interfaces.Interface
 */
_gpfDefIntrf("IEnumerator", {

    /**
     * Sets the enumerator to its initial position, which is *before* the
     * first element in the collection.
     *
     * NOTE once reset has been called, you must call moveNext to access (or
     * not)the first element.
     */
    reset: function () {
    },

    /**
     * Moves the enumerator to the next element of the enumeration.
     *
     * @param {gpf.events.Handler} eventsHandler
     * @return {Boolean}
     * - true if the enumerator was successfully advanced to the next element
     * - false if the enumerator has passed the end of the collection or it has
     *   to go through an asynchronous operation
     *
     * NOTE: if no eventsHandler is specified, no asynchronous operation will
     * be triggered when false is returned.
     *
     * @event gpf.events.EVENT_DATA
     * The asynchronous operation succeeded, the current item is available
     *
     * @event gpf.events.EVENT_END_OF_DATA
     * No more data is available
     */
    "[moveNext]": [gpf.$ClassEventHandler()],
    moveNext: function (eventsHandler) {
        _gpfIgnore(eventsHandler);
        return false;
    },

    /**
     * Gets the current element in the collection.
     *
     * @return {*}
     */
    current: function () {
        return null;
    },

    static: {

        /**
         * Enumerates all elements of the enumerator and call the callback
         * function.
         *
         * @param {gpf.interfaces.IEnumerator} enumerator
         * @param {Function} callback receive each item of the enumerator,
         * signature is either:
         * - {*} element
         *
         * or
         * - {*} element
         * - {gpf.events.Handler} eventsHandler
         *
         * If the signature supports two parameter, the last one will be used
         * to control the iteration. The callback function has to trigger
         * - gpf.events.EVENT_CONTINUE
         * - gpf.events.EVENT_STOP
         *
         * @param {gpf.events.Handler} eventsHandler
         *
         * @event gpf.events.EVENT_END_OF_DATA
         * No more data is available, the each function terminated
         *
         * @event gpf.events.EVENT_STOPPED
         * The processing function requested to stop enumeration
         */
        // TODO how to put attributes on static members?
        // "[each]": [gpf.$ClassEventHandler()],
        each: function (enumerator, callback, eventsHandler) {
            _gpfIgnore(enumerator);
            _gpfIgnore(callback);
            _gpfIgnore(eventsHandler);
        }

    }

});

/**
 * Builds an enumerable interface based on an array
 *
 * @param {Object[]} array Base of the enumeration
 * @return {Object} Object implementing the IEnumerable interface
 * @private
 */
function _gpfArrayEnumerator(array) {
    var pos = -1;
    return {
        reset: function () {
            pos = -1;
        },
        moveNext: function (eventsHandler) {
            var result;
            ++pos;
            result = pos < array.length;
            if (!result && eventsHandler) {
                _gpfEventsFire.apply(this, [
                    _GPF_EVENT_END_OF_DATA,
                    {},
                    eventsHandler
                ]);
            }
            return result;
        },
        current: function () {
            if (0 > pos || pos >= array.length) {
                return undefined;
            }
            return array[pos];
        }
    };
}

/**
 * Interface builder that connects to the EnumerableAttribute attribute
 *
 * @param {Object} object
 * @return {Object} Object implementing the IEnumerable interface
 * @private
 */
function _buildEnumeratorOnObjectArray(object) {
    // Look for related member
    var
        attributes = new _gpfA.Map(object).filter(_gpfA.EnumerableAttribute),
        members = attributes.members();
    return _gpfArrayEnumerator(object[members[0]]);
}

/**
 * Extend the class to provide an enumerator interface
 *
 * @class gpf.attributes.EnumerableAttribute
 * @extends gpf.attributes.ClassAttribute
 * @alias gpf.$Enumerable
 */
_gpfDefAttr("$Enumerable", _gpfA.ClassAttribute, {

    "Class": [gpf.$UniqueAttribute()],

    /**
     * @inheritDoc gpf.attributes.Attribute:_alterPrototype
     */
    _alterPrototype: function (objPrototype) {
        if (!_gpfIsArrayLike(objPrototype[this._member])) {
            throw gpf.Error.EnumerableInvalidMember();
        }
        _gpfA.add(objPrototype.constructor, "Class", [
            new _gpfA.InterfaceImplementAttribute(_gpfI.IEnumerator,
                _buildEnumeratorOnObjectArray)
        ]);
    }

});<commit_msg>IEnumerator.each<commit_after>/*#ifndef(UMD)*/
"use strict";
/*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*global _gpfA*/ // gpf.attributes
/*global _gpfDefAttr*/ // gpf.define for attributes
/*global _gpfI*/ // gpf.interfaces
/*global _gpfDefIntrf*/ // gpf.define for interfaces
/*global _gpfIsArrayLike*/ // Return true if the parameter looks like an array
/*global _gpfIgnore*/ // Helper to remove unused parameter warning
/*global _gpfEventsFire*/ // gpf.events.fire (internal, parameters must match)
/*global _GPF_EVENT_END_OF_DATA*/ // gpf.events.EVENT_END_OF_DATA
/*exported _gpfArrayEnumerator*/
/*#endif*/

_gpfErrorDeclare("i_enumerator", {
    EnumerableInvalidMember:
        "$Enumerator can be associated to arrays only"
});

/**
 * Enumerable interface
 *
 * @class gpf.interfaces.IEnumerator
 * @extends gpf.interfaces.Interface
 */
_gpfDefIntrf("IEnumerator", {

    /**
     * Sets the enumerator to its initial position, which is *before* the
     * first element in the collection.
     *
     * NOTE once reset has been called, you must call moveNext to access (or
     * not)the first element.
     */
    reset: function () {
    },

    /**
     * Moves the enumerator to the next element of the enumeration.
     *
     * @param {gpf.events.Handler} eventsHandler
     * @return {Boolean}
     * - true if the enumerator was successfully advanced to the next element
     * - false if the enumerator has passed the end of the collection or it has
     *   to go through an asynchronous operation
     *
     * NOTE: if no eventsHandler is specified, no asynchronous operation will
     * be triggered when false is returned.
     *
     * @event gpf.events.EVENT_DATA
     * The asynchronous operation succeeded, the current item is available
     *
     * @event gpf.events.EVENT_END_OF_DATA
     * No more data is available
     */
    "[moveNext]": [gpf.$ClassEventHandler()],
    moveNext: function (eventsHandler) {
        _gpfIgnore(eventsHandler);
        return false;
    },

    /**
     * Gets the current element in the collection.
     *
     * @return {*}
     */
    current: function () {
        return null;
    },

    static: {

        /**
         * Enumerates all elements of the enumerator and call the callback
         * function.
         *
         * NOTE: reset is *not* called.
         *
         * @param {gpf.interfaces.IEnumerator} enumerator
         * @param {Function} callback receive each item of the enumerator,
         * signature is either:
         * - {*} element
         *
         * or
         * - {*} element
         * - {gpf.events.Handler} eventsHandler
         *
         * If the signature supports two parameter, the last one will be used
         * to control the iteration. The callback function has to trigger
         * - gpf.events.EVENT_CONTINUE
         * - gpf.events.EVENT_STOP
         *
         * @param {gpf.events.Handler} eventsHandler
         *
         * @event gpf.events.EVENT_END_OF_DATA
         * No more data is available, the each function terminated
         *
         * @event gpf.events.EVENT_STOPPED
         * The processing function requested to stop enumeration
         */
        // TODO how to put attributes on static members?
        // "[each]": [gpf.$ClassEventHandler()],
        each: function (enumerator, callback, eventsHandler) {
            var
                iEnumerator = _gpfI.query(enumerator, _gpfI.IEnumerator),
                end = function (event) {
                    _gpfEventsFire.apply(enumerator, [event, {},
                        eventsHandler]);
                },
                process;
            if (1 < callback.length) {
                process = function (event) {
                    if (gpf.events.EVENT_CONTINUE === event.type) {
                        if (!iEnumerator.moveNext(process)) {
                            return;
                        }
                    } else if (gpf.events.EVENT_STOP === event.type) {
                        return end(gpf.events.EVENT_STOPPED);
                    } else if (gpf.events.EVENT_DATA !== event.type) {
                        return end(event.type);
                    }
                    callback(iEnumerator.current(), process);
                };
                if (iEnumerator.moveNext(process)) {
                    callback(iEnumerator.current(), process);
                }

            } else {
                process = function (event) {
                    if (gpf.events.EVENT_DATA !== event.type) {
                        return end(event.type);
                    }
                    do {
                        callback(iEnumerator.current());
                    } while (iEnumerator.moveNext(process));
                };
                while (iEnumerator.moveNext(process)) {
                    callback(iEnumerator.current());
                }
            }
            process();
        }

    }

});

/**
 * Builds an enumerable interface based on an array
 *
 * @param {Object[]} array Base of the enumeration
 * @return {Object} Object implementing the IEnumerable interface
 * @private
 */
function _gpfArrayEnumerator(array) {
    var pos = -1;
    return {
        reset: function () {
            pos = -1;
        },
        moveNext: function (eventsHandler) {
            var result;
            ++pos;
            result = pos < array.length;
            if (!result && eventsHandler) {
                _gpfEventsFire.apply(this, [
                    _GPF_EVENT_END_OF_DATA,
                    {},
                    eventsHandler
                ]);
            }
            return result;
        },
        current: function () {
            if (0 > pos || pos >= array.length) {
                return undefined;
            }
            return array[pos];
        }
    };
}

/**
 * Interface builder that connects to the EnumerableAttribute attribute
 *
 * @param {Object} object
 * @return {Object} Object implementing the IEnumerable interface
 * @private
 */
function _buildEnumeratorOnObjectArray(object) {
    // Look for related member
    var
        attributes = new _gpfA.Map(object).filter(_gpfA.EnumerableAttribute),
        members = attributes.members();
    return _gpfArrayEnumerator(object[members[0]]);
}

/**
 * Extend the class to provide an enumerator interface
 *
 * @class gpf.attributes.EnumerableAttribute
 * @extends gpf.attributes.ClassAttribute
 * @alias gpf.$Enumerable
 */
_gpfDefAttr("$Enumerable", _gpfA.ClassAttribute, {

    "Class": [gpf.$UniqueAttribute()],

    /**
     * @inheritDoc gpf.attributes.Attribute:_alterPrototype
     */
    _alterPrototype: function (objPrototype) {
        if (!_gpfIsArrayLike(objPrototype[this._member])) {
            throw gpf.Error.EnumerableInvalidMember();
        }
        _gpfA.add(objPrototype.constructor, "Class", [
            new _gpfA.InterfaceImplementAttribute(_gpfI.IEnumerator,
                _buildEnumeratorOnObjectArray)
        ]);
    }

});<|endoftext|>


<commit_before>/*eslint strict: [2, "function"]*/ // IIFE form
/*eslint-disable func-style*/ // So that everything is grouped in one var
(function () {
    "use strict";

    /*global run, exit:true*/ // From bdd.js
    /*global __coverage__*/ // Coverage data

    var Func = Function,
        sources,
        context = (function () {
            /*global global*/ // NodeJS global
            if ("object" === typeof global) {
                return global;
            }
            /*global window*/ // Browser global
            if ("undefined" !== typeof window) {
                return window;
            }
            return this; //eslint-disable-line no-invalid-this
        }()),

        _resolvePath = function (configuration, relativePath) {
            return configuration.gpfPath
                .split(configuration.pathSeparator)
                .concat(relativePath.split("/"))
                .join(configuration.pathSeparator);
        },

        _processParameters = function (configuration, options) {
            var len = configuration.parameters.length,
                idx,
                value;
            for (idx = 0; idx < len; ++idx) {
                value = configuration.parameters[idx];
                if (value.charAt(0) === "-") {
                    value = value.substr(1);
                    if (value in options && "boolean" === typeof options[value]) {
                        options[value] = !options[value]; // Simple switch
                    }
                } else {
                    options.tests.push(value);
                }
            }
            if (options.perfInfinite) {
                options.perf = true;
            }
        },

        _load = function (configuration, path) {
            var content = configuration.read(path);
            try {
                /*jslint evil: true*/
                eval(content); //eslint-disable-line no-eval
                /*jslint evil: false*/
            } catch (e) {
                configuration.log("An error occurred while evaluating: " + path + "\r\n" + e.message);
                configuration.exit(-1);
            }
        },

        _requireGpf = function (configuration, path) {
            if (configuration.require) {
                context.gpf = configuration.require(path);
            } else {
                _load(configuration, path);
                if ("undefined" === typeof gpf) {
                    configuration.log("GPF was not loaded");
                    configuration.exit(-1);
                }
            }
        },

        _loadGpf = function (configuration, options, verbose) {
            if (options.release) {
                verbose("Using release version");
                _requireGpf(configuration, _resolvePath(configuration, "build/gpf.js"));

            } else if (options.debug) {
                verbose("Using debug version");
                _requireGpf(configuration, _resolvePath(configuration, "build/gpf-debug.js"));

            } else {
                if (options.coverage) {
                    verbose("Using *instrumented* source version");
                    context.global = context;
                    context.gpfSourcesPath = _resolvePath(configuration, "tmp/coverage/instrument/src/");

                } else {
                    verbose("Using source version");
                    context.gpfSourcesPath = _resolvePath(configuration, "src/");
                }
                _load(configuration, gpfSourcesPath + "boot.js");
            }
            // Load the list of modules
            var sourcesJson = configuration.read("src/sources.json");
            sources = new Func("return " + sourcesJson + ";")();
        },

        _loadBDD = function (configuration, verbose) {
            if (undefined === configuration.run) {
                verbose("Loading BDD...");
                _load(configuration, _resolvePath(configuration, "test/host/bdd.js"));
                verbose("BDD loaded.");
            }
        },

        _loadTest = function (configuration, path) {
            if (configuration.loadTest) {
                configuration.loadTest(path);
            } else {
                _load(configuration, path);
            }
        },

        _loadTestsFromNames = function (configuration, names) {
            var len = names.length,
                sourceIdx,
                source;
            for (sourceIdx = 0; sourceIdx < len; ++sourceIdx) {
                source = names[sourceIdx];
                if (source.indexOf("legacy/") === 0) {
                    delete gpf.internals;
                }
                _loadTest(configuration, _resolvePath(configuration, "test/" + source + ".js"));
            }
        },

        _loadTestsFromModules = function (configuration) {
            var len = sources.length,
                sourceIdx,
                source;
            for (sourceIdx = 0; sourceIdx < len; ++sourceIdx) {
                source = sources[sourceIdx];
                if (source.load !== false && source.test !== false) {
                    _loadTest(configuration, _resolvePath(configuration, "test/" + source.name + ".js"));
                }
            }
        },

        _loadTests = function (configuration, options, verbose) {
            verbose("Loading test files...");
            if (options.tests.length) {
                _loadTestsFromNames(configuration, options.tests);
            } else {
                _loadTestsFromModules(configuration);
            }
            verbose("Test files loaded.");
        },

        _setupConfig = function (configuration/*, options*/) {
            var configFile = JSON.parse(configuration.read("tmp/config.json"));
            context.config = {
                httpPort: configFile.serve.httpPort
            };
        },

        _mean = function (values) {
            var total = 0,
                len = values.length,
                idx;
            for (idx = 0; idx < len; ++idx) {
                total += values[idx];
            }
            return Math.floor(total / len);
        },

        _stdDeviation = function (values) {
            var mean = _mean(values),
                total = 0,
                len = values.length,
                idx,
                diff;
            for (idx = 0; idx < len; ++idx) {
                diff = values[idx] - mean;
                total += diff * diff;
            }
            return Math.floor(Math.sqrt(total / len));
        },

        _pad = function (value, size) {
            var pad = size - value.toString().length;
            if (pad > 0) {
                return new Array(pad).join(" ") + value;
            }
            return value;
        },

        _runBDDPerf = function (configuration, options) {
            var loop = 1,
                maxLoop,
                runWithCallback,
                measures = [];
            if (options.perfInfinite) {
                maxLoop = Math.MAX_SAFE_INTEGER;
            } else {
                maxLoop = 10;
            }
            function callback (type, data) {
                var statistics;
                if ("it" === type) {
                    if (!data.result) {
                        configuration.log("ERROR: " + JSON.stringify(data));
                        maxLoop = 0; // Stop
                    }
                } else if ("results" === type) {
                    statistics = ["Round ", _pad(loop, 9), ": ", _pad(data.timeSpent, 5), "ms "];
                    if (1 === loop) {
                        statistics.push("(ignored)");
                    } else {
                        measures.push(data.timeSpent);
                        statistics.push("mean: ", _pad(_mean(measures), 5), "ms ",
                            "deviation: ", _pad(_stdDeviation(measures), 5));
                    }
                    configuration.log(statistics.join(""));
                    if (maxLoop < loop) {
                        configuration.log("Mean time: " + _mean(measures) + "ms");
                    } else {
                        ++loop;
                        setTimeout(runWithCallback, 0);
                    }
                }
            }
            runWithCallback = function () {
                run(callback);
            };
            runWithCallback();
        },

        _runBDDForCoverage = function (configuration, options, verbose) {
            verbose("Running BDD - coverage");
            run(function (type, data) {
                if ("results" !== type) {
                    return;
                }
                if (data.fail) {
                    verbose("Failed: " + data.fail + ".");
                    exit(-1);
                }
                verbose("Uploading coverage results...");
                gpf.http.request({
                    method: gpf.http.methods.post,
                    url: "http://localhost:" + config.httpPort + "/fs/tmp/coverage/reports/coverage."
                        + gpf.host() + ".json",
                    data: JSON.stringify(__coverage__)
                })
                    .then(function () {
                        verbose("Coverage results uploaded.");
                        exit(0);
                    }, function (reason) {
                        verbose("Upload failed: " + reason.toString());
                        exit(-1);
                    });
            });
        },

        _runBDD = function (configuration, options, verbose) {
            exit = configuration.exit; // used by BDD.js
            if (options.perf) {
                verbose("Running BDD - performances");
                _runBDDPerf(configuration, options);
            } else if (options.coverage) {
                _runBDDForCoverage(configuration, options, verbose);
            } else {
                verbose("Running BDD");
                run();
            }
        },

        _safeRunBDD = function (configuration, options, verbose) {
            try {
                if (undefined === configuration.run) {
                    _runBDD(configuration, options, verbose);
                } else {
                    configuration.run();
                }
                gpf.handleTimeout();
            } catch (e) {
                configuration.log("An error occurred while running the tests:\r\n" + e.message);
                configuration.exit(-1);
            }
        };

    /*
     * Expected members on configuration:
     * - {String[]} parameters command line parameters
     * - {String} gpfPath GPF base path
     * - {String} pathSeparator
     * - {Function} log
     * - {Function} exit
     * - (Function) require
     * - (Function) read  function (filePath) {} reads a file
     * - (Function) [loadTest=undefined] loadTest function (filePath) {} reads a test file
     * - {Function} run When defined, this method is triggered to execute the tests
     */
    context.loadGpfAndTests = function (configuration) {
        var options = {
                release: false,
                debug: false,
                coverage: false,
                verbose: false,
                ignoreConsole: false,
                perf: false,
                perfInfinite: false,
                tests: []
            },
            verbose;
        _processParameters(configuration, options);
        // Define a debug function that outputs when verbose is set
        if (options.verbose) {
            verbose = configuration.log;
        } else {
            verbose = function () {};
        }
        _loadGpf(configuration, options, verbose);
        _loadBDD(configuration, verbose);
        if (!options.ignoreConsole) {
            verbose("Loading console...");
            _load(configuration, _resolvePath(configuration, "test/host/console.js"));
            verbose("Console loaded.");
        }
        _setupConfig(configuration, options);
        _loadTests(configuration, options, verbose);
        _safeRunBDD(configuration, options, verbose);
    };

}());
<commit_msg>Better error reporting<commit_after>/*eslint strict: [2, "function"]*/ // IIFE form
/*eslint-disable func-style*/ // So that everything is grouped in one var
(function () {
    "use strict";

    /*global run, exit:true*/ // From bdd.js
    /*global __coverage__*/ // Coverage data

    var Func = Function,
        sources,
        context = (function () {
            /*global global*/ // NodeJS global
            if ("object" === typeof global) {
                return global;
            }
            /*global window*/ // Browser global
            if ("undefined" !== typeof window) {
                return window;
            }
            return this; //eslint-disable-line no-invalid-this
        }()),

        _resolvePath = function (configuration, relativePath) {
            return configuration.gpfPath
                .split(configuration.pathSeparator)
                .concat(relativePath.split("/"))
                .join(configuration.pathSeparator);
        },

        _processParameters = function (configuration, options) {
            var len = configuration.parameters.length,
                idx,
                value;
            for (idx = 0; idx < len; ++idx) {
                value = configuration.parameters[idx];
                if (value.charAt(0) === "-") {
                    value = value.substr(1);
                    if (value in options && "boolean" === typeof options[value]) {
                        options[value] = !options[value]; // Simple switch
                    }
                } else {
                    options.tests.push(value);
                }
            }
            if (options.perfInfinite) {
                options.perf = true;
            }
        },

        _load = function (configuration, path) {
            var content = configuration.read(path);
            try {
                /*jslint evil: true*/
                eval(content); //eslint-disable-line no-eval
                /*jslint evil: false*/
            } catch (e) {
                configuration.log("An error occurred while evaluating: " + path + "\r\n" + e.message);
                configuration.exit(-1);
            }
        },

        _requireGpf = function (configuration, path) {
            if (configuration.require) {
                context.gpf = configuration.require(path);
            } else {
                _load(configuration, path);
                if ("undefined" === typeof gpf) {
                    configuration.log("GPF was not loaded");
                    configuration.exit(-1);
                }
            }
        },

        _loadGpf = function (configuration, options, verbose) {
            if (options.release) {
                verbose("Using release version");
                _requireGpf(configuration, _resolvePath(configuration, "build/gpf.js"));

            } else if (options.debug) {
                verbose("Using debug version");
                _requireGpf(configuration, _resolvePath(configuration, "build/gpf-debug.js"));

            } else {
                if (options.coverage) {
                    verbose("Using *instrumented* source version");
                    context.global = context;
                    context.gpfSourcesPath = _resolvePath(configuration, "tmp/coverage/instrument/src/");

                } else {
                    verbose("Using source version");
                    context.gpfSourcesPath = _resolvePath(configuration, "src/");
                }
                _load(configuration, gpfSourcesPath + "boot.js");
            }
            // Load the list of modules
            var sourcesJson = configuration.read("src/sources.json");
            sources = new Func("return " + sourcesJson + ";")();
        },

        _loadBDD = function (configuration, verbose) {
            if (undefined === configuration.run) {
                verbose("Loading BDD...");
                _load(configuration, _resolvePath(configuration, "test/host/bdd.js"));
                verbose("BDD loaded.");
            }
        },

        _loadTest = function (configuration, path) {
            if (configuration.loadTest) {
                configuration.loadTest(path);
            } else {
                _load(configuration, path);
            }
        },

        _loadTestsFromNames = function (configuration, names) {
            var len = names.length,
                sourceIdx,
                source;
            for (sourceIdx = 0; sourceIdx < len; ++sourceIdx) {
                source = names[sourceIdx];
                if (source.indexOf("legacy/") === 0) {
                    delete gpf.internals;
                }
                _loadTest(configuration, _resolvePath(configuration, "test/" + source + ".js"));
            }
        },

        _loadTestsFromModules = function (configuration) {
            var len = sources.length,
                sourceIdx,
                source;
            for (sourceIdx = 0; sourceIdx < len; ++sourceIdx) {
                source = sources[sourceIdx];
                if (source.load !== false && source.test !== false) {
                    _loadTest(configuration, _resolvePath(configuration, "test/" + source.name + ".js"));
                }
            }
        },

        _loadTests = function (configuration, options, verbose) {
            verbose("Loading test files...");
            if (options.tests.length) {
                _loadTestsFromNames(configuration, options.tests);
            } else {
                _loadTestsFromModules(configuration);
            }
            verbose("Test files loaded.");
        },

        _setupConfig = function (configuration/*, options*/) {
            var configFile = JSON.parse(configuration.read("tmp/config.json"));
            context.config = {
                httpPort: configFile.serve.httpPort
            };
        },

        _mean = function (values) {
            var total = 0,
                len = values.length,
                idx;
            for (idx = 0; idx < len; ++idx) {
                total += values[idx];
            }
            return Math.floor(total / len);
        },

        _stdDeviation = function (values) {
            var mean = _mean(values),
                total = 0,
                len = values.length,
                idx,
                diff;
            for (idx = 0; idx < len; ++idx) {
                diff = values[idx] - mean;
                total += diff * diff;
            }
            return Math.floor(Math.sqrt(total / len));
        },

        _pad = function (value, size) {
            var pad = size - value.toString().length;
            if (pad > 0) {
                return new Array(pad).join(" ") + value;
            }
            return value;
        },

        _perfError = function (configuration, data) {
            configuration.log("ERROR during performance test:");
            var property,
                value;
            for (property in data) {
                if (data.hasOwnProperty(property)) {
                    value = data[property];
                    if (property === "exception" && value instanceof Error) {
                        configuration.log("\t" + _pad(property, 10) + ": " + value.message);
                    } else {
                        configuration.log("\t" + _pad(property, 10) + ": " + value.toString());
                    }
                }
            }
        },

        _runBDDPerf = function (configuration, options) {
            var loop = 1,
                maxLoop,
                runWithCallback,
                measures = [];
            if (options.perfInfinite) {
                maxLoop = Math.MAX_SAFE_INTEGER;
            } else {
                maxLoop = 10;
            }
            function callback (type, data) {
                var statistics;
                if ("it" === type) {
                    if (!data.result) {
                        _perfError(configuration, data);
                        maxLoop = 0; // Stop
                    }
                } else if ("results" === type) {
                    statistics = ["Round ", _pad(loop, 9), ": ", _pad(data.timeSpent, 5), "ms "];
                    if (1 === loop) {
                        statistics.push("(ignored)");
                    } else {
                        measures.push(data.timeSpent);
                        statistics.push("mean: ", _pad(_mean(measures), 5), "ms ",
                            "deviation: ", _pad(_stdDeviation(measures), 5));
                    }
                    configuration.log(statistics.join(""));
                    if (maxLoop < loop) {
                        configuration.log("Mean time: " + _mean(measures) + "ms");
                    } else {
                        ++loop;
                        setTimeout(runWithCallback, 0);
                    }
                }
            }
            runWithCallback = function () {
                run(callback);
            };
            runWithCallback();
        },

        _runBDDForCoverage = function (configuration, options, verbose) {
            verbose("Running BDD - coverage");
            run(function (type, data) {
                if ("results" !== type) {
                    return;
                }
                if (data.fail) {
                    verbose("Failed: " + data.fail + ".");
                    exit(-1);
                }
                verbose("Uploading coverage results...");
                gpf.http.request({
                    method: gpf.http.methods.post,
                    url: "http://localhost:" + config.httpPort + "/fs/tmp/coverage/reports/coverage."
                        + gpf.host() + ".json",
                    data: JSON.stringify(__coverage__)
                })
                    .then(function () {
                        verbose("Coverage results uploaded.");
                        exit(0);
                    }, function (reason) {
                        verbose("Upload failed: " + reason.toString());
                        exit(-1);
                    });
            });
        },

        _runBDD = function (configuration, options, verbose) {
            exit = configuration.exit; // used by BDD.js
            if (options.perf) {
                verbose("Running BDD - performances");
                _runBDDPerf(configuration, options);
            } else if (options.coverage) {
                _runBDDForCoverage(configuration, options, verbose);
            } else {
                verbose("Running BDD");
                run();
            }
        },

        _safeRunBDD = function (configuration, options, verbose) {
            try {
                if (undefined === configuration.run) {
                    _runBDD(configuration, options, verbose);
                } else {
                    configuration.run();
                }
                gpf.handleTimeout();
            } catch (e) {
                configuration.log("An error occurred while running the tests:\r\n" + e.message);
                configuration.exit(-1);
            }
        };

    /*
     * Expected members on configuration:
     * - {String[]} parameters command line parameters
     * - {String} gpfPath GPF base path
     * - {String} pathSeparator
     * - {Function} log
     * - {Function} exit
     * - (Function) require
     * - (Function) read  function (filePath) {} reads a file
     * - (Function) [loadTest=undefined] loadTest function (filePath) {} reads a test file
     * - {Function} run When defined, this method is triggered to execute the tests
     */
    context.loadGpfAndTests = function (configuration) {
        var options = {
                release: false,
                debug: false,
                coverage: false,
                verbose: false,
                ignoreConsole: false,
                perf: false,
                perfInfinite: false,
                tests: []
            },
            verbose;
        _processParameters(configuration, options);
        // Define a debug function that outputs when verbose is set
        if (options.verbose) {
            verbose = configuration.log;
        } else {
            verbose = function () {};
        }
        _loadGpf(configuration, options, verbose);
        _loadBDD(configuration, verbose);
        if (!options.ignoreConsole) {
            verbose("Loading console...");
            _load(configuration, _resolvePath(configuration, "test/host/console.js"));
            verbose("Console loaded.");
        }
        _setupConfig(configuration, options);
        _loadTests(configuration, options, verbose);
        _safeRunBDD(configuration, options, verbose);
    };

}());
<|endoftext|>


<commit_before>/*globals Ember, LRUCache*/

(function() {
  Ember.Resource.IdentityMap = function(limit, evictionHandler) {
    this.cache = new LRUCache(limit || Ember.Resource.IdentityMap.DEFAULT_IDENTITY_MAP_LIMIT);
    this.evictionHandler = evictionHandler || function() {};
    var map = this;
    this.cache.shift = function() {
      var entry = LRUCache.prototype.shift.call(this);
      map.evictionHandler(entry);
      return entry;
    };
  };

  Ember.Resource.IdentityMap.prototype = {
    get: function() {
      return LRUCache.prototype.get.apply(this.cache, arguments);
    },

    put: function() {
      return LRUCache.prototype.put.apply(this.cache, arguments);
    },

    remove: function() {
      return LRUCache.prototype.remove.apply(this.cache, arguments);
    },

    clear: function() {
      return LRUCache.prototype.removeAll.apply(this.cache, arguments);
    },

    size: function() {
      return this.cache.size;
    },

    limit: function() {
      return this.cache.limit;
    }

  };

  Ember.Resource.IdentityMap.DEFAULT_IDENTITY_MAP_LIMIT = 500;

}());
<commit_msg>more defensive<commit_after>/*globals Ember, LRUCache*/

(function() {
  Ember.Resource.IdentityMap = function(limit, evictionHandler) {
    this.cache = new LRUCache(limit || Ember.Resource.IdentityMap.DEFAULT_IDENTITY_MAP_LIMIT);
    this.evictionHandler = evictionHandler || function() {};
    var map = this,
        origShift = this.cache.shift;

    this.cache.shift = function() {
      var entry = origShift.apply(this, arguments);
      map.evictionHandler(entry);
      return entry;
    };
  };

  Ember.Resource.IdentityMap.prototype = {
    get: function() {
      return LRUCache.prototype.get.apply(this.cache, arguments);
    },

    put: function() {
      return LRUCache.prototype.put.apply(this.cache, arguments);
    },

    remove: function() {
      return LRUCache.prototype.remove.apply(this.cache, arguments);
    },

    clear: function() {
      return LRUCache.prototype.removeAll.apply(this.cache, arguments);
    },

    size: function() {
      return this.cache.size;
    },

    limit: function() {
      return this.cache.limit;
    }

  };

  Ember.Resource.IdentityMap.DEFAULT_IDENTITY_MAP_LIMIT = 500;

}());
<|endoftext|>