<commit_before>//------------------------------------------------------------------------------
// Copyright IBM Corp. 2015
//
// 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.
//------------------------------------------------------------------------------
'use strict';
var mqtt = require('./mqtt-wrapper.js')();
var bebop = require('node-bebop');
var drone = bebop.createClient();
var request = require('request');
var stream = require('stream');
var MjpegConsumer = require("mjpeg-consumer");
var consumer = new MjpegConsumer();

var latestMjpeg;
class EchoStream extends stream.Writable {
   _write(chunk, enc, next) {
     console.log(chunk.length);
     latestMjpeg = chunk;
     next();
   }
};

console.log('Trying to connect to the Bebop...');
drone.connect(function() {
  console.log('Connected to the Bebop!');

  drone.getMjpegStream().pipe(consumer).pipe(new EchoStream());

  mqtt.connect(function(client, deviceId) {
  	client.on('connect', function() {
	  console.log('MQTT client connected to IBM IoT Cloud.');
	  drone.on('battery', function(battery) {
	  	console.log("Battery percentage: " + battery + "%");
	  	client.publish('iot-2/evt/battery/fmt/json', JSON.stringify({
          "d" : {
            "batteryPercentage" : battery
          }
        }), function () {
	        console.log("Battery percentage published.")
	    });
	  });
	  client.subscribe('iot-2/cmd/fly/fmt/json', {qos : 0}, function(err, granted) {
	    if (err) throw err;
	      console.log("subscribed");
	    });
	  });
	  client.on('error', function(err) {
	    console.error('client error ' + err);
	    process.exit(1);
	  });
	  client.on('close', function() {
	    console.log('client closed');
	    process.exit(1);
	  });

	  client.on('message', function(topic, message, packet) {
	   console.log(topic);
	   var msg = JSON.parse(message.toString());
	   if(msg.d.action === '#takeoff') {
	     console.log('take off');
		 drone.takeOff();
	   } else if(msg.d.action === '#land') {
	     console.log('land');
		 drone.land();
           } else if(msg.d.action === '#up') {
             console.log('up');
             drone.stop();
             drone.up(0.2);
             setTimeout(function() {
             drone.stop();
             }, 2000);
           } else if(msg.d.action === '#down') {
             console.log('down');
             drone.stop();
             drone.down(0.2);
             setTimeout(function() {
             drone.stop();
             }, 1000);
           } else if(msg.d.action === '#rotatec') {
             console.log('rotatec');
             drone.stop();
             drone.clockwise(0.3);
             setTimeout(function() {
             drone.stop();
             }, 1000);
           } else if(msg.d.action === '#rotatecc') {
             console.log('rotatecc');
             drone.stop();
             drone.counterClockwise(0.3);
             setTimeout(function() {
             drone.stop();
             }, 1000);
           } else if(msg.d.action === '#takeoffandland') {
             console.log('take off and land');
             var length = msg.d.length ? msg.d.length : 5000;
             //drone.disableEmergency();
             drone.takeOff();
             setTimeout(function() {
                drone.stop();
                drone.land();
              }, length);

	   //} else if(msg.d.action === '#takeoffandland') {
	     //console.log('take off and land');
	     //var length = msg.d.length ? msg.d.length : 4000;
	//	 drone.takeOff();
	  //   setTimeout(function() {
	//	   drone.land();
	  //   }, length);
	   } else if(msg.d.action === '#takepicture') {
	    if(!latestMjpeg) {
	      console.log('No images yet');
	      var options = {
	        uri: msg.d.callback,
	        method: 'POST',
	        json: {
	          "error" : "No image"
	        }
	      };
	      request(options, function (error, response, body) {});
	    } else {
	      var fs = require('fs');
	      console.log(latestMjpeg.length);
	      fs.writeFile('pic.jpeg', latestMjpeg, function(){console.log('written')});
	      var formData = {
	        my_file: {
	          value: latestMjpeg,
	          options: {
	            filename: 'picture.jpeg',
	            contentType: 'image/jpeg'
	          }
	        }
	      };
	      request.post({uri: msg.d.callback, formData: formData}, function(err, httpResponse, body) {
	        if(err) {
	          console.log("error posting picture " + err);
	        } else {
	          console.log('Picture uploaded');
	        }
	      });
	    }
	  }
    });
  });
});
<commit_msg>Removed console.log<commit_after>//------------------------------------------------------------------------------
// Copyright IBM Corp. 2015
//
// 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.
//------------------------------------------------------------------------------
'use strict';
var mqtt = require('./mqtt-wrapper.js')();
var bebop = require('node-bebop');
var drone = bebop.createClient();
var request = require('request');
var stream = require('stream');
var MjpegConsumer = require("mjpeg-consumer");
var consumer = new MjpegConsumer();

var latestMjpeg;
class EchoStream extends stream.Writable {
   _write(chunk, enc, next) {
     latestMjpeg = chunk;
     next();
   }
};

console.log('Trying to connect to the Bebop...');
drone.connect(function() {
  console.log('Connected to the Bebop!');

  drone.getMjpegStream().pipe(consumer).pipe(new EchoStream());

  mqtt.connect(function(client, deviceId) {
  	client.on('connect', function() {
	  console.log('MQTT client connected to IBM IoT Cloud.');
	  drone.on('battery', function(battery) {
	  	console.log("Battery percentage: " + battery + "%");
	  	client.publish('iot-2/evt/battery/fmt/json', JSON.stringify({
          "d" : {
            "batteryPercentage" : battery
          }
        }), function () {
	        console.log("Battery percentage published.")
	    });
	  });
	  client.subscribe('iot-2/cmd/fly/fmt/json', {qos : 0}, function(err, granted) {
	    if (err) throw err;
	      console.log("subscribed");
	    });
	  });
	  client.on('error', function(err) {
	    console.error('client error ' + err);
	    process.exit(1);
	  });
	  client.on('close', function() {
	    console.log('client closed');
	    process.exit(1);
	  });

	  client.on('message', function(topic, message, packet) {
	   console.log(topic);
	   var msg = JSON.parse(message.toString());
	   if(msg.d.action === '#takeoff') {
	     console.log('take off');
		 drone.takeOff();
	   } else if(msg.d.action === '#land') {
	     console.log('land');
		 drone.land();
           } else if(msg.d.action === '#up') {
             console.log('up');
             drone.stop();
             drone.up(0.2);
             setTimeout(function() {
             drone.stop();
             }, 2000);
           } else if(msg.d.action === '#down') {
             console.log('down');
             drone.stop();
             drone.down(0.2);
             setTimeout(function() {
             drone.stop();
             }, 1000);
           } else if(msg.d.action === '#rotatec') {
             console.log('rotatec');
             drone.stop();
             drone.clockwise(0.3);
             setTimeout(function() {
             drone.stop();
             }, 1000);
           } else if(msg.d.action === '#rotatecc') {
             console.log('rotatecc');
             drone.stop();
             drone.counterClockwise(0.3);
             setTimeout(function() {
             drone.stop();
             }, 1000);
           } else if(msg.d.action === '#takeoffandland') {
             console.log('take off and land');
             var length = msg.d.length ? msg.d.length : 5000;
             //drone.disableEmergency();
             drone.takeOff();
             setTimeout(function() {
                drone.stop();
                drone.land();
              }, length);

	   //} else if(msg.d.action === '#takeoffandland') {
	     //console.log('take off and land');
	     //var length = msg.d.length ? msg.d.length : 4000;
	//	 drone.takeOff();
	  //   setTimeout(function() {
	//	   drone.land();
	  //   }, length);
	   } else if(msg.d.action === '#takepicture') {
	    if(!latestMjpeg) {
	      console.log('No images yet');
	      var options = {
	        uri: msg.d.callback,
	        method: 'POST',
	        json: {
	          "error" : "No image"
	        }
	      };
	      request(options, function (error, response, body) {});
	    } else {
	      var fs = require('fs');
	      console.log(latestMjpeg.length);
	      fs.writeFile('pic.jpeg', latestMjpeg, function(){console.log('written')});
	      var formData = {
	        my_file: {
	          value: latestMjpeg,
	          options: {
	            filename: 'picture.jpeg',
	            contentType: 'image/jpeg'
	          }
	        }
	      };
	      request.post({uri: msg.d.callback, formData: formData}, function(err, httpResponse, body) {
	        if(err) {
	          console.log("error posting picture " + err);
	        } else {
	          console.log('Picture uploaded');
	        }
	      });
	    }
	  }
    });
  });
});
<|endoftext|>


<commit_before>dojo.provide("dijit._editor.plugins.AlwaysShowToolbar");

