<commit_before>//This is the events immediately before the upcoming event.
var events_before =[];
var events_before_index = 0;
function show_previous_doc(){
	console.log("in show_previous_doc function");

	if (currentUserEvents.length == 0 ) {
		return;
	}
    var currentUserEvents_tmp = currentUserEvents.sort(function(a,b){return parseInt(a.startTime) - parseInt(b.startTime)});
    var ev = flashTeamsJSON["events"][getEventJSONIndex(currentUserEvents_tmp[0].id)];
    var upcomingEvent_tmp = ev.id;

    //get the first unfinished task of the worker.
    while (ev.status == "completed"){
        toDelete = upcomingEvent_tmp;
        currentUserEvents_tmp.splice(0,1);
        if (currentUserEvents_tmp.length == 0){
            return;
        }
        upcomingEvent_tmp = currentUserEvents_tmp[0].id;
        ev = flashTeamsJSON["events"][getEventJSONIndex(upcomingEvent_tmp)];
    }

    events_before = events_immediately_before(ev.id);
    if (events_before.length == 0) return;
    var ev_before = flashTeamsJSON["events"][getEventJSONIndex(events_before[events_before_index])];

    if (!checkEventsBeforeCompletedNoAlert(ev.id)) return;

    if(upcoming_ev_doc_seen(upcomingEvent_tmp)){
    	return;
    }
    else{
    	add_ev_seenDocQ(upcomingEvent_tmp);

    	showDocModal(ev_before, events_before);
    	updateStatus();
    }
};

function add_ev_seenDocQ(upcomingEvent_tmp){

 	if(current == undefined){
 		console.log("error: current user is undefined!");
 		return;
 	}
 	for (var i = 0; i < flashTeamsJSON["members"].length; i++) {
        if (parseInt(flashTeamsJSON["members"][i].id) == parseInt(current_user.id))
    		flashTeamsJSON["members"][i].seenDocQs.push(upcomingEvent_tmp);
    }

};

function upcoming_ev_doc_seen(upcomingEvent_tmp){

  var curr_mem = getMemberById(current_user.id);

  var seenDocQs = flashTeamsJSON["members"][0]["seenDocQs"];

  if( (seenDocQs.indexOf(upcomingEvent_tmp)) == -1){
  	return false;
  }
  else{
  	return true;
  }
};

function showDocModal(ev_before, events_before){
	//body of the modal

    var content = '
' ;
    content += "
 The following questions are answered by the DRI of the "+ ev_before.title +" task. Please review them as they are related to your upcoming task:
 ";

    //Add output documentation questions to task modal
    for (var key in ev_before.outputQs){
        if (key != ""){
            content +=   key + "
";
            keyArray = ev_before.outputQs[key];
            for (i = 0; i < keyArray.length; i++){
                content += "

- " + keyArray[i][0] + "
" + keyArray[i][1] + "
";
            }
        }
    }
    //Add general documentation questions to task modal
    if (ev_before.docQs.length > 0){
        docQs = ev_before.docQs;
        for (i = 0; i < docQs.length; i++){
            if (docQs[i][1] != null){
                content += "
- " +  docQs[i][0] ;
                content += "
" + docQs[i][1] + "
";
            }
        }
    }
	content += "
";

	//alert(ev_tmp.docQs[0][0]);
	var modal_footer= '<button class="btn btn-primary" id="next-doc-modal" onclick="nextDocModal()">Next</button>';
	var modal_body=content;
	var modal_label= ev_before.title + " Documentation";

	 $('#doc_modal').modal('show');
     $('.doc-modal-footer').html(modal_footer);
     $('.doc-modal-body').html(modal_body);
     $('#doc_modal_Label').html(modal_label);
     $("#next-doc-modal").css('display', '');
     if( (events_before_index + 1) >= (events_before.length) ){
     	modal_footer = '<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>';
     	$('.doc-modal-footer').html(modal_footer);
 	 }
 	 else
 	 	events_before_index = events_before_index + 1;
};

//is called when next button on the modal is clicked.
function nextDocModal(){
	if(events_before_index >= events_before.length )
		return;
	if (events_before.length == 0) return;
	var ev_before = flashTeamsJSON["events"][getEventJSONIndex(events_before[events_before_index])];
	showDocModal(ev_before, events_before);

};

<commit_msg>bug fix 1.<commit_after>//This is the events immediately before the upcoming event.
var events_before =[];
var events_before_index = 0;
function show_previous_doc(){
	console.log("in show_previous_doc function");

	if (currentUserEvents.length == 0 ) {
		return;
	}
    var currentUserEvents_tmp = currentUserEvents.sort(function(a,b){return parseInt(a.startTime) - parseInt(b.startTime)});
    var ev = flashTeamsJSON["events"][getEventJSONIndex(currentUserEvents_tmp[0].id)];
    var upcomingEvent_tmp = ev.id;

    //get the first unfinished task of the worker.
    while (ev.status == "completed"){
        toDelete = upcomingEvent_tmp;
        currentUserEvents_tmp.splice(0,1);
        if (currentUserEvents_tmp.length == 0){
            return;
        }
        upcomingEvent_tmp = currentUserEvents_tmp[0].id;
        ev = flashTeamsJSON["events"][getEventJSONIndex(upcomingEvent_tmp)];
    }

    events_before = events_immediately_before(ev.id);
    if (events_before.length == 0) return;
    var ev_before = flashTeamsJSON["events"][getEventJSONIndex(events_before[events_before_index])];

    if (!checkEventsBeforeCompletedNoAlert(ev.id)) return;

    if(upcoming_ev_doc_seen(upcomingEvent_tmp)){
    	return;
    }
    else{
    	add_ev_seenDocQ(upcomingEvent_tmp);

    	showDocModal(ev_before, events_before);
    	updateStatus();
    }
};

function add_ev_seenDocQ(upcomingEvent_tmp){

 	if(current == undefined){
 		console.log("error: current user is undefined!");
 		return;
 	}

 	for (var i = 0; i < flashTeamsJSON["members"].length; i++) {
        if (parseInt(flashTeamsJSON["members"][i].id) == parseInt(current_user.id))
    		flashTeamsJSON["members"][i].seenDocQs.push(upcomingEvent_tmp);
    }
};

function upcoming_ev_doc_seen(upcomingEvent_tmp){

  var curr_mem = getMemberById(current_user.id);

  var seenDocQs = curr_mem["seenDocQs"];

  if( (seenDocQs.indexOf(upcomingEvent_tmp)) == -1){
  	return false;
  }
  else{
  	return true;
  }
};

function showDocModal(ev_before, events_before){
	//body of the modal

    var content = '
' ;
    content += "
 The following questions are answered by the DRI of the "+ ev_before.title +" task. Please review them as they are related to your upcoming task:
 ";

    //Add output documentation questions to task modal
    for (var key in ev_before.outputQs){
        if (key != ""){
            content +=   key + "
";
            keyArray = ev_before.outputQs[key];
            for (i = 0; i < keyArray.length; i++){
                content += "

- " + keyArray[i][0] + "
" + keyArray[i][1] + "
";
            }
        }
    }
    //Add general documentation questions to task modal
    if (ev_before.docQs.length > 0){
        docQs = ev_before.docQs;
        for (i = 0; i < docQs.length; i++){
            if (docQs[i][1] != null){
                content += "
- " +  docQs[i][0] ;
                content += "
" + docQs[i][1] + "
";
            }
        }
    }
	content += "
";

	//alert(ev_tmp.docQs[0][0]);
	var modal_footer= '<button class="btn btn-primary" id="next-doc-modal" onclick="nextDocModal()">Next</button>';
	var modal_body=content;
	var modal_label= ev_before.title + " Documentation";

	 $('#doc_modal').modal('show');
     $('.doc-modal-footer').html(modal_footer);
     $('.doc-modal-body').html(modal_body);
     $('#doc_modal_Label').html(modal_label);
     $("#next-doc-modal").css('display', '');
     if( (events_before_index + 1) >= (events_before.length) ){
     	modal_footer = '<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>';
     	$('.doc-modal-footer').html(modal_footer);
 	 }
 	 else
 	 	events_before_index = events_before_index + 1;
};

//is called when next button on the modal is clicked.
function nextDocModal(){
	if(events_before_index >= events_before.length )
		return;
	if (events_before.length == 0) return;
	var ev_before = flashTeamsJSON["events"][getEventJSONIndex(events_before[events_before_index])];
	showDocModal(ev_before, events_before);

};

<|endoftext|>


<commit_before>Vps.onContentReady(function()
{
    var fadeComponents = Ext.query('div.vpsFadeElements');
    Ext.each(fadeComponents, function(c) {
        var selector = Ext.query('.fadeSelector', c)[0].value;
        var config = Ext.query('.fadeConfig', c); // optional
        if (config && config[0]) {
            config = Ext.decode(config[0].value);
        } else {
            config = { };
        }
        var textSelector = Ext.query('.textSelector', c); // optional
        if (textSelector[0]) {
            config.textSelector = textSelector[0].value;
        }

        config.selector = selector;
        config.selectorRoot = c;

        var fade = new Vps.Fade.Elements(config);
        fade.start();
    });
});

Ext.namespace("Vps.Fade");

Vps.Fade.Elements = function(cfg) {
    this.selector = cfg.selector;

    this.elementAccessLinks = false; // optional
    this.selectorRoot = document;
    this.fadeDuration = 1.5;
    this.easingFadeOut = 'easeIn';
    this.easingFadeIn = 'easeIn';
    this.fadeEvery = 7;
    this.startRandom = true;

    if (cfg.elementAccessLinks) this.elementAccessLinks = cfg.elementAccessLinks;
    if (cfg.selectorRoot) this.selectorRoot = cfg.selectorRoot;
    if (cfg.fadeDuration) this.fadeDuration = cfg.fadeDuration;
    if (cfg.easingFadeOut) this.easingFadeOut = cfg.easingFadeOut;
    if (cfg.easingFadeIn) this.easingFadeIn = cfg.easingFadeIn;
    if (cfg.fadeEvery) this.fadeEvery = cfg.fadeEvery;
    if (cfg.startRandom) this.startRandom = cfg.startRandom;

    this.fadeElements = Ext.query(this.selector, this.selectorRoot);

    if (this.startRandom) {
        this.active = Math.floor(Math.random() * this.fadeElements.length);
        if (this.active >= this.fadeElements.length) {
            this.active = this.fadeElements.length - 1;
        }

        this.next = this.active + 1;
        if (this.next >= this.fadeElements.length) {
            this.next = 0;
        }
    }

    var i = 0;
    Ext.each(this.fadeElements, function(e) {
        var ee = Ext.get(e);

        ee.addClass('vpsFadeElement');
        if (i != this.active) {
            ee.setStyle('display', 'none');
        } else {
            ee.setStyle('display', 'block');
        }
        i += 1;
    }, this);

    // wenn nur ein fade element existiert und im text element kein inhalt ist: ausblenden
    if (this.fadeElements.length == 1 && cfg.textSelector) {
        var dontShowEl = Ext.query(cfg.textSelector, this.selectorRoot);
        if (dontShowEl && dontShowEl[0]) {
            if (dontShowEl[0].innerHTML.replace(/\s/g, '') == '') {
                Ext.get(dontShowEl[0]).setDisplayed('none');
            }
        }
    }

    // create the element access link if needed
    if (this.elementAccessLinks && i >= 1) {
        this._createElementAccessLinks(this.active);
    }
};

Vps.Fade.Elements.prototype = {

    active: 0,
    next: 1,
    _firstFaded: false,
    _timeoutId: null,
    _elementAccessLinkEls: [ ],
    _playPause: 'play',
    _playPauseButton: null,

    start: function() {
        if (this.fadeElements.length <= 1) return;
        this._timeoutId = this.doFade.defer(this._getDeferTime(), this);
    },

    doFade: function() {
        if (this.fadeElements.length <= 1) return;

        var activeEl = Ext.get(this.fadeElements[this.active]);
        activeEl.fadeOut({ endOpacity: .0, easing: this.easingFadeOut, duration: this.fadeDuration, useDisplay: true });

        var nextEl = Ext.get(this.fadeElements[this.next]);
        nextEl.fadeIn({ endOpacity: 1.0, easing: this.easingFadeIn, duration: this.fadeDuration, useDisplay: true });

        if (this.elementAccessLinks) {
            if (this._elementAccessLinkEls[this.active].hasClass('elementAccessLinkActive')) {
                this._elementAccessLinkEls[this.active].removeClass('elementAccessLinkActive');
            }
            this._elementAccessLinkEls[this.next].addClass('elementAccessLinkActive');
        }

        this.active = this.next;
        this.next += 1;
        if (typeof this.fadeElements[this.next] == 'undefined') {
            this.next = 0;
        }

        this._timeoutId = this.doFade.defer(this._getDeferTime(), this);
    },

    pause: function() {
        if (this._timeoutId) window.clearTimeout(this._timeoutId);
        if (this._playPauseButton) {
            this._playPauseButton.removeClass('elementAccessPause');
            this._playPauseButton.addClass('elementAccessPlay');
        }
        this._playPause = 'pause';
    },

    play: function() {
        this.doFade();
        if (this._playPauseButton) {
            this._playPauseButton.removeClass('elementAccessPlay');
            this._playPauseButton.addClass('elementAccessPause');
        }
        this._playPause = 'play';
    },

    _getDeferTime: function() {
        if (!this._firstFaded) {
            this._firstFaded = true;
            return Math.ceil(this.fadeEvery * 1000) - Math.ceil(this.fadeDuration * 1000);
        } else {
            return Math.ceil(this.fadeEvery * 1000);
        }
    },

    _createElementAccessLinks: function(activeLinkIndex) {
        var ul = Ext.get(this.selectorRoot).createChild({ tag: 'ul', cls: 'elementAccessLinks' });

        // accessLinks and play / pause button if there are at least 2 images
        if (this.fadeElements.length >= 2) {
            var j = 0;
            Ext.each(this.fadeElements, function(e) {
                var a = ul.createChild({ tag: 'li' })
                    .createChild({
                        tag: 'a',
                        cls: 'elementAccessLink'+(activeLinkIndex==j ? ' elementAccessLinkActive' : ''),
                        html: '',
                        href: '#'
                    });
                a.on('click', function(ev, el, opt) {
                    ev.stopEvent();

                    if (this._timeoutId) {
                        window.clearTimeout(this._timeoutId);
                    }
                    this.next = opt.activateIdx;
                    this.doFade();
                    this.pause();

                }, this, { activateIdx: j });
                this._elementAccessLinkEls.push(a);
                j += 1;
            }, this);

            this._playPauseButton = ul.createChild({ tag: 'li' })
                .createChild({
                    tag: 'a',
                    cls: 'elementAccessPlayPauseButton elementAccessPause',
                    html: ' ',
                    href: '#'
                });
            this._playPauseButton.on('click', function(ev, el, opt) {
                ev.stopEvent();

                if (this._playPause == 'play') {
                    this.pause();
                } else if (this._playPause == 'pause') {
                    this.play();
                }
            }, this);
        }
    }
};
<commit_msg>Fading: durch letzten Bugfix moeglichen Fehler ausgebessert<commit_after>Vps.onContentReady(function()
{
    var fadeComponents = Ext.query('div.vpsFadeElements');
    Ext.each(fadeComponents, function(c) {
        var selector = Ext.query('.fadeSelector', c)[0].value;
        var config = Ext.query('.fadeConfig', c); // optional
        if (config && config[0]) {
            config = Ext.decode(config[0].value);
        } else {
            config = { };
        }
        var textSelector = Ext.query('.textSelector', c); // optional
        if (textSelector && textSelector[0]) {
            config.textSelector = textSelector[0].value;
        }

        config.selector = selector;
        config.selectorRoot = c;

        var fade = new Vps.Fade.Elements(config);
        fade.start();
    });
});

Ext.namespace("Vps.Fade");

Vps.Fade.Elements = function(cfg) {
    this.selector = cfg.selector;

    this.elementAccessLinks = false; // optional
    this.selectorRoot = document;
    this.fadeDuration = 1.5;
    this.easingFadeOut = 'easeIn';
    this.easingFadeIn = 'easeIn';
    this.fadeEvery = 7;
    this.startRandom = true;

    if (cfg.elementAccessLinks) this.elementAccessLinks = cfg.elementAccessLinks;
    if (cfg.selectorRoot) this.selectorRoot = cfg.selectorRoot;
    if (cfg.fadeDuration) this.fadeDuration = cfg.fadeDuration;
    if (cfg.easingFadeOut) this.easingFadeOut = cfg.easingFadeOut;
    if (cfg.easingFadeIn) this.easingFadeIn = cfg.easingFadeIn;
    if (cfg.fadeEvery) this.fadeEvery = cfg.fadeEvery;
    if (cfg.startRandom) this.startRandom = cfg.startRandom;

    this.fadeElements = Ext.query(this.selector, this.selectorRoot);

    if (this.startRandom) {
        this.active = Math.floor(Math.random() * this.fadeElements.length);
        if (this.active >= this.fadeElements.length) {
            this.active = this.fadeElements.length - 1;
        }

        this.next = this.active + 1;
        if (this.next >= this.fadeElements.length) {
            this.next = 0;
        }
    }

    var i = 0;
    Ext.each(this.fadeElements, function(e) {
        var ee = Ext.get(e);

        ee.addClass('vpsFadeElement');
        if (i != this.active) {
            ee.setStyle('display', 'none');
        } else {
            ee.setStyle('display', 'block');
        }
        i += 1;
    }, this);

    // wenn nur ein fade element existiert und im text element kein inhalt ist: ausblenden
    if (this.fadeElements.length == 1 && cfg.textSelector) {
        var dontShowEl = Ext.query(cfg.textSelector, this.selectorRoot);
        if (dontShowEl && dontShowEl[0]) {
            if (dontShowEl[0].innerHTML.replace(/\s/g, '') == '') {
                Ext.get(dontShowEl[0]).setDisplayed('none');
            }
        }
    }

    // create the element access link if needed
    if (this.elementAccessLinks && i >= 1) {
        this._createElementAccessLinks(this.active);
    }
};