dojo.declare("dijit._editor.plugins.AlwaysShowToolbar", dijit._editor._Plugin,
	{
	_handleScroll: true,
	setEditor: function(e){
		if(!e.iframe){
			console.log('Port AlwaysShowToolbar plugin to work with Editor without iframe');
			return;
		}

		this.editor = e;

		e.onLoadDeferred.addCallback(dojo.hitch(this, this.enable));
	},
	enable: function(d){
		this._updateHeight();
		this.connect(window, 'onscroll', "globalOnScrollHandler");
		this.connect(this.editor, 'onNormalizedDisplayChanged', "_updateHeight");
		return d;
	},
	_updateHeight: function(){
		// summary:
		//		Updates the height of the editor area to fit the contents.
		var e = this.editor;
		if(!e.isLoaded){ return; }
		if(e.height){ return; }

		var height = dojo.marginBox(e.editNode).h;
		if(dojo.isOpera){
			height = e.editNode.scrollHeight;
		}
		// console.debug('height',height);
		// alert(this.editNode);

		//height maybe zero in some cases even though the content is not empty,
		//we try the height of body instead
		if(!height){
			height = dojo.marginBox(e.document.body).h;
		}

		if(height == 0){
			console.debug("Can not figure out the height of the editing area!");
			return; //prevent setting height to 0
		}
		if(height != this._lastHeight){
			this._lastHeight = height;
			// this.editorObject.style.height = this._lastHeight + "px";
			dojo.marginBox(e.iframe, { h: this._lastHeight });
		}
	},
	_lastHeight: 0,
	globalOnScrollHandler: function(){
		var isIE = dojo.isIE && dojo.isIE<7;
		if(!this._handleScroll){ return; }
		var tdn = this.editor.toolbar.domNode;
		var db = dojo.body;

		if(!this._scrollSetUp){
			this._scrollSetUp = true;
			this._scrollThreshold = dojo._abs(tdn, true).y;
//			console.log("threshold:", this._scrollThreshold);
			//what's this for?? comment out for now
//			if((isIE)&&(db)&&(dojo.style(db, "backgroundIimage")=="none")){
//				db.style.backgroundImage = "url(" + dojo.uri.moduleUri("dijit", "templates/blank.gif") + ")";
//				db.style.backgroundAttachment = "fixed";
//			}
		}

		var scrollPos = dojo._docScroll().y;
		var s = tdn.style;

		if(scrollPos > this._scrollThreshold && scrollPos < this._scrollThreshold+this._lastHeight){
			// dojo.debug(scrollPos);
			if(!this._fixEnabled){
				var tdnbox = dojo.marginBox(tdn);
				this.editor.iframe.style.marginTop = tdnbox.h+"px";

				if(isIE){
					s.left = dojo._abs(tdn).x;
					if(tdn.previousSibling){
						this._IEOriginalPos = ['after',tdn.previousSibling];
					}else if(tdn.nextSibling){
						this._IEOriginalPos = ['before',tdn.nextSibling];
					}else{
						this._IEOriginalPos = ['last',tdn.parentNode];
					}
					dojo.body().appendChild(tdn);
					dojo.addClass(tdn,'dijitIEFixedToolbar');
				}else{
					s.position = "fixed";
					s.top = "0px";
				}

				dojo.marginBox(tdn, { w: tdnbox.w });
				s.zIndex = 2000;
				this._fixEnabled = true;
			}
			// if we're showing the floating toolbar, make sure that if
			// we've scrolled past the bottom of the editor that we hide
			// the toolbar for this instance of the editor.

			// TODO: when we get multiple editor toolbar support working
			// correctly, ensure that we check this against the scroll
			// position of the bottom-most editor instance.
			var eHeight = (this.height) ? parseInt(this.editor.height) : this.editor._lastHeight;
			s.display = (scrollPos > this._scrollThreshold+eHeight) ? "none" : "";
		}else if(this._fixEnabled){
			this.editor.iframe.style.marginTop = '';
			s.position = "";
			s.top = "";
			s.zIndex = "";
			s.display = "";
			if(isIE){
				s.left = "";
				dojo.removeClass(tdn,'dijitIEFixedToolbar');
				if(this._IEOriginalPos){
					dojo.place(tdn, this._IEOriginalPos[1], this._IEOriginalPos[0]);
					this._IEOriginalPos = null;
				}else{
					dojo.place(tdn, this.editor.iframe, 'before');
				}
			}
			s.width = "";
			this._fixEnabled = false;
		}
	},
	destroy: function(){
		this._IEOriginalPos = null;
		this._handleScroll = false;
		dojo.forEach(this._connects, dojo.disconnect);
//		clearInterval(this.scrollInterval);

		if(dojo.isIE && dojo.isIE<7){
			dojo.removeClass(this.editor.toolbar.domNode, 'dijitIEFixedToolbar');
		}
	}
});
<commit_msg>simplify IE version check.  Refs #7159 !strict<commit_after>dojo.provide("dijit._editor.plugins.AlwaysShowToolbar");

dojo.declare("dijit._editor.plugins.AlwaysShowToolbar", dijit._editor._Plugin,
	{
	_handleScroll: true,
	setEditor: function(e){
		if(!e.iframe){
			console.log('Port AlwaysShowToolbar plugin to work with Editor without iframe');
			return;
		}

		this.editor = e;

		e.onLoadDeferred.addCallback(dojo.hitch(this, this.enable));
	},
	enable: function(d){
		this._updateHeight();
		this.connect(window, 'onscroll', "globalOnScrollHandler");
		this.connect(this.editor, 'onNormalizedDisplayChanged', "_updateHeight");
		return d;
	},
	_updateHeight: function(){
		// summary:
		//		Updates the height of the editor area to fit the contents.
		var e = this.editor;
		if(!e.isLoaded){ return; }
		if(e.height){ return; }

		var height = dojo.marginBox(e.editNode).h;
		if(dojo.isOpera){
			height = e.editNode.scrollHeight;
		}
		// console.debug('height',height);
		// alert(this.editNode);

		//height maybe zero in some cases even though the content is not empty,
		//we try the height of body instead
		if(!height){
			height = dojo.marginBox(e.document.body).h;
		}

		if(height == 0){
			console.debug("Can not figure out the height of the editing area!");
			return; //prevent setting height to 0
		}
		if(height != this._lastHeight){
			this._lastHeight = height;
			// this.editorObject.style.height = this._lastHeight + "px";
			dojo.marginBox(e.iframe, { h: this._lastHeight });
		}
	},
	_lastHeight: 0,
	globalOnScrollHandler: function(){
		var isIE6 = dojo.isIE < 7;
		if(!this._handleScroll){ return; }
		var tdn = this.editor.toolbar.domNode;
		var db = dojo.body;

		if(!this._scrollSetUp){
			this._scrollSetUp = true;
			this._scrollThreshold = dojo._abs(tdn, true).y;
//			console.log("threshold:", this._scrollThreshold);
			//what's this for?? comment out for now
//			if((isIE6)&&(db)&&(dojo.style(db, "backgroundIimage")=="none")){
//				db.style.backgroundImage = "url(" + dojo.uri.moduleUri("dijit", "templates/blank.gif") + ")";
//				db.style.backgroundAttachment = "fixed";
//			}
		}

		var scrollPos = dojo._docScroll().y;
		var s = tdn.style;

		if(scrollPos > this._scrollThreshold && scrollPos < this._scrollThreshold+this._lastHeight){
			// dojo.debug(scrollPos);
			if(!this._fixEnabled){
				var tdnbox = dojo.marginBox(tdn);
				this.editor.iframe.style.marginTop = tdnbox.h+"px";

				if(isIE6){
					s.left = dojo._abs(tdn).x;
					if(tdn.previousSibling){
						this._IEOriginalPos = ['after',tdn.previousSibling];
					}else if(tdn.nextSibling){
						this._IEOriginalPos = ['before',tdn.nextSibling];
					}else{
						this._IEOriginalPos = ['last',tdn.parentNode];
					}
					dojo.body().appendChild(tdn);
					dojo.addClass(tdn,'dijitIEFixedToolbar');
				}else{
					s.position = "fixed";
					s.top = "0px";
				}

				dojo.marginBox(tdn, { w: tdnbox.w });
				s.zIndex = 2000;
				this._fixEnabled = true;
			}
			// if we're showing the floating toolbar, make sure that if
			// we've scrolled past the bottom of the editor that we hide
			// the toolbar for this instance of the editor.

			// TODO: when we get multiple editor toolbar support working
			// correctly, ensure that we check this against the scroll
			// position of the bottom-most editor instance.
			var eHeight = (this.height) ? parseInt(this.editor.height) : this.editor._lastHeight;
			s.display = (scrollPos > this._scrollThreshold+eHeight) ? "none" : "";
		}else if(this._fixEnabled){
			this.editor.iframe.style.marginTop = '';
			s.position = "";
			s.top = "";
			s.zIndex = "";
			s.display = "";
			if(isIE6){
				s.left = "";
				dojo.removeClass(tdn,'dijitIEFixedToolbar');
				if(this._IEOriginalPos){
					dojo.place(tdn, this._IEOriginalPos[1], this._IEOriginalPos[0]);
					this._IEOriginalPos = null;
				}else{
					dojo.place(tdn, this.editor.iframe, 'before');
				}
			}
			s.width = "";
			this._fixEnabled = false;
		}
	},
	destroy: function(){
		this._IEOriginalPos = null;
		this._handleScroll = false;
		dojo.forEach(this._connects, dojo.disconnect);
//		clearInterval(this.scrollInterval);

		if(dojo.isIE < 7){
			dojo.removeClass(this.editor.toolbar.domNode, 'dijitIEFixedToolbar');
		}
	}
});
<|endoftext|>


<commit_before>var AIRTIME = (function(AIRTIME) {
    var mod;

    if (AIRTIME.history === undefined) {
        AIRTIME.history = {};
    }
    mod = AIRTIME.history;

    mod.historyTable = function() {
        var oTable,
        	historyContentDiv = $("#history_content"),
        	historyTableDiv = historyContentDiv.find("#history_table"),
        	tableHeight = historyContentDiv.height() - 200,
        	fnServerData;

        fnServerData = function ( sSource, aoData, fnCallback ) {

        	if (fnServerData.hasOwnProperty("start")) {
    			aoData.push( { name: "start", value: fnServerData.start} );
    		}
    		if (fnServerData.hasOwnProperty("end")) {
    			aoData.push( { name: "end", value: fnServerData.end} );
    		}

            aoData.push( { name: "format", value: "json"} );

            $.ajax( {
                "dataType": 'json',
                "type": "GET",
                "url": sSource,
                "data": aoData,
                "success": fnCallback
            } );
        };

        oTable = historyTableDiv.dataTable( {

            "aoColumns": [
               {"sTitle": "Title", "mDataProp": "title", "sClass": "his_title"}, /* Title */
               {"sTitle": "Artist", "mDataProp": "artist", "sClass": "his_artist"}, /* Creator */
               {"sTitle": "Played", "mDataProp": "played", "sClass": "his_artist"}, /* times played */
               {"sTitle": "Length", "mDataProp": "length", "sClass": "his_length library_length"}, /* Length */
               {"sTitle": "Composer", "mDataProp": "composer", "sClass": "his_composer"}, /* Composer */
               {"sTitle": "Copyright", "mDataProp": "copyright", "sClass": "his_copyright"} /* Copyright */
            ],

            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": "/Playouthistory/playout-history-feed",
            "sAjaxDataProp": "history",

            "fnServerData": fnServerData,

            "oLanguage": {
                "sSearch": ""
            },

            "aLengthMenu": [[50, 100, 500, -1], [50, 100, 500, "All"]],
            "iDisplayLength": 50,

            "sPaginationType": "full_numbers",
            "bJQueryUI": true,
            "bAutoWidth": true,

            "sDom": 'lf<"dt-process-rel"r><"H"T><"dataTables_scrolling"t><"F"ip>',

            "oTableTools": {
                "sSwfPath": "/js/datatables/plugin/TableTools/swf/copy_cvs_xls_pdf.swf"
            }
        });
        oTable.fnSetFilteringDelay(350);

        historyContentDiv.find(".dataTables_scrolling").css("max-height", tableHeight);

        return oTable;
    };

return AIRTIME;

}(AIRTIME || {}));