Vps.Fade.Elements.prototype = {

    active: 0,
    next: 1,
    _firstFaded: false,
    _timeoutId: null,
    _elementAccessLinkEls: [ ],
    _playPause: 'play',
    _playPauseButton: null,

    start: function() {
        if (this.fadeElements.length <= 1) return;
        this._timeoutId = this.doFade.defer(this._getDeferTime(), this);
    },

    doFade: function() {
        if (this.fadeElements.length <= 1) return;

        var activeEl = Ext.get(this.fadeElements[this.active]);
        activeEl.fadeOut({ endOpacity: .0, easing: this.easingFadeOut, duration: this.fadeDuration, useDisplay: true });

        var nextEl = Ext.get(this.fadeElements[this.next]);
        nextEl.fadeIn({ endOpacity: 1.0, easing: this.easingFadeIn, duration: this.fadeDuration, useDisplay: true });

        if (this.elementAccessLinks) {
            if (this._elementAccessLinkEls[this.active].hasClass('elementAccessLinkActive')) {
                this._elementAccessLinkEls[this.active].removeClass('elementAccessLinkActive');
            }
            this._elementAccessLinkEls[this.next].addClass('elementAccessLinkActive');
        }

        this.active = this.next;
        this.next += 1;
        if (typeof this.fadeElements[this.next] == 'undefined') {
            this.next = 0;
        }

        this._timeoutId = this.doFade.defer(this._getDeferTime(), this);
    },

    pause: function() {
        if (this._timeoutId) window.clearTimeout(this._timeoutId);
        if (this._playPauseButton) {
            this._playPauseButton.removeClass('elementAccessPause');
            this._playPauseButton.addClass('elementAccessPlay');
        }
        this._playPause = 'pause';
    },

    play: function() {
        this.doFade();
        if (this._playPauseButton) {
            this._playPauseButton.removeClass('elementAccessPlay');
            this._playPauseButton.addClass('elementAccessPause');
        }
        this._playPause = 'play';
    },

    _getDeferTime: function() {
        if (!this._firstFaded) {
            this._firstFaded = true;
            return Math.ceil(this.fadeEvery * 1000) - Math.ceil(this.fadeDuration * 1000);
        } else {
            return Math.ceil(this.fadeEvery * 1000);
        }
    },

    _createElementAccessLinks: function(activeLinkIndex) {
        var ul = Ext.get(this.selectorRoot).createChild({ tag: 'ul', cls: 'elementAccessLinks' });

        // accessLinks and play / pause button if there are at least 2 images
        if (this.fadeElements.length >= 2) {
            var j = 0;
            Ext.each(this.fadeElements, function(e) {
                var a = ul.createChild({ tag: 'li' })
                    .createChild({
                        tag: 'a',
                        cls: 'elementAccessLink'+(activeLinkIndex==j ? ' elementAccessLinkActive' : ''),
                        html: '',
                        href: '#'
                    });
                a.on('click', function(ev, el, opt) {
                    ev.stopEvent();

                    if (this._timeoutId) {
                        window.clearTimeout(this._timeoutId);
                    }
                    this.next = opt.activateIdx;
                    this.doFade();
                    this.pause();

                }, this, { activateIdx: j });
                this._elementAccessLinkEls.push(a);
                j += 1;
            }, this);

            this._playPauseButton = ul.createChild({ tag: 'li' })
                .createChild({
                    tag: 'a',
                    cls: 'elementAccessPlayPauseButton elementAccessPause',
                    html: ' ',
                    href: '#'
                });
            this._playPauseButton.on('click', function(ev, el, opt) {
                ev.stopEvent();

                if (this._playPause == 'play') {
                    this.pause();
                } else if (this._playPause == 'pause') {
                    this.play();
                }
            }, this);
        }
    }
};
<|endoftext|>


<commit_before>require(['app/loading-manager',
				 'app/feedback-form-manager',
				 'classList'
				 'domReady!'],
	function(lm,feedback,classList) {
  'use strict';

	document.body.classList.add("require-loaded");
  lm.hide();
  feedback.init();

});<commit_msg>Fixes issue with /about module loading<commit_after>require(['app/loading-manager',
				 'app/feedback-form-manager',
				 'classList',
				 'domReady!'],
	function(lm,feedback,classList) {
  'use strict';

	document.body.classList.add("require-loaded");
  lm.hide();
  feedback.init();

});<|endoftext|>


<commit_before>(function(node) {
	/*!
	 * GameWindow
	 */

	var Player = node.Player;
	var PlayerList = node.PlayerList;
	var GameState = node.GameState;
	var GameMsg = node.GameMsg;
	var GameMsgGenerator = node.GameMsgGenerator;

	var Document = node.window.Document;

	GameWindow.prototype = new Document();
	GameWindow.prototype.constructor = GameWindow;

	// The widgets container
	GameWindow.prototype.widgets = {};

	function GameWindow() {

		if ('undefined' !== typeof node) {
			node.log('nodeWindow: loading...');
			var gsc = node.gsc || null;
			var game = node.game || null;
		}
		else {
			node.log('nodeWindow: nodeGame not found');
		}

		Document.call(this);

		this.frame = null;
		this.mainframe = 'mainframe';
		this.root = this.generateRandomRoot();

		this.state = GameState.iss.LOADED;
		this.areLoading = 0;

		var that = this;

		var listeners = function() {

			node.on('HIDE', function(id) {
				var el = that.getElementById(id);
				if (!el) {
					node.log('Cannot hide element ' + id);
					return;
				}
				el.style.visibility = 'hidden';
			});

			node.on('SHOW', function(id) {
				var el = that.getElementById(id);
				if (!el) {
					node.log('Cannot show element ' + id);
					return;
				}
				el.style.visibility = 'visible';
			});

			node.on('TOGGLE', function(id) {
				var el = that.getElementById(id);
				if (!el) {
					node.log('Cannot toggle element ' + id);
					return;
				}
				if (el.style.visibility === 'visible') {
					el.style.visibility = 'hidden';
				}
				else {
					el.style.visibility = 'visible';
				}
			});

			// Disable all the input forms found within a given id element
			node.on('INPUT_DISABLE', function(id) {
				that.toggleInputs(id, true);
			});

			// Disable all the input forms found within a given id element
			node.on('INPUT_ENABLE', function(id) {
				that.toggleInputs(id, false);
			});

			// Disable all the input forms found within a given id element
			node.on('INPUT_TOGGLE', function(id) {
				that.toggleInputs(id);
			});

		}();
	};

	// Overriding Document.write and Document.writeln
	GameWindow.prototype._write = Document.prototype.write;
	GameWindow.prototype._writeln = Document.prototype.writeln;

	// TODO: findLastElement
	GameWindow.prototype.findLastElement = function() {
		var el = this.frame;
		if (el) {
			el = this.frame.body || el;
		}
		else {
			el = document.body || document.lastElementChild;
		}
		return 	el;
	}

	GameWindow.prototype.write = function (text, root) {
		var root = root || this.findLastElement();
		if (!root) {
			node.log('Could not determine where writing', 'ERR');
		}
		return this._write(root, text);
	};

	GameWindow.prototype.writeln = function (text, root, br) {
		var root = root || this.findLastElement();
		if (!root) {
			node.log('Could not determine where writing', 'ERR');
		}
		return this._writeln(root, text, br);
	};

	/**
	 * Enable / Disable all input in a container with id @id.
	 * If no container with id @id is found, then the whole document is used.
	 *
	 * If @op is defined, all the input are set to @op, otherwise, the disabled
	 * property is toggled. (i.e. false means enable, true means disable)
	 *
	 */
	GameWindow.prototype.toggleInputs = function (id, op) {

		if ('undefined' !== typeof id) {
			var container = this.getElementById(id);
		}
		if ('undefined' === typeof container) {
			var container = this.frame.body;
		}

		var inputTags = ['button', 'select', 'textarea', 'input'];

		var j=0;
		for (;j<inputTags.length;j++) {
			var all = container.getElementsByTagName(inputTags[j]);
			var i=0;
			var max = all.length;
			for (; i < max; i++) {
				//node.log(all[i]);

				// If op is defined do that
				var state = op;

				// Otherwise toggle
				if (!state) {
					state = all[i].disabled ? false : true;
				}

				all[i].disabled = state;
			}
		}
	};

	GameWindow.prototype.generateRandomRoot = function () {
		// We assume that the BODY element always exists
		// TODO: Check if body element does not exist and add it
		var root = Math.floor(Math.random()*10000);
		return this.addElement('div', document.body, root);
	};

	GameWindow.prototype.generateHeader = function () {
		if (this.header) {
			this.header.innerHTML = '';
			this.header = null;
		}

		return this.addElement('div', this.root, 'gn_header');
	};

	GameWindow.prototype.setup = function (type){

		switch (type) {

		case 'MONITOR':

			// TODO: Check this
			node.node.removeListener('in.STATE');

			this.addWidget('NextPreviousState');
			this.addWidget('GameSummary');
			this.addWidget('StateDisplay');
			this.addWidget('StateBar');
			this.addWidget('DataBar');
			this.addWidget('MsgBar');
			this.addWidget('GameBoard');
			this.addWidget('ServerInfoDisplay');
			this.addWidget('Wall');
			//this.addWidget('GameTable');

			break;

		case 'PLAYER':

			//var maincss		= this.addCSS(this.root, 'style.css');
			this.header 	= this.generateHeader();
		    var mainframe 	= this.addIFrame(this.root,'mainframe');

		    this.addWidget('WaitScreen');

			break;
		}
		this.frame = window.frames[this.mainframe]; // there is no document yet
	};

	/**
	 * Returns the element with id 'id'. Looks first into the mainframe,
	 * and then into the rest of the page.
	 */
	GameWindow.prototype.getElementById = function (id) {
		var el = null;
		if (this.frame) {
			el = this.frame.getElementById(id);
		}
		if (!el) {
			el = document.getElementById(id);
		}
		return el;
	};

	GameWindow.prototype.getElementsByTagName = function (tag) {
		return (this.frame) ? this.frame.getElementsByTagName(tag) : document.getElementsByTagName(tag);
	};

	GameWindow.prototype.load = GameWindow.prototype.loadFrame = function (url, func, frame) {

 		this.state = GameState.iss.LOADING;
 		this.areLoading++; // keep track of nested call to loadFrame

		var frame =  frame || this.mainframe;
 		var that = this;

 		// First add the onload event listener
		var iframe = document.getElementById(frame);
		iframe.onload = function() {
			that.updateStatus(func,frame);
		};

		// Then update the frame location
		window.frames[frame].location = url;

 	};

 	GameWindow.prototype.updateStatus = function(func, frame) {
 		// Update the reference to the frame obj
		this.frame = window.frames[frame].document;

		if (func) {
    		func.call(node.game); // TODO: Pass the right this reference
    		//node.log('Frame Loaded correctly!');
    	}

		this.areLoading--;
		//node.log('ARE LOADING: ' + that.areLoading);
		if (this.areLoading === 0) {
			this.state = GameState.iss.LOADED;
			node.emit('WINDOW_LOADED');
		}
		else {
			node.log('Attempt to update state, before the window object was loaded', 'DEBUG');
		}
 	};

	GameWindow.prototype.getFrame = function() {
		return this.frame = window.frames['mainframe'].document;
	};

	// Header

	GameWindow.prototype.addHeader = function (root, id) {
		return this.addDiv(root,id);
	};

	/**
	 * Add a widget to the browser window.
	 * TODO: If an already existing id is provided, the existing element is deleted.
	 */
	GameWindow.prototype.addWidget = function (w, root, options) {
		var that = this;

		function appendFieldset(root, options, w) {
			if (!options) return root;
			var idFieldset = options.id || w.id + '_fieldset';
			var legend = options.legend || w.legend;
			return that.addFieldset(root, idFieldset, legend, options.attributes);
		};

		function attachListeners (options, w) {
			if (!options || !w) return;
			for (var i in options) {
				if (options.hasOwnProperty(i)) {
					if (JSUS.in_array(i, ['onclick', 'onfocus', 'onblur', 'onchange', 'onsubmit', 'onload', 'onunload', 'onmouseover'])) {
						w.getRoot()[i] = function() {
							options[i].call(w);
						}
					}
				}
			};
		};

		// Init default values
		var root = root || this.root;
		var options = options || {};

		// Check if it is a object (new gadget)
		// If it is a string is the name of an existing gadget
		if ('object' !== typeof w) {
			w = JSUS.getNestedValue(w,this.widgets);
			w = new w(options);
		}

		node.log('nodeWindow: registering gadget ' + w.name + ' v.' +  w.version);
		//try {
			// options exists and options.fieldset exist
			var fieldsetOptions = ('undefined' !== typeof options.fieldset) ? options.fieldset : w.fieldset;
			root = appendFieldset(root, fieldsetOptions, w);
			w.append(root);
			// nodeGame listeners
			w.listeners();
			// user listeners
			attachListeners(options, w);

//		}
//		catch(e){
//			throw 'Error while loading widget ' + w.name + ': ' + e;
//		}

		return w;
	};

	// Recipients

	GameWindow.prototype.addRecipientSelector = function (root, id) {

		var toSelector = document.createElement('select');
		toSelector.id = id;

		root.appendChild(toSelector);

		this.addStandardRecipients(toSelector);

		//this.toSels.push(toSelector);

		return toSelector;
	};

	GameWindow.prototype.addStandardRecipients = function (toSelector) {

		var opt = document.createElement('option');
		opt.value = 'ALL';
		opt.appendChild(document.createTextNode('ALL'));
		toSelector.appendChild(opt);

		var opt = document.createElement('option');
		opt.value = 'SERVER';
		opt.appendChild(document.createTextNode('SERVER'));
		toSelector.appendChild(opt);

	};

	GameWindow.prototype.populateRecipientSelector = function (toSelector, playerList) {

		if ('object' !==  typeof playerList || 'object' !== typeof toSelector) {
			return;
		}

		this.removeChildrenFromNode(toSelector);
		this.addStandardRecipients(toSelector);

		var opt;
		var pl = new PlayerList({}, playerList);

		try {
			pl.forEach( function(p) {
				opt = document.createElement('option');
				opt.value = p.id;
				opt.appendChild(document.createTextNode(p.name));
				toSelector.appendChild(opt);
			});
		}
		catch (e) {
			node.log('Bad Formatted Player List. Discarded. ' + p, 'ERR');
		}
	};

	// Actions

	GameWindow.prototype.addActionSelector = function (root, id) {

		var actionSelector = document.createElement('select');
		actionSelector.id = id;

		root.appendChild(actionSelector);
		this.populateSelect(actionSelector, node.actions);

		return actionSelector;
	};

	// States

	GameWindow.prototype.addStateSelector = function (root, id) {
		var stateSelector = this.addTextInput(root,id);
		return stateSelector;
	};

	GameWindow.prototype.addEventButton = function (event, text, root, id, attributes) {
		if (!event) return;
		if (!root) {
			var root = root || this.frame.body;
			root = root.lastElementChild || root;
		}

		var b = this.addButton(root, id, text, attributes);
		b.onclick = function () {
			node.emit(event);
		};
		return b;
	};

	/**
	 * Expose nodeGame to the global object
	 */
	node.window = new GameWindow();
	node.window.Document = Document; // Restoring Document constructor

})(window.node);<commit_msg>Creating addons. GameTimer and VisualTimer refactoring. GameWindow checks for dependencies when loading widgets<commit_after>(function(node) {
	/*!
	 * GameWindow
	 */

	var Player = node.Player;
	var PlayerList = node.PlayerList;
	var GameState = node.GameState;
	var GameMsg = node.GameMsg;
	var GameMsgGenerator = node.GameMsgGenerator;

	var Document = node.window.Document;

	GameWindow.prototype = new Document();
	GameWindow.prototype.constructor = GameWindow;

	// The widgets container
	GameWindow.prototype.widgets = {};

	function GameWindow() {

		if ('undefined' !== typeof node) {
			node.log('nodeWindow: loading...');
			var gsc = node.gsc || null;
			var game = node.game || null;
		}
		else {
			node.log('nodeWindow: nodeGame not found');
		}

		Document.call(this);

		this.frame = null;
		this.mainframe = 'mainframe';
		this.root = this.generateRandomRoot();

		this.state = GameState.iss.LOADED;
		this.areLoading = 0;

		var that = this;

		var listeners = function() {

			node.on('HIDE', function(id) {
				var el = that.getElementById(id);
				if (!el) {
					node.log('Cannot hide element ' + id);
					return;
				}
				el.style.visibility = 'hidden';
			});

			node.on('SHOW', function(id) {
				var el = that.getElementById(id);
				if (!el) {
					node.log('Cannot show element ' + id);
					return;
				}
				el.style.visibility = 'visible';
			});

			node.on('TOGGLE', function(id) {
				var el = that.getElementById(id);
				if (!el) {
					node.log('Cannot toggle element ' + id);
					return;
				}
				if (el.style.visibility === 'visible') {
					el.style.visibility = 'hidden';
				}
				else {
					el.style.visibility = 'visible';
				}
			});

			// Disable all the input forms found within a given id element
			node.on('INPUT_DISABLE', function(id) {
				that.toggleInputs(id, true);
			});

			// Disable all the input forms found within a given id element
			node.on('INPUT_ENABLE', function(id) {
				that.toggleInputs(id, false);
			});

			// Disable all the input forms found within a given id element
			node.on('INPUT_TOGGLE', function(id) {
				that.toggleInputs(id);
			});

		}();
	};

	// Overriding Document.write and Document.writeln
	GameWindow.prototype._write = Document.prototype.write;
	GameWindow.prototype._writeln = Document.prototype.writeln;

	// TODO: findLastElement
	GameWindow.prototype.findLastElement = function() {
		var el = this.frame;
		if (el) {
			el = this.frame.body || el;
		}
		else {
			el = document.body || document.lastElementChild;
		}
		return 	el;
	}

	GameWindow.prototype.write = function (text, root) {
		var root = root || this.findLastElement();
		if (!root) {
			node.log('Could not determine where writing', 'ERR');
		}
		return this._write(root, text);
	};

	GameWindow.prototype.writeln = function (text, root, br) {
		var root = root || this.findLastElement();
		if (!root) {
			node.log('Could not determine where writing', 'ERR');
		}
		return this._writeln(root, text, br);
	};

	/**
	 * Enable / Disable all input in a container with id @id.
	 * If no container with id @id is found, then the whole document is used.
	 *
	 * If @op is defined, all the input are set to @op, otherwise, the disabled
	 * property is toggled. (i.e. false means enable, true means disable)
	 *
	 */
	GameWindow.prototype.toggleInputs = function (id, op) {

		if ('undefined' !== typeof id) {
			var container = this.getElementById(id);
		}
		if ('undefined' === typeof container) {
			var container = this.frame.body;
		}

		var inputTags = ['button', 'select', 'textarea', 'input'];

		var j=0;
		for (;j<inputTags.length;j++) {
			var all = container.getElementsByTagName(inputTags[j]);
			var i=0;
			var max = all.length;
			for (; i < max; i++) {
				//node.log(all[i]);

				// If op is defined do that
				var state = op;

				// Otherwise toggle
				if (!state) {
					state = all[i].disabled ? false : true;
				}

				all[i].disabled = state;
			}
		}
	};

	GameWindow.prototype.generateRandomRoot = function () {
		// We assume that the BODY element always exists
		// TODO: Check if body element does not exist and add it
		var root = Math.floor(Math.random()*10000);
		return this.addElement('div', document.body, root);
	};

	GameWindow.prototype.generateHeader = function () {
		if (this.header) {
			this.header.innerHTML = '';
			this.header = null;
		}

		return this.addElement('div', this.root, 'gn_header');
	};

	GameWindow.prototype.setup = function (type){

		switch (type) {

		case 'MONITOR':

			// TODO: Check this
			node.node.removeListener('in.STATE');

			this.addWidget('NextPreviousState');
			this.addWidget('GameSummary');
			this.addWidget('StateDisplay');
			this.addWidget('StateBar');
			this.addWidget('DataBar');
			this.addWidget('MsgBar');
			this.addWidget('GameBoard');
			this.addWidget('ServerInfoDisplay');
			this.addWidget('Wall');
			//this.addWidget('GameTable');

			break;

		case 'PLAYER':

			//var maincss		= this.addCSS(this.root, 'style.css');
			this.header 	= this.generateHeader();
		    var mainframe 	= this.addIFrame(this.root,'mainframe');

		    this.addWidget('WaitScreen');

			break;
		}
		this.frame = window.frames[this.mainframe]; // there is no document yet
	};

	/**
	 * Returns the element with id 'id'. Looks first into the mainframe,
	 * and then into the rest of the page.
	 */
	GameWindow.prototype.getElementById = function (id) {
		var el = null;
		if (this.frame) {
			el = this.frame.getElementById(id);
		}
		if (!el) {
			el = document.getElementById(id);
		}
		return el;
	};

	GameWindow.prototype.getElementsByTagName = function (tag) {
		return (this.frame) ? this.frame.getElementsByTagName(tag) : document.getElementsByTagName(tag);
	};

	GameWindow.prototype.load = GameWindow.prototype.loadFrame = function (url, func, frame) {

 		this.state = GameState.iss.LOADING;
 		this.areLoading++; // keep track of nested call to loadFrame

		var frame =  frame || this.mainframe;
 		var that = this;

 		// First add the onload event listener
		var iframe = document.getElementById(frame);
		iframe.onload = function() {
			that.updateStatus(func,frame);
		};

		// Then update the frame location
		window.frames[frame].location = url;

 	};

 	GameWindow.prototype.updateStatus = function(func, frame) {
 		// Update the reference to the frame obj
		this.frame = window.frames[frame].document;

		if (func) {
    		func.call(node.game); // TODO: Pass the right this reference
    		//node.log('Frame Loaded correctly!');
    	}

		this.areLoading--;
		//node.log('ARE LOADING: ' + that.areLoading);
		if (this.areLoading === 0) {
			this.state = GameState.iss.LOADED;
			node.emit('WINDOW_LOADED');
		}
		else {
			node.log('Attempt to update state, before the window object was loaded', 'DEBUG');
		}
 	};

	GameWindow.prototype.getFrame = function() {
		return this.frame = window.frames['mainframe'].document;
	};

	// Header

	GameWindow.prototype.addHeader = function (root, id) {
		return this.addDiv(root,id);
	};

	/**
	 * Add a widget to the browser window.
	 * TODO: If an already existing id is provided, the existing element is deleted.
	 */
	GameWindow.prototype.addWidget = function (w, root, options) {
		var that = this;

		function appendFieldset(root, options, w) {
			if (!options) return root;
			var idFieldset = options.id || w.id + '_fieldset';
			var legend = options.legend || w.legend;
			return that.addFieldset(root, idFieldset, legend, options.attributes);
		};

		function attachListeners (options, w) {
			if (!options || !w) return;
			for (var i in options) {
				if (options.hasOwnProperty(i)) {
					if (JSUS.in_array(i, ['onclick', 'onfocus', 'onblur', 'onchange', 'onsubmit', 'onload', 'onunload', 'onmouseover'])) {
						w.getRoot()[i] = function() {
							options[i].call(w);
						}
					}
				}
			};
		};

		// Init default values
		var root = root || this.root;
		var options = options || {};

		// Check if it is a object (new gadget)
		// If it is a string is the name of an existing gadget
		// In this case a dependencies check is done
		if ('object' !== typeof w) {
			w = JSUS.getNestedValue(w, this.widgets);

			if (this.checkDependencies(w)) {
				w = new w(options);
			}
			else {
				return false;
			}

		}

		node.log('nodeWindow: registering gadget ' + w.name + ' v.' +  w.version);
		//try {
			// options exists and options.fieldset exist
			var fieldsetOptions = ('undefined' !== typeof options.fieldset) ? options.fieldset : w.fieldset;
			root = appendFieldset(root, fieldsetOptions, w);
			w.append(root);
			// nodeGame listeners
			w.listeners();
			// user listeners
			attachListeners(options, w);

//		}
//		catch(e){
//			throw 'Error while loading widget ' + w.name + ': ' + e;
//		}

		return w;
	};

	// TODO: Check for version and other constraints.
	GameWindow.prototype.checkDependencies = function (w, quiet) {
		if (!w.dependencies) return;

		var errMsg = function (w, d) {
			var name = w.name || w.id;// || w.toString();
			node.log(d + ' not found. ' + name + ' cannot be loaded.', 'ERR');
		}

		var d = w.dependencies;
		for (var i in d) {
			if (d.hasOwnProperty(i)) {
				if (!window[i] && !node[i]) {
					if (!quiet) {
						errMsg(w, i);
					}
					return false;
				}
			}
		}

		return true;
	};
	// Recipients

	GameWindow.prototype.addRecipientSelector = function (root, id) {

		var toSelector = document.createElement('select');
		toSelector.id = id;

		root.appendChild(toSelector);

		this.addStandardRecipients(toSelector);

		//this.toSels.push(toSelector);

		return toSelector;
	};

	GameWindow.prototype.addStandardRecipients = function (toSelector) {

		var opt = document.createElement('option');
		opt.value = 'ALL';
		opt.appendChild(document.createTextNode('ALL'));
		toSelector.appendChild(opt);

		var opt = document.createElement('option');
		opt.value = 'SERVER';
		opt.appendChild(document.createTextNode('SERVER'));
		toSelector.appendChild(opt);

	};

	GameWindow.prototype.populateRecipientSelector = function (toSelector, playerList) {

		if ('object' !==  typeof playerList || 'object' !== typeof toSelector) {
			return;
		}

		this.removeChildrenFromNode(toSelector);
		this.addStandardRecipients(toSelector);

		var opt;
		var pl = new PlayerList({}, playerList);

		try {
			pl.forEach( function(p) {
				opt = document.createElement('option');
				opt.value = p.id;
				opt.appendChild(document.createTextNode(p.name));
				toSelector.appendChild(opt);
			});
		}
		catch (e) {
			node.log('Bad Formatted Player List. Discarded. ' + p, 'ERR');
		}
	};

	// Actions

	GameWindow.prototype.addActionSelector = function (root, id) {

		var actionSelector = document.createElement('select');
		actionSelector.id = id;

		root.appendChild(actionSelector);
		this.populateSelect(actionSelector, node.actions);

		return actionSelector;
	};

	// States

	GameWindow.prototype.addStateSelector = function (root, id) {
		var stateSelector = this.addTextInput(root,id);
		return stateSelector;
	};

	GameWindow.prototype.addEventButton = function (event, text, root, id, attributes) {
		if (!event) return;
		if (!root) {
			var root = root || this.frame.body;
			root = root.lastElementChild || root;
		}

		var b = this.addButton(root, id, text, attributes);
		b.onclick = function () {
			node.emit(event);
		};
		return b;
	};

	/**
	 * Expose nodeGame to the global object
	 */
	node.window = new GameWindow();
	node.window.Document = Document; // Restoring Document constructor

})(window.node);<|endoftext|>


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