$(document).ready(function(){

	var viewport = AIRTIME.utilities.findViewportDimensions(),
		history_content = $("#history_content"),
		widgetHeight = viewport.height - 185,
		screenWidth = Math.floor(viewport.width - 110),
		oBaseDatePickerSettings,
		oBaseTimePickerSettings,
		oTable,
		dateStartId = "#his_date_start",
		timeStartId = "#his_time_start",
		dateEndId = "#his_date_end",
		timeEndId = "#his_time_end";

	/*
     * Icon hover states for search.
     */
	history_content.on("mouseenter", ".his-timerange .ui-button", function(ev) {
    	$(this).addClass("ui-state-hover");
    });
	history_content.on("mouseleave", ".his-timerange .ui-button", function(ev) {
    	$(this).removeClass("ui-state-hover");
    });

	history_content
		.height(widgetHeight)
		.width(screenWidth);

	oBaseDatePickerSettings = {
		dateFormat: 'yy-mm-dd',
		onSelect: function(sDate, oDatePicker) {
			$(this).datepicker( "setDate", sDate );
		}
	};

	oBaseTimePickerSettings = {
		showPeriodLabels: false,
		showCloseButton: true,
		showLeadingZero: false,
		defaultTime: '0:00'
	};

	oTable = AIRTIME.history.historyTable();

	history_content.find(dateStartId).datepicker(oBaseDatePickerSettings);
	history_content.find(timeStartId).timepicker(oBaseTimePickerSettings);
	history_content.find(dateEndId).datepicker(oBaseDatePickerSettings);
	history_content.find(timeEndId).timepicker(oBaseTimePickerSettings);

	history_content.find("#his_submit").click(function(ev){
		var fn,
			oRange;

		oRange = AIRTIME.utilities.fnGetScheduleRange(dateStartId, timeStartId, dateEndId, timeEndId);

	    fn = oTable.fnSettings().fnServerData;
	    fn.start = oRange.start;
	    fn.end = oRange.end;

		oTable.fnDraw();
	});

});<commit_msg>CC-3979: Playout History export should include date range in file and/or filename<commit_after>function getFileName(){
    var filename = $("#his_date_start").val()+"_"+$("#his_time_start").val()+"m--"+$("#his_date_end").val()+"_"+$("#his_time_end").val()+"m"
    filename = filename.replace(/:/g,"h")
    return filename;
}

function setFlashFileName( nButton, oConfig, oFlash ) {
    var filename = getFileName()
    oFlash.setFileName( filename );
    this.fnSetText( oFlash,
        "title:"+ this.fnGetTitle(oConfig) +"\n"+
        "message:"+ oConfig.sPdfMessage +"\n"+
        "colWidth:"+ this.fnCalcColRatios(oConfig) +"\n"+
        "orientation:"+ oConfig.sPdfOrientation +"\n"+
        "size:"+ oConfig.sPdfSize +"\n"+
        "--/TableToolsOpts--\n" +
        this.fnGetTableData(oConfig));
}

var AIRTIME = (function(AIRTIME) {
    var mod;

    if (AIRTIME.history === undefined) {
        AIRTIME.history = {};
    }
    mod = AIRTIME.history;

    mod.historyTable = function() {
        var oTable,
        	historyContentDiv = $("#history_content"),
        	historyTableDiv = historyContentDiv.find("#history_table"),
        	tableHeight = historyContentDiv.height() - 200,
        	fnServerData;

        fnServerData = function ( sSource, aoData, fnCallback ) {

        	if (fnServerData.hasOwnProperty("start")) {
    			aoData.push( { name: "start", value: fnServerData.start} );
    		}
    		if (fnServerData.hasOwnProperty("end")) {
    			aoData.push( { name: "end", value: fnServerData.end} );
    		}

            aoData.push( { name: "format", value: "json"} );

            $.ajax( {
                "dataType": 'json',
                "type": "GET",
                "url": sSource,
                "data": aoData,
                "success": fnCallback
            } );
        };

        oTable = historyTableDiv.dataTable( {

            "aoColumns": [
               {"sTitle": "Title", "mDataProp": "title", "sClass": "his_title"}, /* Title */
               {"sTitle": "Artist", "mDataProp": "artist", "sClass": "his_artist"}, /* Creator */
               {"sTitle": "Played", "mDataProp": "played", "sClass": "his_artist"}, /* times played */
               {"sTitle": "Length", "mDataProp": "length", "sClass": "his_length library_length"}, /* Length */
               {"sTitle": "Composer", "mDataProp": "composer", "sClass": "his_composer"}, /* Composer */
               {"sTitle": "Copyright", "mDataProp": "copyright", "sClass": "his_copyright"} /* Copyright */
            ],

            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": "/Playouthistory/playout-history-feed",
            "sAjaxDataProp": "history",

            "fnServerData": fnServerData,

            "oLanguage": {
                "sSearch": ""
            },

            "aLengthMenu": [[50, 100, 500, -1], [50, 100, 500, "All"]],
            "iDisplayLength": 50,

            "sPaginationType": "full_numbers",
            "bJQueryUI": true,
            "bAutoWidth": true,

            "sDom": 'lf<"dt-process-rel"r><"H"T><"dataTables_scrolling"t><"F"ip>',

            "oTableTools": {
                "sSwfPath": "/js/datatables/plugin/TableTools/swf/copy_cvs_xls_pdf.swf",
                "aButtons": [
                             "copy",
                             {
                                 "sExtends": "csv",
                                 "fnClick": setFlashFileName
                             },
                             {
                                 "sExtends": "xls",
                                 "fnClick": setFlashFileName
                             },
                             {
                                 "sExtends": "pdf",
                                 "fnClick": setFlashFileName
                             },
                             "print"
                         ]
            }
        });
        oTable.fnSetFilteringDelay(350);

        historyContentDiv.find(".dataTables_scrolling").css("max-height", tableHeight);

        return oTable;
    };

return AIRTIME;

}(AIRTIME || {}));

$(document).ready(function(){

	var viewport = AIRTIME.utilities.findViewportDimensions(),
		history_content = $("#history_content"),
		widgetHeight = viewport.height - 185,
		screenWidth = Math.floor(viewport.width - 110),
		oBaseDatePickerSettings,
		oBaseTimePickerSettings,
		oTable,
		dateStartId = "#his_date_start",
		timeStartId = "#his_time_start",
		dateEndId = "#his_date_end",
		timeEndId = "#his_time_end";

	/*
     * Icon hover states for search.
     */
	history_content.on("mouseenter", ".his-timerange .ui-button", function(ev) {
    	$(this).addClass("ui-state-hover");
    });
	history_content.on("mouseleave", ".his-timerange .ui-button", function(ev) {
    	$(this).removeClass("ui-state-hover");
    });

	history_content
		.height(widgetHeight)
		.width(screenWidth);

	oBaseDatePickerSettings = {
		dateFormat: 'yy-mm-dd',
		onSelect: function(sDate, oDatePicker) {
			$(this).datepicker( "setDate", sDate );
		}
	};

	oBaseTimePickerSettings = {
		showPeriodLabels: false,
		showCloseButton: true,
		showLeadingZero: false,
		defaultTime: '0:00'
	};

	oTable = AIRTIME.history.historyTable();

	history_content.find(dateStartId).datepicker(oBaseDatePickerSettings);
	history_content.find(timeStartId).timepicker(oBaseTimePickerSettings);
	history_content.find(dateEndId).datepicker(oBaseDatePickerSettings);
	history_content.find(timeEndId).timepicker(oBaseTimePickerSettings);

	history_content.find("#his_submit").click(function(ev){
		var fn,
			oRange;

		oRange = AIRTIME.utilities.fnGetScheduleRange(dateStartId, timeStartId, dateEndId, timeEndId);

	    fn = oTable.fnSettings().fnServerData;
	    fn.start = oRange.start;
	    fn.end = oRange.end;

		oTable.fnDraw();
	});

});<|endoftext|>