/**
 * Most test cases for format*() APIs are covered by xUnit.
 * xUnit only supports locale en-US, so component tests are testing
 * for localized string.
 */
({ // eslint-disable-line no-unused-expressions
    /**
     * Test $A.localizationService.parseDateTime with the default locale
     */
    testParseDateTime: {
        test: function() {
            var format =  "MMM DD, YYYY h:mm:ss A";
            var dateString = "Sep 23, 2014 4:30:00 PM";

            var date = $A.localizationService.parseDateTime(dateString, format);

            // date object contains browser timezone offset, so formatting the date to verify
            var actual = $A.localizationService.formatDateTime(date, format);
            $A.test.assertEquals(dateString, actual, "parseDateTime() returns a incorrect date");
        }
    },

    /**
     * Test $A.localizationService.parseDateTimeUTC with the default
     * locale
     */
    testParseDateTimeUTC: {
        test: function() {
            var format =  "MMM DD, YYYY h:mm:ss A";
            var dateString = "Sep 23, 2014 4:30:00 PM";

            var date = $A.localizationService.parseDateTimeUTC(dateString, format);

            var actual = $A.localizationService.formatDateTimeUTC(date, format);
            $A.test.assertEquals(dateString, actual, "parseDateTimeUTC() returns a incorrect date");
        }
    },

    /**
     * Test $A.localizationService.formatDate with "fr_FR" and "th"
     * locales.
     */
    testFormatDateToLocalizedString: {
        test: [function testFrFR() {
            var expected = "mars 12, 2014 3:02:03 AM";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatDate(date, format, "fr_FR");

            $A.test.assertEquals(expected, actual, "formatDate() returns an unexpected date string");
        }, function testyyyyWithTh() {
            var expected = "มี.ค. 12, 2014 3:02:03 ก่อนเที่ยง";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatDate(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDate() for the 'th' locale and format with yyyy returns an unexpected date string");
        }, function testyyWithTh() {
            var expected = "มี.ค. 12, 14 3:02:03 ก่อนเที่ยง";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yy h:mm:ss A";

            var actual = $A.localizationService.formatDate(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDate() for the 'th' locale and format with yy returns an unexpected date string");
        }]
    },

    /**
     * Test $A.localizationService.formatDateUTC with "fr_FR" and "th"
     * locales.
     */
    testFormatDateUTCToLocalizedString: {
        test: [function testFrFR() {
            var expected = "mars 12, 2014 3:22:30 AM";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatDateUTC(date, format, "fr_FR");

            $A.test.assertEquals(expected, actual, "formatDateUTC() for the 'fr_FR' returns an unexpected date string");
        }, function testyyyyWithTh() {
            var expected = "มี.ค. 12, 2014 3:22:30 ก่อนเที่ยง";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatDateUTC(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDateUTC() for the 'th' locale and format with yyyy returns an unexpected date string");
        }, function testyyWithTh() {
            var expected = "มี.ค. 12, 14 3:22:30 ก่อนเที่ยง";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yy h:mm:ss A";

            var actual = $A.localizationService.formatDateUTC(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDateUTC() for the 'th' locale and format with yy returns an unexpected date string");
        }]
    },

    /**
     * Test $A.localizationService.formatDateTime with "fr_FR" and "th"
     * locales.
     */
    testFormatDateTimeToLocalizedString: {
        test: [function testFrFR() {
            var expected = "mars 12, 2014 3:02:03 AM";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatDateTime(date, format, "fr_FR");

            $A.test.assertEquals(expected, actual, "formatDateTime() returns an unexpected date string");
        }, function testyyyyWithTh() {
            var expected = "มี.ค. 12, 2014 3:02:03 ก่อนเที่ยง";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatDateTime(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDateTime() for the 'th' locale and format with yyyy returns an unexpected date string");
        }, function testyyWithTh() {
            var expected = "มี.ค. 12, 14 3:02:03 ก่อนเที่ยง";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yy h:mm:ss A";

            var actual = $A.localizationService.formatDateTime(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDateTime() for the 'th' locale and format with yy returns an unexpected date string");
        }]
    },

    /**
     * Test $A.localizationService.formatDateTimeUTC with "fr_FR" and
     * "th" locales.
     */
    testFormatDateTimeUTCToLocalizedString: {
        test: [function testFrFR() {
            var expected = "mars 12, 2014 3:22:30 AM";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatDateTimeUTC(date, format, "fr_FR");

            $A.test.assertEquals(expected, actual, "formatDateTimeUTC() for the 'fr_FR' returns an unexpected date string");
        }, function testyyyyWithTh() {
            var expected = "มี.ค. 12, 2014 3:22:30 ก่อนเที่ยง";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatDateTimeUTC(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDateTimeUTC() for the 'th' locale and format with yyyy returns an unexpected date string");
        }, function testyyWithTh() {
            var expected = "มี.ค. 12, 14 3:22:30 ก่อนเที่ยง";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yy h:mm:ss A";

            var actual = $A.localizationService.formatDateTimeUTC(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDateTimeUTC() for the 'th' locale and format with yy returns an unexpected date string");
        }]
    },

    /**
     * Test $A.localizationService.formatTime with "fr_FR" and "th"
     * locales.
     */
    testFormatTimeToLocalizedString: {
        test: [function testFrFR() {
            var expected = "mars 12, 2014 3:02:03 AM";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatTime(date, format, "fr_FR");

            $A.test.assertEquals(expected, actual, "formatTime() returns an unexpected date string");
        }, function testyyyyWithTh() {
            var expected = "มี.ค. 12, 2014 3:02:03 ก่อนเที่ยง";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatTime(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatTime() for the 'th' locale and format with yyyy returns an unexpected date string");
        }, function testyyWithTh() {
            var expected = "มี.ค. 12, 14 3:02:03 ก่อนเที่ยง";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yy h:mm:ss A";

            var actual = $A.localizationService.formatTime(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatTime() for the 'th' locale and format with yy returns an unexpected date string");
        },
        /**
         * Special case for ja. Intl.DateTimeFormat does not respect 2-digit for hour.
         */
        function testWithJaJP() {
            var expected = "03:02:03.000";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "HH:mm:ss.SSS";

            var actual = $A.localizationService.formatTime(date, format, "ja_JP");

            $A.test.assertEquals(expected, actual, "formatDateTime() returns an unexpected date string");
        }]
    },

    /**
     * Test $A.localizationService.formatTimeUTC with "fr_FR" and "th"
     * locales.
     */
    testFormatTimeUTCToLocalizedString: {
        test: [function testFrFR() {
            var expected = "mars 12, 2014 3:22:30 AM";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatTimeUTC(date, format, "fr_FR");

            $A.test.assertEquals(expected, actual, "formatTimeUTC() for the 'fr_FR' returns an unexpected date string");
        }, function testyyyyWithTh() {
            var expected = "มี.ค. 12, 2014 3:22:30 ก่อนเที่ยง";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatTimeUTC(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatTimeUTC() for the 'th' locale and format with yyyy returns an unexpected date string");
        }, function testyyWithTh() {
            var expected = "มี.ค. 12, 14 3:22:30 ก่อนเที่ยง";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yy h:mm:ss A";

            var actual = $A.localizationService.formatTimeUTC(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatTimeUTC() for the 'th' locale and format with yy returns an unexpected date string");
        }]
    }
})<commit_msg>Switched to testing with a translation that is the same across all of the browsers (#3505)<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Most test cases for format*() APIs are covered by xUnit. xUnit only supports
 * locale en-US, so component tests are testing for localized string.
 */
({ // eslint-disable-line no-unused-expressions
    /**
     * Test $A.localizationService.parseDateTime with the default locale
     */
    testParseDateTime: {
        test: function() {
            var format =  "MMM DD, YYYY h:mm:ss A";
            var dateString = "Sep 23, 2014 4:30:00 PM";

            var date = $A.localizationService.parseDateTime(dateString, format);

            // date object contains browser timezone offset, so formatting the date to verify
            var actual = $A.localizationService.formatDateTime(date, format);
            $A.test.assertEquals(dateString, actual, "parseDateTime() returns a incorrect date");
        }
    },

    /**
     * Test $A.localizationService.parseDateTimeUTC with the default
     * locale
     */
    testParseDateTimeUTC: {
        test: function() {
            var format =  "MMM DD, YYYY h:mm:ss A";
            var dateString = "Sep 23, 2014 4:30:00 PM";

            var date = $A.localizationService.parseDateTimeUTC(dateString, format);

            var actual = $A.localizationService.formatDateTimeUTC(date, format);
            $A.test.assertEquals(dateString, actual, "parseDateTimeUTC() returns a incorrect date");
        }
    },

    /**
     * Test $A.localizationService.formatDate with "fr_FR" and "th"
     * locales.
     */
    testFormatDateToLocalizedString: {
        test: [function testFrFR() {
            var expected = "mars 12, 2014 3:02:03 AM";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatDate(date, format, "fr_FR");

            $A.test.assertEquals(expected, actual, "formatDate() returns an unexpected date string");
        }, function testyyyyWithTh() {
            var expected = "มี.ค. 12, 2014 03:02:03";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yyyy kk:mm:ss";

            var actual = $A.localizationService.formatDate(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDate() for the 'th' locale and format with yyyy returns an unexpected date string");
        }, function testyyWithTh() {
            var expected = "มี.ค. 12, 14 03:02:03";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yy kk:mm:ss";

            var actual = $A.localizationService.formatDate(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDate() for the 'th' locale and format with yy returns an unexpected date string");
        }]
    },

    /**
     * Test $A.localizationService.formatDateUTC with "fr_FR" and "th"
     * locales.
     */
    testFormatDateUTCToLocalizedString: {
        test: [function testFrFR() {
            var expected = "mars 12, 2014 3:22:30 AM";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatDateUTC(date, format, "fr_FR");

            $A.test.assertEquals(expected, actual, "formatDateUTC() for the 'fr_FR' returns an unexpected date string");
        }, function testyyyyWithTh() {
            var expected = "มี.ค. 12, 2014 03:22:30";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yyyy kk:mm:ss";

            var actual = $A.localizationService.formatDateUTC(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDateUTC() for the 'th' locale and format with yyyy returns an unexpected date string");
        }, function testyyWithTh() {
            var expected = "มี.ค. 12, 14 03:22:30";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yy kk:mm:ss";

            var actual = $A.localizationService.formatDateUTC(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDateUTC() for the 'th' locale and format with yy returns an unexpected date string");
        }]
    },

    /**
     * Test $A.localizationService.formatDateTime with "fr_FR" and "th"
     * locales.
     */
    testFormatDateTimeToLocalizedString: {
        test: [function testFrFR() {
            var expected = "mars 12, 2014 3:02:03 AM";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatDateTime(date, format, "fr_FR");

            $A.test.assertEquals(expected, actual, "formatDateTime() returns an unexpected date string");
        }, function testyyyyWithTh() {
            var expected = "มี.ค. 12, 2014 03:02:03";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yyyy kk:mm:ss";

            var actual = $A.localizationService.formatDateTime(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDateTime() for the 'th' locale and format with yyyy returns an unexpected date string");
        }, function testyyWithTh() {
            var expected = "มี.ค. 12, 14 03:02:03";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yy kk:mm:ss";

            var actual = $A.localizationService.formatDateTime(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDateTime() for the 'th' locale and format with yy returns an unexpected date string");
        }]
    },

    /**
     * Test $A.localizationService.formatDateTimeUTC with "fr_FR" and
     * "th" locales.
     */
    testFormatDateTimeUTCToLocalizedString: {
        test: [function testFrFR() {
            var expected = "mars 12, 2014 3:22:30 AM";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatDateTimeUTC(date, format, "fr_FR");

            $A.test.assertEquals(expected, actual, "formatDateTimeUTC() for the 'fr_FR' returns an unexpected date string");
        }, function testyyyyWithTh() {
            var expected = "มี.ค. 12, 2014 03:22:30";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yyyy kk:mm:ss";

            var actual = $A.localizationService.formatDateTimeUTC(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDateTimeUTC() for the 'th' locale and format with yyyy returns an unexpected date string");
        }, function testyyWithTh() {
            var expected = "มี.ค. 12, 14 03:22:30";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yy kk:mm:ss";

            var actual = $A.localizationService.formatDateTimeUTC(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatDateTimeUTC() for the 'th' locale and format with yy returns an unexpected date string");
        }]
    },

    /**
     * Test $A.localizationService.formatTime with "fr_FR" and "th"
     * locales.
     */
    testFormatTimeToLocalizedString: {
        test: [function testFrFR() {
            var expected = "mars 12, 2014 3:02:03 AM";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatTime(date, format, "fr_FR");

            $A.test.assertEquals(expected, actual, "formatTime() returns an unexpected date string");
        }, function testyyyyWithTh() {
            var expected = "มี.ค. 12, 2014 03:02:03";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yyyy kk:mm:ss";

            var actual = $A.localizationService.formatTime(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatTime() for the 'th' locale and format with yyyy returns an unexpected date string");
        }, function testyyWithTh() {
            var expected = "มี.ค. 12, 14 03:02:03";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "MMM dd, yy kk:mm:ss";

            var actual = $A.localizationService.formatTime(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatTime() for the 'th' locale and format with yy returns an unexpected date string");
        },
        /**
         * Special case for ja. Intl.DateTimeFormat does not respect 2-digit for hour.
         */
        function testWithJaJP() {
            var expected = "03:02:03.000";
            var date = new Date(2014, 2, 12, 3, 2, 3);
            var format = "HH:mm:ss.SSS";

            var actual = $A.localizationService.formatTime(date, format, "ja_JP");

            $A.test.assertEquals(expected, actual, "formatDateTime() returns an unexpected date string");
        }]
    },

    /**
     * Test $A.localizationService.formatTimeUTC with "fr_FR" and "th"
     * locales.
     */
    testFormatTimeUTCToLocalizedString: {
        test: [function testFrFR() {
            var expected = "mars 12, 2014 3:22:30 AM";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yyyy h:mm:ss A";

            var actual = $A.localizationService.formatTimeUTC(date, format, "fr_FR");

            $A.test.assertEquals(expected, actual, "formatTimeUTC() for the 'fr_FR' returns an unexpected date string");
        }, function testyyyyWithTh() {
            var expected = "มี.ค. 12, 2014 03:22:30";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yyyy kk:mm:ss";

            var actual = $A.localizationService.formatTimeUTC(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatTimeUTC() for the 'th' locale and format with yyyy returns an unexpected date string");
        }, function testyyWithTh() {
            var expected = "มี.ค. 12, 14 03:22:30";
            var date = new Date(Date.UTC(2014, 2, 12, 3, 22, 30));
            var format = "MMM dd, yy kk:mm:ss";

            var actual = $A.localizationService.formatTimeUTC(date, format, "th");

            $A.test.assertEquals(expected, actual, "formatTimeUTC() for the 'th' locale and format with yy returns an unexpected date string");
        }]
    }
})<|endoftext|>


<commit_before>define([
  'extensions/collections/matrix'
],
function (MatrixCollection) {

  var CategoriesCollection = MatrixCollection.extend({
    queryParams: function () {
      return {
        collect: this.options.valueAttr,
        period: this.options.period,
        group_by: this.options.category,
        filter_by: this.options.filterBy ? this.options.filterBy : [],
        duration: this.options.duration ? this.options.duration : null
      };
    },

    parse: function (response) {
      var data = response.data,
        category = this.options.category,
        valueAttr = this.options.valueAttr;

      if (this.options.showTotalLines) {

        var totalSeries = {};
        totalSeries[category] = "Total";
        totalSeries[valueAttr] = 0.0;

        var totalValues = [];
        var tmp = {};

        _.each(response.data, function(d) {
          _.each(d.values, function (obj) {
            if (tmp[obj._start_at]) {
              if ((valueAttr in obj) && (obj[valueAttr] !== null)) {
                tmp[obj._start_at][valueAttr] += obj[valueAttr];
              }
            } else {
              tmp[obj._start_at] = {_end_at: obj._end_at};
              tmp[obj._start_at][valueAttr] = (valueAttr in obj) ? obj[valueAttr] : 0;
            }
          });
        });
        _.each(tmp, function (v, i) {
            var t = {_start_at: i, _end_at: v._end_at};
            t[valueAttr] = v[valueAttr];
            totalValues.push(t);
        });

        totalSeries.values = totalValues;
        data.push(totalSeries);
      }

      return _.map(this.options.seriesList, function (series) {
        var dataSeries = _.find(data, function (d) {
          return d[category] === series.id;
        });

        return _.extend({}, series, {
          values: dataSeries.values
        });
      });
    },

    getDataByTableFormat: function () {
      if (this.options.axisLabels && this.options.seriesList && this.options.period) {
        var allTables = [],
          dateRow = this.options.axisLabels.x.label + ' (' + this.options.period + ')',
          dateKey = this.options.axisLabels.x.key,
          series = this.options.seriesList,
          seriesLength = series.length,
          seriesData = this.options.axisLabels.y.key,
          tableHeadings = [];

        tableHeadings.push(dateRow);

        _.each(series, function (item) {
          tableHeadings.push(item.title);
        });

        allTables.push(tableHeadings);
        _.each(this.models, function (collectionOfCollections, index) {
          var collection = collectionOfCollections.get('values');

          if (collection.length && index === 0) {
            _.each(collection.models, function (model) {
              var tableRow = new Array(seriesLength + 1);
              tableRow[0] = this.getMoment(model.get(dateKey))
                .format(this.periods[this.options.period].format.longhand);
              tableRow[1] = model.get(seriesData);

              allTables.push(tableRow);
            }, this);
          } else {
            _.each(collection.models, function (model, modelIndex) {
              var tableRow = allTables[modelIndex + 1];
              tableRow[index + 1] = model.get(seriesData);
            });
          }
        }, this);

        return allTables;
      }

      return MatrixCollection.prototype.getDataByTableFormat.apply(this, arguments);
    }

  });

  return CategoriesCollection;
});
<commit_msg>Fix JSLint errors<commit_after>define([
  'extensions/collections/matrix'
],
function (MatrixCollection) {

  var CategoriesCollection = MatrixCollection.extend({
    queryParams: function () {
      return {
        collect: this.options.valueAttr,
        period: this.options.period,
        group_by: this.options.category,
        filter_by: this.options.filterBy ? this.options.filterBy : [],
        duration: this.options.duration ? this.options.duration : null
      };
    },

    parse: function (response) {
      var data = response.data,
        category = this.options.category,
        valueAttr = this.options.valueAttr;

      if (this.options.showTotalLines) {

        var totalSeries = {};
        totalSeries[category] = 'Total';
        totalSeries[valueAttr] = 0.0;

        var totalValues = [];
        var tmp = {};

        _.each(response.data, function (d) {
          _.each(d.values, function (obj) {
            if (tmp[obj._start_at]) {
              if ((valueAttr in obj) && (obj[valueAttr] !== null)) {
                tmp[obj._start_at][valueAttr] += obj[valueAttr];
              }
            } else {
              tmp[obj._start_at] = {_end_at: obj._end_at};
              tmp[obj._start_at][valueAttr] = (valueAttr in obj) ? obj[valueAttr] : 0;
            }
          });
        });
        _.each(tmp, function (v, i) {
            var t = {_start_at: i, _end_at: v._end_at};
            t[valueAttr] = v[valueAttr];
            totalValues.push(t);
          });

        totalSeries.values = totalValues;
        data.push(totalSeries);
      }

      return _.map(this.options.seriesList, function (series) {
        var dataSeries = _.find(data, function (d) {
          return d[category] === series.id;
        });

        return _.extend({}, series, {
          values: dataSeries.values
        });
      });
    },

    getDataByTableFormat: function () {
      if (this.options.axisLabels && this.options.seriesList && this.options.period) {
        var allTables = [],
          dateRow = this.options.axisLabels.x.label + ' (' + this.options.period + ')',
          dateKey = this.options.axisLabels.x.key,
          series = this.options.seriesList,
          seriesLength = series.length,
          seriesData = this.options.axisLabels.y.key,
          tableHeadings = [];

        tableHeadings.push(dateRow);

        _.each(series, function (item) {
          tableHeadings.push(item.title);
        });

        allTables.push(tableHeadings);
        _.each(this.models, function (collectionOfCollections, index) {
          var collection = collectionOfCollections.get('values');

          if (collection.length && index === 0) {
            _.each(collection.models, function (model) {
              var tableRow = new Array(seriesLength + 1);
              tableRow[0] = this.getMoment(model.get(dateKey))
                .format(this.periods[this.options.period].format.longhand);
              tableRow[1] = model.get(seriesData);

              allTables.push(tableRow);
            }, this);
          } else {
            _.each(collection.models, function (model, modelIndex) {
              var tableRow = allTables[modelIndex + 1];
              tableRow[index + 1] = model.get(seriesData);
            });
          }
        }, this);

        return allTables;
      }

      return MatrixCollection.prototype.getDataByTableFormat.apply(this, arguments);
    }

  });

  return CategoriesCollection;
});
<|endoftext|>


<commit_before>/*
 * Simplified interface to dust and filesystem templates
 * Copyright (C) 2011 by Jaakko-Heikki Heusala <jheusala@iki.fi>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

module.exports = (function() {
	var dust = require('dust'),
	    fs = require('fs'),
	    path = require('path'),
	    foreach = require('snippets').foreach,
	    compiled = {},
		dirs = [],
		mod = {};

	/* Returns the directory where file exists */
	function search_dir(file) {
		var matches = [];
		foreach(dirs).do(function(dir) {
			if(path.existsSync(dir+"/"+file)) matches.push(dir);
		});
		if(matches.length != 0) return matches.shift();
	}

	/* Compile template from filesystem */
	function do_compile(file, name) {
		var name = name || file;
		if(!file) throw new Error("file not defined");
		if(compiled[name]) return compiled[name];
		var source = fs.readFileSync(file, "UTF-8");
		    compiled[name] = dust.compile(source, name);
		//console.log("Template compiled: " + file + " as " + name);
		return compiled[name];
	}

	/* Load template from filesystem */
	function do_load(file, name) {
		var name = name || file;
		if(!file) throw new Error("file not defined");
		var c = do_compile(file, name);
		dust.loadSource(c);
		//console.log("Template loaded: " + file + " as " + name);
		return c;
	}

	/* Create context for dust */
	function do_create_context(context) {
		var context = context || {};

		if(!context.replace) {
			context.replace = (function(chunk, context, bodies, params) {
					return chunk.tap(function(data) {
						return (params.from && params.to && (data === params.from) ) ? params.to : data;
					}).render(bodies.block, context).untap();
				});
		}

		if(!context.toFixed) {
			context.toFixed = (function(chunk, context, bodies, params) {
					return chunk.tap(function(data) {
						return parseFloat(data).toFixed(params.x || 0);
					}).render(bodies.block, context).untap();
				}); // end of context
		}

		return context;
	}

	/* Render template with dust */
	function do_render(name, context, callback) {
		var context = do_create_context(context),
		    dir;
		if(!compiled[name]) {
			dir = search_dir(name);
			if(!dir) {
				callback("Could not find template: "+name);
				return;
			}
			do_load(dir+"/"+name, name);
		}
		//console.log("Rendering template: " + name);
		dust.render(name, context, callback);
	}

	/* Set directories to search files */
	function do_dirs() {
		foreach(arguments).do(function(dir) {
			dirs.push(dir);
			fs.readdir(dir, function(err, files) {
				if(err) {
					//console.log(err);
					return;
				}
				foreach(files).do(function(file) {
					if(path.extname(file) != ".dust") return;
					do_load(dir+"/"+file, file);
				});
			});
		});
	}

	/* Export functions */

	mod.search_dir = search_dir;
	mod.compile = do_compile;
	mod.load = do_load;

	mod.render = do_render;
	mod.dirs = do_dirs;

	return mod;
})();

/* EOF */
<commit_msg>Debug can now be enabled or disabled by dustfs.debug(true|false)<commit_after>/*
 * Simplified interface to dust and filesystem templates
 * Copyright (C) 2011 by Jaakko-Heikki Heusala <jheusala@iki.fi>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

module.exports = (function() {
	var debug = false,
	    dust = require('dust'),
	    fs = require('fs'),
	    path = require('path'),
	    foreach = require('snippets').foreach,
	    compiled = {},
		dirs = [],
		mod = {};

	/* Returns the directory where file exists */
	function search_dir(file) {
		var matches = [];
		foreach(dirs).do(function(dir) {
			if(path.existsSync(dir+"/"+file)) matches.push(dir);
		});
		if(matches.length != 0) return matches.shift();
	}

	/* Compile template from filesystem */
	function do_compile(file, name) {
		var name = name || file;
		if(!file) throw new Error("file not defined");
		if(compiled[name]) return compiled[name];
		var source = fs.readFileSync(file, "UTF-8");
		    compiled[name] = dust.compile(source, name);
		if(debug) console.log("Template compiled: " + file + " as " + name);
		return compiled[name];
	}

	/* Load template from filesystem */
	function do_load(file, name) {
		var name = name || file;
		if(!file) throw new Error("file not defined");
		var c = do_compile(file, name);
		dust.loadSource(c);
		if(debug) console.log("Template loaded: " + file + " as " + name);
		return c;
	}

	/* Create context for dust */
	function do_create_context(context) {
		var context = context || {};

		if(!context.replace) {
			context.replace = (function(chunk, context, bodies, params) {
					return chunk.tap(function(data) {
						return (params.from && params.to && (data === params.from) ) ? params.to : data;
					}).render(bodies.block, context).untap();
				});
		}

		if(!context.toFixed) {
			context.toFixed = (function(chunk, context, bodies, params) {
					return chunk.tap(function(data) {
						return parseFloat(data).toFixed(params.x || 0);
					}).render(bodies.block, context).untap();
				}); // end of context
		}

		return context;
	}

	/* Render template with dust */
	function do_render(name, context, callback) {
		var context = do_create_context(context),
		    dir;
		if(!compiled[name]) {
			dir = search_dir(name);
			if(!dir) {
				callback("Could not find template: "+name);
				return;
			}
			do_load(dir+"/"+name, name);
		}
		if(debug) console.log("Rendering template: " + name);
		dust.render(name, context, callback);
	}

	/* Set directories to search files */
	function do_dirs() {
		foreach(arguments).do(function(dir) {
			dirs.push(dir);
			fs.readdir(dir, function(err, files) {
				if(err) {
					console.log(err);
					return;
				}
				foreach(files).do(function(file) {
					if(path.extname(file) != ".dust") return;
					do_load(dir+"/"+file, file);
				});
			});
		});
	}

	/* Enable or disable debug to console */
	function do_debug(enabled) {
		debug = (enabled === true) ? true : false;
	}

	/* Export functions */

	mod.debug = do_debug;

	mod.search_dir = search_dir;
	mod.compile = do_compile;
	mod.load = do_load;

	mod.render = do_render;
	mod.dirs = do_dirs;

	return mod;
})();

/* EOF */
<|endoftext|>


<commit_before>var bcrypto = require('./crypto')
var bs58check = require('bs58check')
var ecdsa = require('./ecdsa')
var randomBytes = require('randombytes')
var typeforce = require('typeforce')
var types = require('./types')
var wif = require('wif')

var NETWORKS = require('./networks')
var BigInteger = require('bigi')

var ecurve = require('ecurve')
var secp256k1 = ecdsa.__curve

function ECPair (d, Q, options) {
  if (options) {
    typeforce({
      compressed: types.maybe(types.Boolean),
      network: types.maybe(types.Network)
    }, options)
  }

  options = options || {}

  if (d) {
    if (d.signum() <= 0) throw new Error('Private key must be greater than 0')
    if (d.compareTo(secp256k1.n) >= 0) throw new Error('Private key must be less than the curve order')
    if (Q) throw new TypeError('Unexpected publicKey parameter')

    this.d = d
  } else {
    typeforce(types.ECPoint, Q)

    this.__Q = Q
  }

  this.compressed = options.compressed === undefined ? true : options.compressed
  this.network = options.network || NETWORKS.bitcoin
}

Object.defineProperty(ECPair.prototype, 'Q', {
  get: function () {
    if (!this.__Q && this.d) {
      this.__Q = secp256k1.G.multiply(this.d)
    }

    return this.__Q
  }
})

ECPair.fromPublicKeyBuffer = function (buffer, network) {
  var Q = ecurve.Point.decodeFrom(secp256k1, buffer)

  return new ECPair(null, Q, {
    compressed: Q.compressed,
    network: network
  })
}

ECPair.fromWIF = function (string, network) {
  var buffer = bs58check.decode(string)

  if (types.Array(network)) {
    var version = buffer[0]

    network = network.filter(function (network) {
      return version === network.wif
    }).pop()

    if (!network) throw new Error('Unknown network version')
  }

  network = network || NETWORKS.bitcoin
  var decoded = wif.decodeRaw(buffer, network.wif)
  var d = BigInteger.fromBuffer(decoded.privateKey)

  return new ECPair(d, null, {
    compressed: decoded.compressed,
    network: network
  })
}

ECPair.makeRandom = function (options) {
  options = options || {}

  var rng = options.rng || randomBytes

  var d
  do {
    var buffer = rng(32)
    typeforce(types.Buffer256bit, buffer)

    d = BigInteger.fromBuffer(buffer)
  } while (d.signum() <= 0 || d.compareTo(secp256k1.n) >= 0)

  return new ECPair(d, null, options)
}

ECPair.prototype.getAddress = function () {
  var pubKey = this.getPublicKeyBuffer()
  var pubKeyHash = bcrypto.hash160(pubKey)

  var payload = new Buffer(21)
  payload.writeUInt8(this.network.pubKeyHash, 0)
  pubKeyHash.copy(payload, 1)

  return bs58check.encode(payload)
}

ECPair.prototype.getNetwork = function () {
  return this.network
}

ECPair.prototype.getPublicKeyBuffer = function () {
  return this.Q.getEncoded(this.compressed)
}

ECPair.prototype.sign = function (hash) {
  if (!this.d) throw new Error('Missing private key')

  return ecdsa.sign(hash, this.d)
}

ECPair.prototype.toWIF = function () {
  if (!this.d) throw new Error('Missing private key')

  return wif.encode(this.network.wif, this.d.toBuffer(32), this.compressed)
}

ECPair.prototype.verify = function (hash, signature) {
  return ecdsa.verify(hash, signature, this.Q)
}

module.exports = ECPair
<commit_msg>ECPair: use toBase58Check<commit_after>var baddress = require('./address')
var bcrypto = require('./crypto')
var bs58check = require('bs58check')
var ecdsa = require('./ecdsa')
var randomBytes = require('randombytes')
var typeforce = require('typeforce')
var types = require('./types')
var wif = require('wif')

var NETWORKS = require('./networks')
var BigInteger = require('bigi')

var ecurve = require('ecurve')
var secp256k1 = ecdsa.__curve

function ECPair (d, Q, options) {
  if (options) {
    typeforce({
      compressed: types.maybe(types.Boolean),
      network: types.maybe(types.Network)
    }, options)
  }

  options = options || {}

  if (d) {
    if (d.signum() <= 0) throw new Error('Private key must be greater than 0')
    if (d.compareTo(secp256k1.n) >= 0) throw new Error('Private key must be less than the curve order')
    if (Q) throw new TypeError('Unexpected publicKey parameter')

    this.d = d
  } else {
    typeforce(types.ECPoint, Q)

    this.__Q = Q
  }

  this.compressed = options.compressed === undefined ? true : options.compressed
  this.network = options.network || NETWORKS.bitcoin
}

Object.defineProperty(ECPair.prototype, 'Q', {
  get: function () {
    if (!this.__Q && this.d) {
      this.__Q = secp256k1.G.multiply(this.d)
    }

    return this.__Q
  }
})

ECPair.fromPublicKeyBuffer = function (buffer, network) {
  var Q = ecurve.Point.decodeFrom(secp256k1, buffer)

  return new ECPair(null, Q, {
    compressed: Q.compressed,
    network: network
  })
}

ECPair.fromWIF = function (string, network) {
  var buffer = bs58check.decode(string)

  if (types.Array(network)) {
    var version = buffer[0]

    network = network.filter(function (network) {
      return version === network.wif
    }).pop()

    if (!network) throw new Error('Unknown network version')
  }

  network = network || NETWORKS.bitcoin
  var decoded = wif.decodeRaw(buffer, network.wif)
  var d = BigInteger.fromBuffer(decoded.privateKey)

  return new ECPair(d, null, {
    compressed: decoded.compressed,
    network: network
  })
}

ECPair.makeRandom = function (options) {
  options = options || {}

  var rng = options.rng || randomBytes

  var d
  do {
    var buffer = rng(32)
    typeforce(types.Buffer256bit, buffer)

    d = BigInteger.fromBuffer(buffer)
  } while (d.signum() <= 0 || d.compareTo(secp256k1.n) >= 0)

  return new ECPair(d, null, options)
}

ECPair.prototype.getAddress = function () {
  return baddress.toBase58Check(bcrypto.hash160(this.getPublicKeyBuffer()), this.getNetwork().pubKeyHash)
}

ECPair.prototype.getNetwork = function () {
  return this.network
}

ECPair.prototype.getPublicKeyBuffer = function () {
  return this.Q.getEncoded(this.compressed)
}

ECPair.prototype.sign = function (hash) {
  if (!this.d) throw new Error('Missing private key')

  return ecdsa.sign(hash, this.d)
}

ECPair.prototype.toWIF = function () {
  if (!this.d) throw new Error('Missing private key')

  return wif.encode(this.network.wif, this.d.toBuffer(32), this.compressed)
}

ECPair.prototype.verify = function (hash, signature) {
  return ecdsa.verify(hash, signature, this.Q)
}

module.exports = ECPair
<|endoftext|>