<commit_before>App.TargetsIndexController = Ember.ObjectController.extend({

    needs: ['application'],

    queryParams: ['uri'],

    uri: '',

    molViewer: null,

    threeDeeTarget: null,

    showMolecule: false,

    pdbStructure: null,

    webGLEnabled: Modernizr.webgl,

    hasPDB: function() {
        if (this.get('model').get('seeAlso').length > 0) {
            return true;
        } else {
            return false;
        }
    }.property('model.seeAlso'),

    threeDeeEnabled: function() {
        return Modernizr.webgl == true && Modernizr.canvas == true;
    }.property('webGLEnabled'),

    showProvenance: false,

    actions: {
        enableProvenance: function() {
            this.set('showProvenance', true);
            console.log("Target provenance enabled");
        },

        disableProvenance: function() {
            this.set('showProvenance', false);
            console.log("Target provenance disabled");
        },

        changeFavouriteStatus: function() {
            console.log('changing favourite status');
            this.get('controllers.application').addFavourite('targets', this.get('model').get('URI'), this.get('model').get('prefLabel'), this.get('model'));
        },

        drawProtein: function() {
            var me = this;
            if (me.get('content').get('seeAlso').length > 0) {
                if (me.get('pdbStructure') == null) {
                    var uri = "http://www.pdb.org/pdb/files/" + me.get('content').get('seeAlso')[0].split('/').pop() + ".pdb"
                    $.get(uri, function(ret) {
                        me.set('pdbStructure', ret);
                        $("#glmol01_src").val(ret);
                        // Draw the protein using the following params. Lots commented out but in the original
                        // glmol examples. Maybe these can be user configured.
                        me.get('molViewer').defineRepresentation = function() {
                            //var idHeader = "#" + this.id + '_';

                            var time = new Date();
                            var all = this.getAllAtoms();
                            //if ($(idHeader + 'biomt').attr('checked') && this.protein.biomtChains != "") all = this.getChain(all, this.protein.biomtChains);
                            var allHet = this.getHetatms(all);
                            var hetatm = this.removeSolvents(allHet);

                            console.log("selection " + (+new Date() - time));
                            time = new Date();

                            this.colorByAtom(all, {});
                            var colorMode = "chainbow"; //$(idHeader + 'color').val();
                            if (colorMode == 'ss') {
                                this.colorByStructure(all, 0xcc00cc, 0x00cccc);
                            } else if (colorMode == 'chain') {
                                this.colorByChain(all);
                            } else if (colorMode == 'chainbow') {
                                this.colorChainbow(all);
                            } else if (colorMode == 'b') {
                                this.colorByBFactor(all);
                            } else if (colorMode == 'polarity') {
                                this.colorByPolarity(all, 0xcc0000, 0xcccccc);
                            }
                            console.log("color " + (+new Date() - time));
                            time = new Date();

                            var asu = new THREE.Object3D();
                            var mainchainMode = "ribbon"; //$(idHeader + 'mainchain').val();
                            var doNotSmoothen = false; //($(idHeader + 'doNotSmoothen').attr('checked') == 'checked');
                            //if ($(idHeader + 'showMainchain').attr('checked')) {
                            if (mainchainMode == 'ribbon') {
                                this.drawCartoon(asu, all, doNotSmoothen);
                                this.drawCartoonNucleicAcid(asu, all);
                            } else if (mainchainMode == 'thickRibbon') {
                                this.drawCartoon(asu, all, doNotSmoothen, this.thickness);
                                this.drawCartoonNucleicAcid(asu, all, null, this.thickness);
                            } else if (mainchainMode == 'strand') {
                                this.drawStrand(asu, all, null, null, null, null, null, doNotSmoothen);
                                this.drawStrandNucleicAcid(asu, all);
                            } else if (mainchainMode == 'chain') {
                                this.drawMainchainCurve(asu, all, this.curveWidth, 'CA', 1);
                                this.drawMainchainCurve(asu, all, this.curveWidth, 'O3\'', 1);
                            } else if (mainchainMode == 'cylinderHelix') {
                                this.drawHelixAsCylinder(asu, all, 1.6);
                                this.drawCartoonNucleicAcid(asu, all);
                            } else if (mainchainMode == 'tube') {
                                this.drawMainchainTube(asu, all, 'CA');
                                this.drawMainchainTube(asu, all, 'O3\''); // FIXME: 5' end problem!
                            } else if (mainchainMode == 'bonds') {
                                this.drawBondsAsLine(asu, all, this.lineWidth);
                            }
                            //}

                            //if ($(idHeader + 'line').attr('checked')) {
                            //    this.drawBondsAsLine(this.modelGroup, this.getSidechains(all), this.lineWidth);
                            //}
                            //console.log("mainchain " + (+new Date() - time));
                            time = new Date();

                            //if ($(idHeader + 'showBases').attr('checked')) {
                            var hetatmMode = "nuclLine"; //$(idHeader + 'base').val();
                            if (hetatmMode == 'nuclStick') {
                                this.drawNucleicAcidStick(this.modelGroup, all);
                            } else if (hetatmMode == 'nuclLine') {
                                this.drawNucleicAcidLine(this.modelGroup, all);
                            } else if (hetatmMode == 'nuclPolygon') {
                                this.drawNucleicAcidLadder(this.modelGroup, all);
                            }
                            //}

                            var target = this.modelGroup;
                            //if ($(idHeader + 'showNonBonded').attr('checked')) {
                            //    var nonBonded = this.getNonbonded(allHet);
                            //    var nbMode = $(idHeader + 'nb').val();
                            //    if (nbMode == 'nb_sphere') {
                            //        this.drawAtomsAsIcosahedron(target, nonBonded, 0.3, true);
                            //    } else if (nbMode == 'nb_cross') {
                            //        this.drawAsCross(target, nonBonded, 0.3, true);

                            //    }
                            //}

                            //if ($(idHeader + 'showHetatms').attr('checked')) {
                            var hetatmMode = "sphere"; //$(idHeader + 'hetatm').val();
                            if (hetatmMode == 'stick') {
                                this.drawBondsAsStick(target, hetatm, this.cylinderRadius, this.cylinderRadius, true);
                            } else if (hetatmMode == 'sphere') {
                                this.drawAtomsAsSphere(target, hetatm, this.sphereRadius);
                            } else if (hetatmMode == 'line') {
                                this.drawBondsAsLine(target, hetatm, this.curveWidth);
                            } else if (hetatmMode == 'icosahedron') {
                                this.drawAtomsAsIcosahedron(target, hetatm, this.sphereRadius);
                            } else if (hetatmMode == 'ballAndStick') {
                                this.drawBondsAsStick(target, hetatm, this.cylinderRadius / 2.0, this.cylinderRadius, true, false, 0.3);
                            } else if (hetatmMode == 'ballAndStick2') {
                                this.drawBondsAsStick(target, hetatm, this.cylinderRadius / 2.0, this.cylinderRadius, true, true, 0.3);
                            }

                            //}
                            console.log("hetatms " + (+new Date() - time));
                            time = new Date();

                            var projectionMode = "perspective"; //$(idHeader + 'projection').val();
                            if (projectionMode == 'perspective') this.camera = this.perspectiveCamera;
                            else if (projectionMode == 'orthoscopic') this.camera = this.orthoscopicCamera;

                            //this.setBackground(parseInt($(idHeader + 'bgcolor').val()));

                            //if ($(idHeader + 'cell').attr('checked')) {
                            //    this.drawUnitcell(this.modelGroup);
                            //}

                            //if ($(idHeader + 'biomt').attr('checked')) {
                            //    this.drawSymmetryMates2(this.modelGroup, asu, this.protein.biomtMatrices);
                            //}
                            //if ($(idHeader + 'packing').attr('checked')) {
                            //    this.drawSymmetryMatesWithTranslation2(this.modelGroup, asu, this.protein.symMat);
                            //}
                            this.modelGroup.add(asu);
                        };
                        me.get('molViewer').loadMolecule();
                        me.set('showMolecule', true);
                        me.get('threeDeeTarget').modal('show');
                    });
                } else {
                    //already loaded, just show it
                    me.get('threeDeeTarget').modal('show');
                }
            }
        }
    }

});
<commit_msg>check that pdb is present before grabbing one from target<commit_after>App.TargetsIndexController = Ember.ObjectController.extend({

    needs: ['application'],

    queryParams: ['uri'],

    uri: '',

    molViewer: null,

    threeDeeTarget: null,

    showMolecule: false,

    pdbStructure: null,

    webGLEnabled: Modernizr.webgl,

    hasPDB: function() {
	    if (this.get('model').get('seeAlso') != null) {
        if (this.get('model').get('seeAlso').length > 0) {
            return true;
        } else {
            return false;
        }
	    }
    }.property('model.seeAlso'),

    threeDeeEnabled: function() {
        return Modernizr.webgl == true && Modernizr.canvas == true;
    }.property('webGLEnabled'),

    showProvenance: false,

    actions: {
        enableProvenance: function() {
            this.set('showProvenance', true);
            console.log("Target provenance enabled");
        },

        disableProvenance: function() {
            this.set('showProvenance', false);
            console.log("Target provenance disabled");
        },

        changeFavouriteStatus: function() {
            console.log('changing favourite status');
            this.get('controllers.application').addFavourite('targets', this.get('model').get('URI'), this.get('model').get('prefLabel'), this.get('model'));
        },

        drawProtein: function() {
            var me = this;
            if (me.get('content').get('seeAlso').length > 0) {
                if (me.get('pdbStructure') == null) {
                    var uri = "http://www.pdb.org/pdb/files/" + me.get('content').get('seeAlso')[0].split('/').pop() + ".pdb"
                    $.get(uri, function(ret) {
                        me.set('pdbStructure', ret);
                        $("#glmol01_src").val(ret);
                        // Draw the protein using the following params. Lots commented out but in the original
                        // glmol examples. Maybe these can be user configured.
                        me.get('molViewer').defineRepresentation = function() {
                            //var idHeader = "#" + this.id + '_';

                            var time = new Date();
                            var all = this.getAllAtoms();
                            //if ($(idHeader + 'biomt').attr('checked') && this.protein.biomtChains != "") all = this.getChain(all, this.protein.biomtChains);
                            var allHet = this.getHetatms(all);
                            var hetatm = this.removeSolvents(allHet);

                            console.log("selection " + (+new Date() - time));
                            time = new Date();

                            this.colorByAtom(all, {});
                            var colorMode = "chainbow"; //$(idHeader + 'color').val();
                            if (colorMode == 'ss') {
                                this.colorByStructure(all, 0xcc00cc, 0x00cccc);
                            } else if (colorMode == 'chain') {
                                this.colorByChain(all);
                            } else if (colorMode == 'chainbow') {
                                this.colorChainbow(all);
                            } else if (colorMode == 'b') {
                                this.colorByBFactor(all);
                            } else if (colorMode == 'polarity') {
                                this.colorByPolarity(all, 0xcc0000, 0xcccccc);
                            }
                            console.log("color " + (+new Date() - time));
                            time = new Date();

                            var asu = new THREE.Object3D();
                            var mainchainMode = "ribbon"; //$(idHeader + 'mainchain').val();
                            var doNotSmoothen = false; //($(idHeader + 'doNotSmoothen').attr('checked') == 'checked');
                            //if ($(idHeader + 'showMainchain').attr('checked')) {
                            if (mainchainMode == 'ribbon') {
                                this.drawCartoon(asu, all, doNotSmoothen);
                                this.drawCartoonNucleicAcid(asu, all);
                            } else if (mainchainMode == 'thickRibbon') {
                                this.drawCartoon(asu, all, doNotSmoothen, this.thickness);
                                this.drawCartoonNucleicAcid(asu, all, null, this.thickness);
                            } else if (mainchainMode == 'strand') {
                                this.drawStrand(asu, all, null, null, null, null, null, doNotSmoothen);
                                this.drawStrandNucleicAcid(asu, all);
                            } else if (mainchainMode == 'chain') {
                                this.drawMainchainCurve(asu, all, this.curveWidth, 'CA', 1);
                                this.drawMainchainCurve(asu, all, this.curveWidth, 'O3\'', 1);
                            } else if (mainchainMode == 'cylinderHelix') {
                                this.drawHelixAsCylinder(asu, all, 1.6);
                                this.drawCartoonNucleicAcid(asu, all);
                            } else if (mainchainMode == 'tube') {
                                this.drawMainchainTube(asu, all, 'CA');
                                this.drawMainchainTube(asu, all, 'O3\''); // FIXME: 5' end problem!
                            } else if (mainchainMode == 'bonds') {
                                this.drawBondsAsLine(asu, all, this.lineWidth);
                            }
                            //}

                            //if ($(idHeader + 'line').attr('checked')) {
                            //    this.drawBondsAsLine(this.modelGroup, this.getSidechains(all), this.lineWidth);
                            //}
                            //console.log("mainchain " + (+new Date() - time));
                            time = new Date();

                            //if ($(idHeader + 'showBases').attr('checked')) {
                            var hetatmMode = "nuclLine"; //$(idHeader + 'base').val();
                            if (hetatmMode == 'nuclStick') {
                                this.drawNucleicAcidStick(this.modelGroup, all);
                            } else if (hetatmMode == 'nuclLine') {
                                this.drawNucleicAcidLine(this.modelGroup, all);
                            } else if (hetatmMode == 'nuclPolygon') {
                                this.drawNucleicAcidLadder(this.modelGroup, all);
                            }
                            //}

                            var target = this.modelGroup;
                            //if ($(idHeader + 'showNonBonded').attr('checked')) {
                            //    var nonBonded = this.getNonbonded(allHet);
                            //    var nbMode = $(idHeader + 'nb').val();
                            //    if (nbMode == 'nb_sphere') {
                            //        this.drawAtomsAsIcosahedron(target, nonBonded, 0.3, true);
                            //    } else if (nbMode == 'nb_cross') {
                            //        this.drawAsCross(target, nonBonded, 0.3, true);

                            //    }
                            //}

                            //if ($(idHeader + 'showHetatms').attr('checked')) {
                            var hetatmMode = "sphere"; //$(idHeader + 'hetatm').val();
                            if (hetatmMode == 'stick') {
                                this.drawBondsAsStick(target, hetatm, this.cylinderRadius, this.cylinderRadius, true);
                            } else if (hetatmMode == 'sphere') {
                                this.drawAtomsAsSphere(target, hetatm, this.sphereRadius);
                            } else if (hetatmMode == 'line') {
                                this.drawBondsAsLine(target, hetatm, this.curveWidth);
                            } else if (hetatmMode == 'icosahedron') {
                                this.drawAtomsAsIcosahedron(target, hetatm, this.sphereRadius);
                            } else if (hetatmMode == 'ballAndStick') {
                                this.drawBondsAsStick(target, hetatm, this.cylinderRadius / 2.0, this.cylinderRadius, true, false, 0.3);
                            } else if (hetatmMode == 'ballAndStick2') {
                                this.drawBondsAsStick(target, hetatm, this.cylinderRadius / 2.0, this.cylinderRadius, true, true, 0.3);
                            }

                            //}
                            console.log("hetatms " + (+new Date() - time));
                            time = new Date();

                            var projectionMode = "perspective"; //$(idHeader + 'projection').val();
                            if (projectionMode == 'perspective') this.camera = this.perspectiveCamera;
                            else if (projectionMode == 'orthoscopic') this.camera = this.orthoscopicCamera;

                            //this.setBackground(parseInt($(idHeader + 'bgcolor').val()));

                            //if ($(idHeader + 'cell').attr('checked')) {
                            //    this.drawUnitcell(this.modelGroup);
                            //}

                            //if ($(idHeader + 'biomt').attr('checked')) {
                            //    this.drawSymmetryMates2(this.modelGroup, asu, this.protein.biomtMatrices);
                            //}
                            //if ($(idHeader + 'packing').attr('checked')) {
                            //    this.drawSymmetryMatesWithTranslation2(this.modelGroup, asu, this.protein.symMat);
                            //}
                            this.modelGroup.add(asu);
                        };
                        me.get('molViewer').loadMolecule();
                        me.set('showMolecule', true);
                        me.get('threeDeeTarget').modal('show');
                    });
                } else {
                    //already loaded, just show it
                    me.get('threeDeeTarget').modal('show');
                }
            }
        }
    }

});
<|endoftext|>


<commit_before>/**
 * The Forest2000 layer module for use on canvas.
 *
 * @return ForestLayer class (extends CanvasLayerClass)
 */
define([
  'd3', 'uri', 'moment',
  'abstract/layer/CanvasLayerClass',
  'map/presenters/layers/TerraiCanvasLayerPresenter'
], function(d3, UriTemplate, moment, CanvasLayerClass, Presenter) {

  'use strict';

  var TerraiCanvasLayer = CanvasLayerClass.extend({

    options: {
      threshold: 30,
      dataMaxZoom: 11,
      //ATTENTION: check config.ru file to get the whole route, reverse proxying here
      //urlTemplate: '/latin-america/Z{z}/{y}/{x}.png'
      urlTemplate: 'http://wri-tiles.s3.amazonaws.com/terrai_test/test1/tiles/{z}/{x}/{y}.png'
    },

    init: function(layer, options, map) {
      this.presenter = new Presenter(this);
      this.currentDate = options.currentDate || [(layer.mindate), (layer.maxdate)];
      this._super(layer, options, map);
      this.top_date = (moment(layer.maxdate).year()-2004)*23+Math.floor(moment(layer.maxdate).dayOfYear()/16);
      this.top_date -= 16;
    },

    /**
     * Filters the canvas imgdata.
     * @override
     */
    filterCanvasImgdata: function(imgdata, w, h) {
      var components = 4;
      var start = (moment(this.currentDate[0]).year()-2004)*23+Math.ceil((moment(this.currentDate[0]).dayOfYear()-1)/16);
      if (start<1) { start = 1; }
      var end   = (moment(this.currentDate[1]).year()-2004)*23+Math.floor((moment(this.currentDate[1]).dayOfYear()-1)/16);

      for(var i=0; i < w; ++i) {
        for(var j=0; j < h; ++j) {
          var pixelPos = (j*w + i) * components;

          var r = imgdata[pixelPos];
          var g = imgdata[pixelPos+1];
          var b = imgdata[pixelPos+2];
          var intensity = Math.min(b * 4, 255);

          var timeLoss = r + g;

          if (timeLoss >= start && timeLoss <= end) {
            imgdata[pixelPos]     = 220;
            imgdata[pixelPos + 1] = 102;
            imgdata[pixelPos + 2] = 153;
            imgdata[pixelPos + 3] = intensity;

            if (timeLoss > this.top_date) {
              imgdata[pixelPos]     = 233;
              imgdata[pixelPos + 1] = 189;
              imgdata[pixelPos + 2] = 21;
              imgdata[pixelPos + 3] = intensity;
            }
          } else {
            imgdata[pixelPos + 3] = 0;
          }
        }
      } //end first for loop
    },

    /**
     * Used by TerraiCanvasLayerPresenter to set the dates for the tile.
     *
     * @param {Array} date 2D array of moment dates [begin, end]
     */
    setTimelineDate: function(date) {
      this.currentDate = date;
      this.updateTiles();
    },
  });

  return TerraiCanvasLayer;

});
<commit_msg>Fix max zoom for new Terra-i layer<commit_after>/**
 * The Forest2000 layer module for use on canvas.
 *
 * @return ForestLayer class (extends CanvasLayerClass)
 */
define([
  'd3', 'uri', 'moment',
  'abstract/layer/CanvasLayerClass',
  'map/presenters/layers/TerraiCanvasLayerPresenter'
], function(d3, UriTemplate, moment, CanvasLayerClass, Presenter) {

  'use strict';

  var TerraiCanvasLayer = CanvasLayerClass.extend({

    options: {
      threshold: 30,
      dataMaxZoom: 10,
      //ATTENTION: check config.ru file to get the whole route, reverse proxying here
      //urlTemplate: '/latin-america/Z{z}/{y}/{x}.png'
      urlTemplate: 'http://wri-tiles.s3.amazonaws.com/terrai_test/test1/tiles/{z}/{x}/{y}.png'
    },

    init: function(layer, options, map) {
      this.presenter = new Presenter(this);
      this.currentDate = options.currentDate || [(layer.mindate), (layer.maxdate)];
      this._super(layer, options, map);
      this.top_date = (moment(layer.maxdate).year()-2004)*23+Math.floor(moment(layer.maxdate).dayOfYear()/16);
      this.top_date -= 16;
    },

    /**
     * Filters the canvas imgdata.
     * @override
     */
    filterCanvasImgdata: function(imgdata, w, h) {
      var components = 4;
      var start = (moment(this.currentDate[0]).year()-2004)*23+Math.ceil((moment(this.currentDate[0]).dayOfYear()-1)/16);
      if (start<1) { start = 1; }
      var end   = (moment(this.currentDate[1]).year()-2004)*23+Math.floor((moment(this.currentDate[1]).dayOfYear()-1)/16);

      for(var i=0; i < w; ++i) {
        for(var j=0; j < h; ++j) {
          var pixelPos = (j*w + i) * components;

          var r = imgdata[pixelPos];
          var g = imgdata[pixelPos+1];
          var b = imgdata[pixelPos+2];
          var intensity = Math.min(b * 4, 255);

          var timeLoss = r + g;

          if (timeLoss >= start && timeLoss <= end) {
            imgdata[pixelPos]     = 220;
            imgdata[pixelPos + 1] = 102;
            imgdata[pixelPos + 2] = 153;
            imgdata[pixelPos + 3] = intensity;

            if (timeLoss > this.top_date) {
              imgdata[pixelPos]     = 233;
              imgdata[pixelPos + 1] = 189;
              imgdata[pixelPos + 2] = 21;
              imgdata[pixelPos + 3] = intensity;
            }
          } else {
            imgdata[pixelPos + 3] = 0;
          }
        }
      } //end first for loop
    },

    /**
     * Used by TerraiCanvasLayerPresenter to set the dates for the tile.
     *
     * @param {Array} date 2D array of moment dates [begin, end]
     */
    setTimelineDate: function(date) {
      this.currentDate = date;
      this.updateTiles();
    },
  });

  return TerraiCanvasLayer;

});
<|endoftext|>


<commit_before>/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 11/4/12
 * Time: 9:24 PM
 * To change this template use File | Settings | File Templates.
 */
define([], function defineLibFile() {

    /**
     * Define LibFile
     * @class LibFile
     * @constructor
     */
    var LibFile = function LibFile() {
    };

    LibFile.extend('LibFile', {

        /**
         * Check API
         * @memberOf LibFile
         * @returns {boolean}
         */
        checkFileApi: function checkFileApi() {

            // Get scope
            var scope = this.view.scope;

            // Check for the various File API support.
            if (window.File && window.FileReader && window.FileList && window.Blob) {
                scope.logger.debug('Great success! All the File APIs are supported');
                return true;
            } else {
                scope.logger.warn('The File APIs are not fully supported in this browser');
                return false;
            }
        },

        /**
         * Create Blob URL
         * @memberOf LibFile
         * @param {string} content
         * @param {string} type
         * @param {string} fname
         * @returns {string}
         */
        createURL: function createURL(content, type, fname) {

            /**
             * Define blob instance
             * @type {Blob}
             */
            var blob = this._base64toBlob(
                content,
                type
            );

            return (navigator.appVersion.toString().indexOf('.NET') > 0) ?
                window.navigator.msSaveOrOpenBlob(blob, fname) :
                window.URL.createObjectURL(blob);
        },

        /**
         * Define convert base64 to blob
         * @memberOf LibFile
         * @param {string} base64Data
         * @param {string} contentType
         * @returns {*}
         * @private
         */
        _base64toBlob: function _base64toBlob(base64Data, contentType) {

            contentType = contentType || '';

            var sliceSize = 1024,
                byteCharacters = decodeURIComponent(atob(base64Data)),
                bytesLength = byteCharacters.length,
                slicesCount = Math.ceil(bytesLength / sliceSize),
                byteArrays = new Array(slicesCount),
                sliceIndex = 0,
                blob;

            for (; sliceIndex < slicesCount; ++sliceIndex) {

                var begin = sliceIndex * sliceSize,
                    end = Math.min(begin + sliceSize, bytesLength),
                    bytes = new Array(end - begin);

                for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
                    bytes[i] = byteCharacters[offset].charCodeAt(0);
                }

                byteArrays[sliceIndex] = new Uint8Array(bytes);
            }

            try {

                /**
                 * Define blob
                 * @type {Blob}
                 */
                blob = new Blob(byteArrays, {type: contentType});

            } catch (e) {

                // TypeError old chrome and FF
                window.BlobBuilder = window.BlobBuilder ||
                window.WebKitBlobBuilder ||
                window.MozBlobBuilder ||
                window.MSBlobBuilder;

                if (e.name == 'TypeError' && window.BlobBuilder) {

                    /**
                     * Define blob builder
                     * @type {BlobBuilder}
                     */
                    var bb = new BlobBuilder();

                    bb.append(byteArrays);
                    blob = bb.getBlob(contentType);

                } else if (e.name == "InvalidStateError") {

                    // InvalidStateError (tested on FF13 WinXP)
                    blob = new Blob(byteArrays, {type: contentType});

                } else {

                    // We're screwed, blob constructor unsupported entirely
                }
            }

            return blob;
        }
    });

    return new LibFile();
});<commit_msg>add binary reader reader<commit_after>/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 11/4/12
 * Time: 9:24 PM
 * To change this template use File | Settings | File Templates.
 */
define([], function defineLibFile() {

    /**
     * Define LibFile
     * @class LibFile
     * @constructor
     */
    var LibFile = function LibFile() {
    };

    LibFile.extend('LibFile', {

        /**
         * Check API
         * @memberOf LibFile
         * @returns {boolean}
         */
        checkFileApi: function checkFileApi() {

            // Get scope
            var scope = this.view.scope;

            // Check for the various File API support.
            if (window.File && window.FileReader && window.FileList && window.Blob) {
                scope.logger.debug('Great success! All the File APIs are supported');
                return true;
            } else {
                scope.logger.warn('The File APIs are not fully supported in this browser');
                return false;
            }
        },

        /**
         * Define binary file reader
         * @memberOf LibFile
         * @param file
         * @param {Function} callback
         * @param {boolean} [base64]
         * @returns {boolean}
         */
        readBinaryFile: function readBinaryFile(file, callback, base64) {

            if (typeof(file) === 'undefined') {
                return false;
            }

            base64 = typeof(base64) === 'undefined' ? true : base64;

            /**
             * Define reader
             * @type {FileReader}
             */
            var reader = new FileReader();

            reader.onloadend = function onLoadEnd(evt) {

                if (evt.target.readyState === this.reader.DONE) {

                    var chars = new Uint8Array(evt.target.result),
                        CHUNK_SIZE = 0x8000,
                        index = 0, length = chars.length,
                        result = '', slice;

                    while (index < length) {
                        slice = chars.subarray(index, Math.min(index + CHUNK_SIZE, length));
                        result += String.fromCharCode.apply(null, slice);
                        index += CHUNK_SIZE;
                    }

                    callback(base64 ? window.btoa(result) : result);
                }
            };

            reader.readAsArrayBuffer(file);
        },

        /**
         * Create Blob URL
         * @memberOf LibFile
         * @param {string} content
         * @param {string} type
         * @param {string} fname
         * @returns {string}
         */
        createURL: function createURL(content, type, fname) {

            /**
             * Define blob instance
             * @type {Blob}
             */
            var blob = this._base64toBlob(
                content,
                type
            );

            return (navigator.appVersion.toString().indexOf('.NET') > 0) ?
                window.navigator.msSaveOrOpenBlob(blob, fname) :
                window.URL.createObjectURL(blob);
        },

        /**
         * Define convert base64 to blob
         * @memberOf LibFile
         * @param {string} base64Data
         * @param {string} contentType
         * @returns {*}
         * @private
         */
        _base64toBlob: function _base64toBlob(base64Data, contentType) {

            contentType = contentType || '';

            var sliceSize = 1024,
                byteCharacters = decodeURIComponent(atob(base64Data)),
                bytesLength = byteCharacters.length,
                slicesCount = Math.ceil(bytesLength / sliceSize),
                byteArrays = new Array(slicesCount),
                sliceIndex = 0,
                blob;

            for (; sliceIndex < slicesCount; ++sliceIndex) {

                var begin = sliceIndex * sliceSize,
                    end = Math.min(begin + sliceSize, bytesLength),
                    bytes = new Array(end - begin);

                for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
                    bytes[i] = byteCharacters[offset].charCodeAt(0);
                }

                byteArrays[sliceIndex] = new Uint8Array(bytes);
            }

            try {

                /**
                 * Define blob
                 * @type {Blob}
                 */
                blob = new Blob(byteArrays, {type: contentType});

            } catch (e) {

                // TypeError old chrome and FF
                window.BlobBuilder = window.BlobBuilder ||
                window.WebKitBlobBuilder ||
                window.MozBlobBuilder ||
                window.MSBlobBuilder;

                if (e.name == 'TypeError' && window.BlobBuilder) {

                    /**
                     * Define blob builder
                     * @type {BlobBuilder}
                     */
                    var bb = new BlobBuilder();

                    bb.append(byteArrays);
                    blob = bb.getBlob(contentType);

                } else if (e.name == "InvalidStateError") {

                    // InvalidStateError (tested on FF13 WinXP)
                    blob = new Blob(byteArrays, {type: contentType});

                } else {

                    // We're screwed, blob constructor unsupported entirely
                }
            }

            return blob;
        }
    });

    return new LibFile();
});<|endoftext|>


<commit_before>// @flow
import React, { Component } from 'react';
import classnames from 'classnames';
import { asYouType, format, getPhoneCode } from 'libphonenumber-js';
import { get, findIndex } from 'lodash';
import { FormattedMessage } from 'react-intl';
import onClickOutside from 'react-onclickoutside';
import countryCodes from './country-codes.json';
import SweetInput from '../SweetInput/SweetInput';
import SelectCountry from '../SelectCountry/SelectCountry';

import './SweetPhoneInput.scss';

type Props = {
  value: string,
  onChange: (number: string) => void,
  title?: any,
  className?: string,
  defaultCountryCode?: string,
  restrictedCountryCode?: string,
};

type State = {
  countryCode?: string,
  phoneNumber: string,
  selectingCountry: boolean,
};

class SweetPhoneInput extends Component {
  props: Props;
  state: State;
  selectCountry: any;

  constructor(props: Props) {
    super(props);
    this.state = {
      countryCode: undefined,
      phoneNumber: props.value || '',
      selectingCountry: false,
    };
  }

  getCountryCode() {
    if (!this.state) {
      return this.props.defaultCountryCode || this.defaultCountry();
    }

    return (
      this.state.countryCode ||
      this.props.defaultCountryCode ||
      this.defaultCountry()
    );
  }

  defaultCountry(): string {
    return get(window, 'champaign.personalization.location.country', 'US');
  }

  handleClickOutside(e: SyntheticEvent) {
    this.setState(state => ({ ...state, selectingCountry: false }));
  }

  defaultTitle() {
    return (
      <FormattedMessage
        id="call_tool.member_phone_number_title"
        defaultMessage="Enter your phone number"
      />
    );
  }

  onPhoneNumberChange = (value: string = '') => {
    this.setState(prevState => ({
      ...prevState,
      phoneNumber: format(value, this.getCountryCode(), 'National'),
    }));
    this.props.onChange(format(value, this.getCountryCode(), 'International'));
  };

  onCountryCodeChange = (countryCode: string) => {
    if (!countryCode) return;

    this.setState(
      state => ({
        ...state,
        countryCode,
        selectingCountry: false,
      }),
      () => {
        if (this.refs.phoneInput) {
          this.refs.phoneInput.focus();
        }
      }
    );
  };

  toggleSelectingCountry = () => {
    this.setState(
      state => ({
        ...state,
        selectingCountry: !state.selectingCountry,
      }),
      () => {
        if (this.state.selectingCountry) {
          this.refs.select.refs.wrappedInstance.focus();
        }
      }
    );
  };

  render() {
    const { restrictedCountryCode } = this.props;
    const className = classnames(
      {
        SweetPhoneInput__root: true,
        'selecting-country': this.state.selectingCountry,
      },
      this.props.className
    );

    return (

          {this.props.title || this.defaultTitle()}

              + {getPhoneCode(this.getCountryCode())}

            <input
              ref="phoneInput"
              className="SweetPhoneInput__phone-number-input"
              type="tel"
              value={this.state.phoneNumber}
              onChange={e => this.onPhoneNumberChange(e.target.value)}
            />

          <SelectCountry
            ref="select"
            className="SweetPhoneInput__select-country"
            clearable={false}
            label="Select your country..."
            value={this.getCountryCode()}
            filter={restrictedCountryCode ? [restrictedCountryCode] : null}
            onChange={code => this.onCountryCodeChange(code)}
          />

    );
  }
}

const X: typeof SweetPhoneInput = onClickOutside(SweetPhoneInput);

export default X;
<commit_msg>further restrict country selector interface when select-by-country disabled<commit_after>// @flow
import React, { Component } from 'react';
import classnames from 'classnames';
import { asYouType, format, getPhoneCode } from 'libphonenumber-js';
import { get, findIndex } from 'lodash';
import { FormattedMessage } from 'react-intl';
import onClickOutside from 'react-onclickoutside';
import countryCodes from './country-codes.json';
import SweetInput from '../SweetInput/SweetInput';
import SelectCountry from '../SelectCountry/SelectCountry';

import './SweetPhoneInput.scss';

type Props = {
  value: string,
  onChange: (number: string) => void,
  title?: any,
  className?: string,
  defaultCountryCode?: string,
  restrictedCountryCode?: string,
};

type State = {
  countryCode?: string,
  phoneNumber: string,
  selectingCountry: boolean,
};

class SweetPhoneInput extends Component {
  props: Props;
  state: State;
  selectCountry: any;

  constructor(props: Props) {
    super(props);
    this.state = {
      countryCode: undefined,
      phoneNumber: props.value || '',
      selectingCountry: false,
    };
  }

  getCountryCode() {
    if (!this.state) {
      return this.props.defaultCountryCode || this.defaultCountry();
    }

    return (
      this.state.countryCode ||
      this.props.defaultCountryCode ||
      this.defaultCountry()
    );
  }

  defaultCountry(): string {
    return get(window, 'champaign.personalization.location.country', 'US');
  }

  handleClickOutside(e: SyntheticEvent) {
    this.setState(state => ({ ...state, selectingCountry: false }));
  }

  defaultTitle() {
    return (
      <FormattedMessage
        id="call_tool.member_phone_number_title"
        defaultMessage="Enter your phone number"
      />
    );
  }

  onPhoneNumberChange = (value: string = '') => {
    this.setState(prevState => ({
      ...prevState,
      phoneNumber: format(value, this.getCountryCode(), 'National'),
    }));
    this.props.onChange(format(value, this.getCountryCode(), 'International'));
  };

  onCountryCodeChange = (countryCode: string) => {
    if (!countryCode) return;

    this.setState(
      state => ({
        ...state,
        countryCode,
        selectingCountry: false,
      }),
      () => {
        if (this.refs.phoneInput) {
          this.refs.phoneInput.focus();
        }
      }
    );
  };

  toggleSelectingCountry = () => {
    this.setState(
      state => ({
        ...state,
        selectingCountry: !state.selectingCountry,
      }),
      () => {
        if (this.state.selectingCountry) {
          this.refs.select.refs.wrappedInstance.focus();
        }
      }
    );
  };

  render() {
    const { restrictedCountryCode } = this.props;
    const className = classnames(
      {
        SweetPhoneInput__root: true,
        'selecting-country': this.state.selectingCountry,
      },
      this.props.className
    );

    return (

          {this.props.title || this.defaultTitle()}

              + {getPhoneCode(this.getCountryCode())}

            {!restrictedCountryCode &&
              }

            <input
              ref="phoneInput"
              className="SweetPhoneInput__phone-number-input"
              type="tel"
              value={this.state.phoneNumber}
              onChange={e => this.onPhoneNumberChange(e.target.value)}
            />

          <SelectCountry
            ref="select"
            className="SweetPhoneInput__select-country"
            clearable={false}
            label="Select your country..."
            value={this.getCountryCode()}
            filter={restrictedCountryCode ? [restrictedCountryCode] : null}
            onChange={code => this.onCountryCodeChange(code)}
          />

    );
  }
}

const X: typeof SweetPhoneInput = onClickOutside(SweetPhoneInput);

export default X;
<|endoftext|>


<commit_before>'use strict';

angular
.module('app.controllers')
.controller('MembershipAddCtrl', function($scope, $rootScope, $stateParams, $state,
		$interval, Restangular, apiDescriptor, formElementProvider, dataTransformer) {

	var resourceName = $stateParams.resourceName;

	var resource = Restangular.all(resourceName);

	$scope.fep = formElementProvider;

	$scope.data = {};
	$scope.model = {attributes: {}};

	apiDescriptor.then(function(apiDescription) {
		$scope.rdesc = apiDescription.resource(resourceName);
		$scope.data = dataTransformer.loadLinkedData($scope.rdesc, $scope.refreshData);
	});

	$scope.createResource = function (model, rdesc) {
		dataTransformer.createResource(model, rdesc, resource).then(function(data) {
			$state.go('list', {resourceName: resourceName, selectionMode: 'single', id: data.id});
		});
	}

	//data: array of array type data
	//fieldResourceType: which field to grab
	$scope.refreshData = function(data, fieldResourceType) {
		data[fieldResourceType] = Restangular.all(fieldResourceType).getList().$object;
	};
});
<commit_msg>fixed line spacing<commit_after>'use strict';

angular
.module('app.controllers')
.controller('MembershipAddCtrl', function($scope, $rootScope, $stateParams, $state,
		$interval, Restangular, apiDescriptor, formElementProvider, dataTransformer) {

	var resourceName = $stateParams.resourceName;

	var resource = Restangular.all(resourceName);

	$scope.fep = formElementProvider;

	$scope.data = {};
	$scope.model = {attributes: {}};

	apiDescriptor.then(function(apiDescription) {
		$scope.rdesc = apiDescription.resource(resourceName);
		$scope.data = dataTransformer.loadLinkedData($scope.rdesc, $scope.refreshData);
	});

	$scope.createResource = function (model, rdesc) {
		dataTransformer.createResource(model, rdesc, resource).then(function(data) {
			$state.go('list', {resourceName: resourceName, selectionMode: 'single', id: data.id});
		});
	}

	//data: array of array type data
	//fieldResourceType: which field to grab
	$scope.refreshData = function(data, fieldResourceType) {
		data[fieldResourceType] = Restangular.all(fieldResourceType).getList().$object;
	};
});
<|endoftext|>


<commit_before>//Given mmd, representing the mmd of this page.

var currentMMDField;
//var xpathResult = document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result );
//More info at: https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript
//Mozilla has better documentation, but we're using chromium.
//Not to worry, we're working with standards here. Both browsers implement the XPath defined in
// http://www.w3.org/TR/2004/NOTE-DOM-Level-3-XPath-20040226/DOM3-XPath.html

function extractMetadata(mmd)
{
    mmd = mmd.meta_metadata;
    var metadata = recursivelyExtractMetadata(mmd, document, metadata);
    var returnVal = {};
    returnVal[mmd.name] = metadata;

    //return returnVal;
    return JSON.stringify(returnVal);

}

function recursivelyExtractMetadata(mmd, contextNode, metadata) {
    if (metadata == null || metadata == undefined)
        metadata = {}; //Output

    if (mmd.kids == null || mmd.kids.length == 0) {
        console.log("\t\tMMD has no kids: " + mmd.name);
        return; //Nothing to do here.
    }
    if (contextNode == null || contextNode == undefined)
        contextNode = document;
    for (mmdFieldIndex in mmd.kids) {
        var mmdField = mmd.kids[mmdFieldIndex];
        currentMMDField = mmdField;
        console.log("Iterating to Next mmdField");
        console.log(mmdField);

        if (mmdField.scalar != null && mmdField.scalar.xpath != null) {
            console.log("Setting scalar: " + mmdField.scalar.name);
            extractScalar(mmdField.scalar, contextNode, metadata);
        }

        if (mmdField.collection != null) {
            console.log("Setting Collection: " + mmdField.collection.name);
            extractCollection(mmdField.collection, contextNode, metadata);
        }

        if (mmdField.composite != null) {
            console.log("Setting Composite: " + mmdField.composite.name);
            extractComposite(mmdField.composite, contextNode, metadata);
        }
        console.log("Recursive extraction result: ");
        console.info(metadata);
    }
    console.log("Returning Metadata: ");
    console.info(metadata);
    return metadata;
}

function extractScalar(mmdScalarField, contextNode, metadata)
{
    var stringValue = getScalarWithXPath(contextNode, mmdScalarField.xpath);
		stringValue = stringValue.replace(new RegExp('\n', 'g'), "");
		stringValue = stringValue.trim();
    if (mmdScalarField.filter != null)
    {
        var regex = mmdScalarField.filter.regex;
        var replace = mmdScalarField.filter.replace;
        if (replace != undefined && replace != "") // We must replace all newlines if the replacement is not a empty character
				{
						stringValue = stringValue.replace(new RegExp(regex, 'g'), replace);
				}
        else
				{
						stringValue = stringValue.match(new RegExp(regex));
				}
    }

    if (mmdScalarField.tag != null && mmdScalarField.tag != mmdScalarField.name)
        metadata[mmdScalarField.tag] = stringValue;
    else
        metadata[mmdScalarField.name] = stringValue;
}

function extractCollection(mmdCollectionField, contextNode, metadata)
{
    console.log("Setting Collection: " + mmdCollectionField.name);
    //nodeList is a XPathResult type, access items with snapshotItem(index)
    var nodeList = getNodeListWithXPath(contextNode, mmdCollectionField.xpath);
    var metadataCollection = [];

    if (mmdCollectionField.child_type == "hypertext_para") {
        //Special field, for now. Parser needs to change it's ways to handle hypertext
        parseNodeListAsHypertext(mmdCollectionField, nodeList, metadata);
        return; //This collection is special. No further normal processing required.
    }

    var collectionFields = mmdCollectionField.kids;

    if (collectionFields == null || collectionFields == undefined)
        console.log("Oops, collection fields doesn't exist");
    for (var resultIndex = 0; resultIndex < nodeList.snapshotLength; resultIndex++) {
        console.log("\tCollection Result Index: " + resultIndex);
        //recursive call.
        var recursiveContext = nodeList.snapshotItem(resultIndex);
        var metadataCollectionItem = {};
        for (var fieldIndex = 0; fieldIndex < collectionFields.length; fieldIndex++) {
            var recursiveField = collectionFields[fieldIndex];
            console.log("\tCollection Recursive Call: ");
            console.log(recursiveField);

            if (recursiveField.scalar != null)
                extractScalar(recursiveField.scalar, recursiveContext, metadataCollectionItem);
            else if (recursiveField.collection != null)
                extractCollection(recursiveField.collection, recursiveContext, metadataCollectionItem);
            else if (recursiveField.composite != null)
                extractComposite(recursiveField.composite, recursiveContext, metadataCollectionItem);

            console.log("Metadata Collection Item: ");
            console.info(metadataCollection);
        }
        metadataCollection.push(metadataCollectionItem);
    }
    var extractedCollection = {};
    console.log("Metadata Collection: ");
    console.info(metadataCollection);
    extractedCollection[mmdCollectionField.child_type] = metadataCollection;
    metadata[mmdCollectionField.name] = extractedCollection;
}

function extractComposite(mmdCompositeField, contextNode, metadata)
{
    if (contextNode == null)
        return null;

    console.log("Setting Composite: " + mmdCompositeField.name);

    if (mmdCompositeField.parse_as_hypertext == true || mmdCompositeField.type == "hypertext_para") {
        var paraNode = getNodeWithXPath(contextNode, mmdCompositeField.xpath);
        var parsedPara = parseHypertextParaFromNode(paraNode);
        metadata[mmdCompositeField.name] = parsedPara;
        return;
    }

    compositeMetadata = {};

    console.log("Composite Recursive call: ");
    console.info(mmdCompositeField);
    //Apply xpath of composite node if it exists
    var newContextNode = contextNode;
    if (mmdCompositeField.xpath != null)
        newContextNode = getNodeWithXPath(contextNode, mmdCompositeField.xpath);

    compositeMetadata = recursivelyExtractMetadata(mmdCompositeField, newContextNode, compositeMetadata);

    console.log("Composite Recursive Result ---------- : ");
    console.info(compositeMetadata);
    metadata[mmdCompositeField.name] = compositeMetadata;

}

function parseNodeListAsHypertext(mmdCollectionField, paras, metadata) {

    console.log("Found hypertext nodes: ");
    console.info(paras);

    var parsedParas = [];

    for (var resultIndex = 0; resultIndex < paras.snapshotLength; resultIndex++) {

        var hypertextNode = paras.snapshotItem(resultIndex);
        //console.log("Current Paragraph parsed: ");
        //console.info(hypertextNode);
        //console.log("Number of childNodes : " + hypertextNode.childNodes.length);

        var paraContainer = {};
        paraContainer[mmdCollectionField.child_type] = parseHypertextParaFromNode(hypertextNode);

        //console.info(hypertextPara);
        parsedParas.push(paraContainer);
    }
    console.info(parsedParas);

    metadata[mmdCollectionField.name] = parsedParas;
}

function parseHypertextParaFromNode(hypertextNode) {

    //internal functions
    function getLinkRun(node) {
        var link_run = {};
        link_run["text"] = node.textContent;
        link_run["location"] = node.href;
        link_run["title"] = node.title; //Wiki specific !
        return link_run;
    }
    function getTextRun(node, formattedRun) {
        var text_run = formattedRun == null ? {} : formattedRun;
        text_run.text = node.textContent;
        return text_run;
    }

    var hypertextPara = {};
    runs = [];
    hypertextPara["runs"] = runs;

    for (var nodeNum = 0; nodeNum < hypertextNode.childNodes.length; nodeNum++) {
        var curNode = hypertextNode.childNodes[nodeNum];
        var nodeName = curNode.nodeName;
        //console.info(curNode);
        var resNode = {};
        if (nodeName == "#text" || nodeName == "SPAN") {
            //console.log("Text: " + curNode.textContent);
            resNode["text_run"] = getTextRun(curNode);

        }
        else if (nodeName == "A") {
            //No further parsing just pull values out.
            resNode["link_run"] = getLinkRun(curNode);
        }
        else if (nodeName == "B") {
            formattedRun = {};
            var styleInfo = {}

            styleInfo["bold"] = true;
            formattedRun["style_info"] = styleInfo;
            if (curNode.childElementCount == 0) {
                resNode["text_run"] = getTextRun(curNode, formattedRun);
                //console.log("Simple bold : " + curNode.text);
            }
            else {
                console.log("Bold link ?");
                //console.log("NestedBold: ");
                //console.info(curNode);
            }
        }
        else if (nodeName == "I") {
            formattedRun = {};
            var styleInfo = {}
            styleInfo["italics"] = true;
            formattedRun["style_info"] = styleInfo;
            resNode["text_run"] = getTextRun(curNode, formattedRun);
        }
        else {
            console.log("IgnoredNode: ");
            console.info(curNode);
        }
        if (!isEmpty(resNode))
            runs.push(resNode);
    }
    return hypertextPara;
}

//Util functions, to make the above functions a little prettier

function isEmpty(ob) {
    for(var i in ob) {return false;}
    return true;
}

/**
* All scalars can be considered strings. Type holds no value in javascript (yet).
*/
function getScalarWithXPath(contextNode, xpath)
{
    return document.evaluate(xpath, contextNode, null, XPathResult.STRING_TYPE, null).stringValue;
}

/**
* Uses getNodeListWithXPath, but verifies and returns only the first value.
*/
function getNodeWithXPath(contextNode, xpath)
{
    var nodelist = getNodeListWithXPath(contextNode, xpath);
    if (nodelist.snapshotLength == 0)
        return null;
    else
        return nodelist.snapshotItem(0);

}

function getNodeListWithXPath(contextNode, xpath) {
    return document.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

}
<commit_msg>fixing regex filter for scalars: when not specifying replace, use regex to extract things.<commit_after>//Given mmd, representing the mmd of this page.

var currentMMDField;
//var xpathResult = document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result );
//More info at: https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript
//Mozilla has better documentation, but we're using chromium.
//Not to worry, we're working with standards here. Both browsers implement the XPath defined in
// http://www.w3.org/TR/2004/NOTE-DOM-Level-3-XPath-20040226/DOM3-XPath.html

function extractMetadata(mmd)
{
    mmd = mmd.meta_metadata;
    var metadata = recursivelyExtractMetadata(mmd, document, metadata);
    var returnVal = {};
    returnVal[mmd.name] = metadata;

    //return returnVal;
    return JSON.stringify(returnVal);

}

function recursivelyExtractMetadata(mmd, contextNode, metadata) {
    if (metadata == null || metadata == undefined)
        metadata = {}; //Output

    if (mmd.kids == null || mmd.kids.length == 0) {
        console.log("\t\tMMD has no kids: " + mmd.name);
        return; //Nothing to do here.
    }
    if (contextNode == null || contextNode == undefined)
        contextNode = document;
    for (mmdFieldIndex in mmd.kids) {
        var mmdField = mmd.kids[mmdFieldIndex];
        currentMMDField = mmdField;
        console.log("Iterating to Next mmdField");
        console.log(mmdField);

        if (mmdField.scalar != null && mmdField.scalar.xpath != null) {
            console.log("Setting scalar: " + mmdField.scalar.name);
            extractScalar(mmdField.scalar, contextNode, metadata);
        }

        if (mmdField.collection != null) {
            console.log("Setting Collection: " + mmdField.collection.name);
            extractCollection(mmdField.collection, contextNode, metadata);
        }

        if (mmdField.composite != null) {
            console.log("Setting Composite: " + mmdField.composite.name);
            extractComposite(mmdField.composite, contextNode, metadata);
        }
        console.log("Recursive extraction result: ");
        console.info(metadata);
    }
    console.log("Returning Metadata: ");
    console.info(metadata);
    return metadata;
}

function extractScalar(mmdScalarField, contextNode, metadata)
{
    var stringValue = getScalarWithXPath(contextNode, mmdScalarField.xpath);
		stringValue = stringValue.replace(new RegExp('\n', 'g'), "");
		stringValue = stringValue.trim();
    if (mmdScalarField.filter != null)
    {
        var regex = mmdScalarField.filter.regex;
        var replace = mmdScalarField.filter.replace;
        if (replace != undefined && replace != "") // We must replace all newlines if the replacement is not a empty character
				{
						stringValue = stringValue.replace(new RegExp(regex, 'g'), replace);
				}
        else
				{
						stringValue = stringValue.match(new RegExp(regex))[0];
				}
    }

    if (mmdScalarField.tag != null && mmdScalarField.tag != mmdScalarField.name)
        metadata[mmdScalarField.tag] = stringValue;
    else
        metadata[mmdScalarField.name] = stringValue;
}

function extractCollection(mmdCollectionField, contextNode, metadata)
{
    console.log("Setting Collection: " + mmdCollectionField.name);
    //nodeList is a XPathResult type, access items with snapshotItem(index)
    var nodeList = getNodeListWithXPath(contextNode, mmdCollectionField.xpath);
    var metadataCollection = [];

    if (mmdCollectionField.child_type == "hypertext_para") {
        //Special field, for now. Parser needs to change it's ways to handle hypertext
        parseNodeListAsHypertext(mmdCollectionField, nodeList, metadata);
        return; //This collection is special. No further normal processing required.
    }

    var collectionFields = mmdCollectionField.kids;

    if (collectionFields == null || collectionFields == undefined)
        console.log("Oops, collection fields doesn't exist");
    for (var resultIndex = 0; resultIndex < nodeList.snapshotLength; resultIndex++) {
        console.log("\tCollection Result Index: " + resultIndex);
        //recursive call.
        var recursiveContext = nodeList.snapshotItem(resultIndex);
        var metadataCollectionItem = {};
        for (var fieldIndex = 0; fieldIndex < collectionFields.length; fieldIndex++) {
            var recursiveField = collectionFields[fieldIndex];
            console.log("\tCollection Recursive Call: ");
            console.log(recursiveField);

            if (recursiveField.scalar != null)
                extractScalar(recursiveField.scalar, recursiveContext, metadataCollectionItem);
            else if (recursiveField.collection != null)
                extractCollection(recursiveField.collection, recursiveContext, metadataCollectionItem);
            else if (recursiveField.composite != null)
                extractComposite(recursiveField.composite, recursiveContext, metadataCollectionItem);

            console.log("Metadata Collection Item: ");
            console.info(metadataCollection);
        }
        metadataCollection.push(metadataCollectionItem);
    }
    var extractedCollection = {};
    console.log("Metadata Collection: ");
    console.info(metadataCollection);
    extractedCollection[mmdCollectionField.child_type] = metadataCollection;
    metadata[mmdCollectionField.name] = extractedCollection;
}

function extractComposite(mmdCompositeField, contextNode, metadata)
{
    if (contextNode == null)
        return null;

    console.log("Setting Composite: " + mmdCompositeField.name);

    if (mmdCompositeField.parse_as_hypertext == true || mmdCompositeField.type == "hypertext_para") {
        var paraNode = getNodeWithXPath(contextNode, mmdCompositeField.xpath);
        var parsedPara = parseHypertextParaFromNode(paraNode);
        metadata[mmdCompositeField.name] = parsedPara;
        return;
    }

    compositeMetadata = {};

    console.log("Composite Recursive call: ");
    console.info(mmdCompositeField);
    //Apply xpath of composite node if it exists
    var newContextNode = contextNode;
    if (mmdCompositeField.xpath != null)
        newContextNode = getNodeWithXPath(contextNode, mmdCompositeField.xpath);

    compositeMetadata = recursivelyExtractMetadata(mmdCompositeField, newContextNode, compositeMetadata);

    console.log("Composite Recursive Result ---------- : ");
    console.info(compositeMetadata);
    metadata[mmdCompositeField.name] = compositeMetadata;

}

function parseNodeListAsHypertext(mmdCollectionField, paras, metadata) {

    console.log("Found hypertext nodes: ");
    console.info(paras);

    var parsedParas = [];

    for (var resultIndex = 0; resultIndex < paras.snapshotLength; resultIndex++) {

        var hypertextNode = paras.snapshotItem(resultIndex);
        //console.log("Current Paragraph parsed: ");
        //console.info(hypertextNode);
        //console.log("Number of childNodes : " + hypertextNode.childNodes.length);

        var paraContainer = {};
        paraContainer[mmdCollectionField.child_type] = parseHypertextParaFromNode(hypertextNode);

        //console.info(hypertextPara);
        parsedParas.push(paraContainer);
    }
    console.info(parsedParas);

    metadata[mmdCollectionField.name] = parsedParas;
}

function parseHypertextParaFromNode(hypertextNode) {

    //internal functions
    function getLinkRun(node) {
        var link_run = {};
        link_run["text"] = node.textContent;
        link_run["location"] = node.href;
        link_run["title"] = node.title; //Wiki specific !
        return link_run;
    }
    function getTextRun(node, formattedRun) {
        var text_run = formattedRun == null ? {} : formattedRun;
        text_run.text = node.textContent;
        return text_run;
    }

    var hypertextPara = {};
    runs = [];
    hypertextPara["runs"] = runs;

    for (var nodeNum = 0; nodeNum < hypertextNode.childNodes.length; nodeNum++) {
        var curNode = hypertextNode.childNodes[nodeNum];
        var nodeName = curNode.nodeName;
        //console.info(curNode);
        var resNode = {};
        if (nodeName == "#text" || nodeName == "SPAN") {
            //console.log("Text: " + curNode.textContent);
            resNode["text_run"] = getTextRun(curNode);

        }
        else if (nodeName == "A") {
            //No further parsing just pull values out.
            resNode["link_run"] = getLinkRun(curNode);
        }
        else if (nodeName == "B") {
            formattedRun = {};
            var styleInfo = {}

            styleInfo["bold"] = true;
            formattedRun["style_info"] = styleInfo;
            if (curNode.childElementCount == 0) {
                resNode["text_run"] = getTextRun(curNode, formattedRun);
                //console.log("Simple bold : " + curNode.text);
            }
            else {
                console.log("Bold link ?");
                //console.log("NestedBold: ");
                //console.info(curNode);
            }
        }
        else if (nodeName == "I") {
            formattedRun = {};
            var styleInfo = {}
            styleInfo["italics"] = true;
            formattedRun["style_info"] = styleInfo;
            resNode["text_run"] = getTextRun(curNode, formattedRun);
        }
        else {
            console.log("IgnoredNode: ");
            console.info(curNode);
        }
        if (!isEmpty(resNode))
            runs.push(resNode);
    }
    return hypertextPara;
}

//Util functions, to make the above functions a little prettier

function isEmpty(ob) {
    for(var i in ob) {return false;}
    return true;
}

/**
* All scalars can be considered strings. Type holds no value in javascript (yet).
*/
function getScalarWithXPath(contextNode, xpath)
{
    return document.evaluate(xpath, contextNode, null, XPathResult.STRING_TYPE, null).stringValue;
}

/**
* Uses getNodeListWithXPath, but verifies and returns only the first value.
*/
function getNodeWithXPath(contextNode, xpath)
{
    var nodelist = getNodeListWithXPath(contextNode, xpath);
    if (nodelist.snapshotLength == 0)
        return null;
    else
        return nodelist.snapshotItem(0);

}

function getNodeListWithXPath(contextNode, xpath) {
    return document.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

}
<|endoftext|>