<commit_before>function calculateEMI() {

var P = $("#la_value").html();
var n = $("#nm_value").html();
var r = $("#roi_value").html();
var t = Math.floor(n/3); // Quarterly

temp=(1+r/n);
        A=P*Math.pow(temp,(n*t));
        I=A-P;

$("#tbl_de").html( P.toFixed(0).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
$("#tbl_full").html(A.toFixed(2).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
$("#tbl_int").html(I.toFixed(2).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));

		var chart = new Highcharts.Chart({

						chart: {
							plotBackgroundColor: null,
							plotBorderWidth: null,
							plotShadow: false,
						    renderTo: 'container'

						},
						tooltip: {
							//pointFormat: '{series.name}: {point.value}%'
						},
	title:{
    text:''
},
	credits: {
    enabled: false
  },
						plotOptions: {
							pie: {
								allowPointSelect: true,
								showInLegend:true,
								cursor: 'pointer',
								dataLabels: {
								    enabled: false,
									color: '#000000',
									connectorColor: '#000000',
									format: '{point.name}: {point.percentage:.1f} %'
								}
							}
						},
						series: [{
							type: 'pie',
							name: 'Amount',
							data: [
								['Principal',   eval(depositedAmount.toFixed(0))],
								['Interest',     eval(finalInterestGain.toFixed(0))]
							]
						}]
					});

}

function setUpHandlers() {

  var laSlider = new Slider("#la");
  var nmSlider = new Slider("#nm");
  var roiSlider = new Slider("#roi");

  laSlider.on("slide", function(data) {
    $("#la_value").html(data);
    calculateEMI();
  });

  nmSlider.on("slide", function(data) {
    $("#nm_value").html(data);
    calculateEMI();
  });

  roiSlider.on("slide", function(data) {
    $("#roi_value").html(data);
    calculateEMI();
  });

  calculateEMI();
}

function defer(method) {
  if (window.jQuery && window.$ && typeof window.Slider === "function") {
    method();
  } else {
    setTimeout(function() {
      defer(method);
    }, 50);
  }
}

defer(setUpHandlers);
<commit_msg>Update fd.js<commit_after>function calculateEMI() {

var P = $("#la_value").html();
var n = $("#nm_value").html();
var r = $("#roi_value").html();
var t = Math.floor(n/12); // Quarterly

var temp =(r/100);
	var A= P*(1+temp*t);
        I=A-P;

$("#tbl_de").html( P.toFixed(0).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
$("#tbl_full").html(A.toFixed(2).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
$("#tbl_int").html(I.toFixed(2).toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));

		var chart = new Highcharts.Chart({

						chart: {
							plotBackgroundColor: null,
							plotBorderWidth: null,
							plotShadow: false,
						    renderTo: 'container'

						},
						tooltip: {
							//pointFormat: '{series.name}: {point.value}%'
						},
	title:{
    text:''
},
	credits: {
    enabled: false
  },
						plotOptions: {
							pie: {
								allowPointSelect: true,
								showInLegend:true,
								cursor: 'pointer',
								dataLabels: {
								    enabled: false,
									color: '#000000',
									connectorColor: '#000000',
									format: '{point.name}: {point.percentage:.1f} %'
								}
							}
						},
						series: [{
							type: 'pie',
							name: 'Amount',
							data: [
								['Principal',   eval(depositedAmount.toFixed(0))],
								['Interest',     eval(finalInterestGain.toFixed(0))]
							]
						}]
					});

}

function setUpHandlers() {

  var laSlider = new Slider("#la");
  var nmSlider = new Slider("#nm");
  var roiSlider = new Slider("#roi");

  laSlider.on("slide", function(data) {
    $("#la_value").html(data);
    calculateEMI();
  });

  nmSlider.on("slide", function(data) {
    $("#nm_value").html(data);
    calculateEMI();
  });

  roiSlider.on("slide", function(data) {
    $("#roi_value").html(data);
    calculateEMI();
  });

  calculateEMI();
}

function defer(method) {
  if (window.jQuery && window.$ && typeof window.Slider === "function") {
    method();
  } else {
    setTimeout(function() {
      defer(method);
    }, 50);
  }
}

defer(setUpHandlers);
<|endoftext|>


<commit_before>var duality = require('duality/core')

exports.load = function(path) {
    var result,
        baseURL = duality.getBaseURL()

    var request = new XMLHttpRequest();
    request.open('GET', baseURL + '/schema/' + path + ".json", false);  // `false` makes the request synchronous
    request.send(null);

    if (request.status === 404) {
        throw "schema: " + baseURL + '/schema/' + path + ".json does not exist. 404."

    }
    else if (request.status === 200) {
      result = request.responseText;
    }

    return JSON.parse(result)
}<commit_msg>Deal with new schema folder structure<commit_after>var duality = require('duality/core')

exports.load = function(path) {
    var result,
        baseURL = duality.getBaseURL()

    var request = new XMLHttpRequest();
    request.open('GET', baseURL + '/' + path + ".json", false);  // `false` makes the request synchronous
    request.send(null);

    if (request.status === 404) {
        throw "schema: " + baseURL + '/' + path + ".json does not exist. 404."

    }
    else if (request.status === 200) {
      result = request.responseText;
    }

    return JSON.parse(result)
}<|endoftext|>


<commit_before>/*jslint browser: true, nomen: true, white: true, vars: true*/
/*global $, R, Isomer, steps*/

'use strict';

var Shape = Isomer.Shape;
var Point = Isomer.Point;
var Color = Isomer.Color;

// Global isomer instance
var isomer;

var config = {
    // http://www.colourlovers.com/palette/1473/Ocean_Five
    colors: [
        new Color(0, 160, 176),
        new Color(106, 74, 60),
        new Color(204, 51, 63),
        new Color(235, 104, 65),
        new Color(237, 201, 81)
    ],
    isomer: {
        normal: {
            scale: 40,
            originX: 40,
            originY: 400
        },
        target: {
            scale: 22,
            originX: 1200,
            originY: 250
        }
    },
};

var renderBlock = function(y, x, value, z) {
    isomer.add(
        new Shape.Prism(
            new Point(x, -6 * y, z),
            1, 1, 1
        ),
        config.colors[value]
    );
};

var renderBlocks = function(len, y, values, x) {
    R.forEachIndexed(R.partial(renderBlock, y, len - x), values);
};

var renderLine = function(line, y) {
    var len = line.length;
    R.forEachIndexed(R.partial(renderBlocks, len, y), line.reverse());
};

var render = R.forEachIndexed(renderLine);

var addColorBlocks = function(str) {
    R.forEach(function(cstr) {
        str = str.replace(new RegExp('\\{' + cstr + '\\}', 'g'), '

');
    }, ['X', 'BL', 'BR', 'RE', 'OR', 'YE']);
    return str;
};

var functions = {
    'stackEqual': stackEqual,
    'flatten': flattenDeep,
    'map({X} ↦ {X}{X})': map2D(clone),
    'map({OR} ↦ {YE})': map2D(replace(OR, YE)),
    'map({YE} ↦ {BR})': map2D(replace(YE, BR)),
    'map({YE} ↦ {BR}{YE})': map2D(replace(YE, [BR, YE])),
    'map({BR} ↦ {BR}{BR}{BR})': map2D(replace(BR, [BR, BR, BR])),
    'map({BR} ↦ {OR}{OR})': map2D(replace(BR, [OR, OR])),
    'reject({OR})': reject2D(R.eq(OR)),
    'reject({YE})': reject2D(R.eq(YE)),
    'filter({BR})': filter2D(R.eq(BR)),
    'map(push({YE}))': R.map(R.append(YE)),
};

// see http://stackoverflow.com/a/11935263/704831
function getRandomSubarray(arr, size) {
    var shuffled = arr.slice(0), i = arr.length, temp, index;
    while (i--) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(0, size);
}

var setIsomerConfig = function(config) {
    isomer.scale = config.scale;
    isomer.originX = config.originX;
    isomer.originY = config.originY;
};

var renderTarget = function(target) {
    setIsomerConfig(config.isomer.target);
    render([target]);
    setIsomerConfig(config.isomer.normal);
};

var newPuzzle = function() {
    // new initial state
    // init = wrap(getRandomSubarray([OR, BR, BR, BR, BR, BR, BR, BR, YE, YE, YE, YE], 6));
    init = wrap([BR, OR, OR, YE, YE, YE, OR, OR, BR]);

    // new puzzle
    var randFs = getRandomSubarray(R.values(functions), 5);
    target = R.last(transformationSteps(init, randFs));

    var width = target.length;
    var height = R.length(R.maxBy(R.length, target));
    var total = R.length(R.flatten(target));
    if (width == 0 || width > 8 || height > 6 || total < 6) {
        newPuzzle();
    }
};

var renderAll = function() {
    var ids = [];
    $('#program').find('li').each(function() {
        ids.push($(this).attr('id'));
    });

    var fs = R.map(R.prop(R.__, functions), ids);
    isomer.canvas.clear();
    var ts = transformationSteps(init, fs);

    if (R.eqDeep(R.last(ts), target)) {
        $('#targetshape h2').html('Solved!');
    } else {
        $('#targetshape h2').html('Target shape');
    }
    renderTarget(target);

    render(ts);
}

var liClickHandler = function() {
    var $li = $(this);
    var targetId = 'program';
    if ($li.parent().attr('id') == 'program') {
        targetId = 'available';
    }
    $li.remove();
    $li.on('click', liClickHandler);
    $('#' + targetId).append($li);

    renderAll();
}

var resetControls = function() {
    $('.sortable').empty();
    R.forEach(function(fid) {
        var $li = $('
' + addColorBlocks(fid) + '
');
        $li.on('click', liClickHandler);
        $('#available').append($li);
    }, R.keys(functions));
};

var init;
var target;

window.onload = function() {
    var canvas = document.getElementById('canvas');
    isomer = new Isomer(canvas);
    setIsomerConfig(config.isomer.normal);

    newPuzzle();
    resetControls();

    $('.sortable').each(function() {
        new Sortable(this, {
            group: 'function-lists',
            ghostClass: 'sortable-ghost',
            animation: 150,
            onSort: renderAll
        });
    });

    renderAll();

    $(window).on('keypress', function(ev) {
        if (ev.keyCode === 114) { // r: reset program
            resetControls();
            renderAll();
        } else if (ev.keyCode === 103) { // g: generate new puzzle
            newPuzzle();
            renderAll();
        }
    });
};
<commit_msg>gjslint<commit_after>/*jslint browser: true, nomen: true, white: true, vars: true*/
/*global $, R, Isomer, steps*/

'use strict';

var Shape = Isomer.Shape;
var Point = Isomer.Point;
var Color = Isomer.Color;

// Global isomer instance
var isomer;

var config = {
    // http://www.colourlovers.com/palette/1473/Ocean_Five
    colors: [
        new Color(0, 160, 176),
        new Color(106, 74, 60),
        new Color(204, 51, 63),
        new Color(235, 104, 65),
        new Color(237, 201, 81)
    ],
    isomer: {
        normal: {
            scale: 40,
            originX: 40,
            originY: 400
        },
        target: {
            scale: 22,
            originX: 1200,
            originY: 250
        }
    }
};

var renderBlock = function(y, x, value, z) {
    isomer.add(
        new Shape.Prism(
            new Point(x, -6 * y, z),
            1, 1, 1
        ),
        config.colors[value]
    );
};

var renderBlocks = function(len, y, values, x) {
    R.forEachIndexed(R.partial(renderBlock, y, len - x), values);
};

var renderLine = function(line, y) {
    var len = line.length;
    R.forEachIndexed(R.partial(renderBlocks, len, y), line.reverse());
};

var render = R.forEachIndexed(renderLine);

var addColorBlocks = function(str) {
    R.forEach(function(cstr) {
        str = str.replace(new RegExp('\\{' + cstr + '\\}', 'g'),
                          '

');
    }, ['X', 'BL', 'BR', 'RE', 'OR', 'YE']);
    return str;
};

var functions = {
    'stackEqual': stackEqual,
    'flatten': flattenDeep,
    'map({X} ↦ {X}{X})': map2D(clone),
    'map({OR} ↦ {YE})': map2D(replace(OR, YE)),
    'map({YE} ↦ {BR})': map2D(replace(YE, BR)),
    'map({YE} ↦ {BR}{YE})': map2D(replace(YE, [BR, YE])),
    'map({BR} ↦ {BR}{BR}{BR})': map2D(replace(BR, [BR, BR, BR])),
    'map({BR} ↦ {OR}{OR})': map2D(replace(BR, [OR, OR])),
    'reject({OR})': reject2D(R.eq(OR)),
    'reject({YE})': reject2D(R.eq(YE)),
    'filter({BR})': filter2D(R.eq(BR)),
    'map(push({YE}))': R.map(R.append(YE))
};

// see http://stackoverflow.com/a/11935263/704831
function getRandomSubarray(arr, size) {
    var shuffled = arr.slice(0), i = arr.length, temp, index;
    while (i--) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(0, size);
}

var setIsomerConfig = function(config) {
    isomer.scale = config.scale;
    isomer.originX = config.originX;
    isomer.originY = config.originY;
};

var renderTarget = function(target) {
    setIsomerConfig(config.isomer.target);
    render([target]);
    setIsomerConfig(config.isomer.normal);
};

var newPuzzle = function() {
    // new initial state
    init = wrap([BR, OR, OR, YE, YE, YE, OR, OR, BR]);

    // new puzzle
    var randFs = getRandomSubarray(R.values(functions), 5);
    target = R.last(transformationSteps(init, randFs));

    // make sure the target is not too big
    var width = target.length;
    var height = R.length(R.maxBy(R.length, target));
    var total = R.length(R.flatten(target));
    if (width == 0 || width > 8 || height > 6 || total < 6) {
        newPuzzle();
    }
};

var renderAll = function() {
    var ids = [];
    $('#program').find('li').each(function() {
        ids.push($(this).attr('id'));
    });

    var fs = R.map(R.prop(R.__, functions), ids);
    isomer.canvas.clear();
    var ts = transformationSteps(init, fs);

    if (R.eqDeep(R.last(ts), target)) {
        $('#targetshape h2').html('Solved!');
    } else {
        $('#targetshape h2').html('Target shape');
    }
    renderTarget(target);

    render(ts);
};

var liClickHandler = function() {
    var $li = $(this);
    var targetId = 'program';
    if ($li.parent().attr('id') == 'program') {
        targetId = 'available';
    }
    $li.remove();
    $li.on('click', liClickHandler);
    $('#' + targetId).append($li);

    renderAll();
};

var resetControls = function() {
    $('.sortable').empty();
    R.forEach(function(fid) {
        var $li = $('
' + addColorBlocks(fid) + '
');
        $li.on('click', liClickHandler);
        $('#available').append($li);
    }, R.keys(functions));
};

var init;
var target;

window.onload = function() {
    var canvas = document.getElementById('canvas');
    isomer = new Isomer(canvas);
    setIsomerConfig(config.isomer.normal);

    newPuzzle();
    resetControls();

    $('.sortable').each(function() {
        new Sortable(this, {
            group: 'function-lists',
            ghostClass: 'sortable-ghost',
            animation: 150,
            onSort: renderAll
        });
    });

    renderAll();

    $(window).on('keypress', function(ev) {
        if (ev.keyCode === 114) { // r: reset program
            resetControls();
            renderAll();
        } else if (ev.keyCode === 103) { // g: generate new puzzle
            newPuzzle();
            renderAll();
        }
    });
};
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var msgpack = require('msgpack-lite');
var net = require('net');
var crypto = require('crypto');
var FluentLoggerError = require('./logger-error');

function FluentSender(tag_prefix, options){
  options = options || {};
  this.tag_prefix = tag_prefix;
  this.host = options.host || 'localhost';
  this.port = options.port || 24224;
  this.path = options.path;
  this.timeout = options.timeout || 3.0;
  this.reconnectInterval = options.reconnectInterval || 600000; // Default is 10 minutes
  this.requireAckResponse = options.requireAckResponse;
  this.ackResponseTimeout = options.ackResponseTimeout || 190000; // Default is 190 seconds
  this._timeResolution = options.milliseconds ? 1 : 1000;
  this._socket = null;
  this._data = null;
  this._sendQueue  = [];    // queue for items waiting for being sent.
  this._sendQueueTail = -1;
  this._eventEmitter = new EventEmitter();
}

FluentSender.prototype.emit = function(/*[label] <data>, [timestamp], [callback] */){
  var label, data, timestamp, callback;
  var args = Array.prototype.slice.call(arguments);
  // Label must be string always
  if (typeof args[0] === "string") label = args.shift();

  // Data can be almost anything
  data = args.shift();

  // Date can be either timestamp number or Date object
  if (typeof args[0] !== "function") timestamp = args.shift();

  // Last argument is an optional callback
  if (typeof args[0] === "function") callback = args.shift();

  var self = this;
  var item = self._makePacketItem(label, data, timestamp);

  if (item.tag === null) {
    var error = new FluentLoggerError.MissingTag('tag is missing',
                                                 { tag_prefix: self.tag_prefix, label: label });
    self._handleError(error, 'error', callback);
  }

  item.callback = callback;

  self._sendQueue.push(item);
  self._sendQueueTail++;
  self._connect(function(){
    self._flushSendQueue();
  });
};

['addListener', 'on', 'once', 'removeListener', 'removeAllListeners', 'setMaxListeners', 'getMaxListeners'].forEach(function(attr, i){
  FluentSender.prototype[attr] = function(){
    return this._eventEmitter[attr].apply(this._eventEmitter, Array.prototype.slice.call(arguments));
  };
});

FluentSender.prototype.end = function(label, data, callback){
  var self = this;
  if ((label != null && data != null)) {
    self.emit(label, data, function(err) {
      self._close();
      self._handleError(err, 'error', callback);
    });
  } else {
    process.nextTick(function() {
      self._close();
      callback && callback();
    });
  }
};

FluentSender.prototype._close = function() {
  if (this._socket) {
    this._socket.end();
    this._socket = null;
  }
};

FluentSender.prototype._makePacketItem = function(label, data, time){
  var self = this;
  var tag = null;
  if (self.tag_prefix && label) {
    tag = [self.tag_prefix, label].join('.');
  } else if (self.tag_prefix) {
    tag = self.tag_prefix;
  } else if (label) {
    tag = label;
  }

  if (typeof time != "number") {
    time = Math.floor((time ? time.getTime() : Date.now()) / this._timeResolution);
  }

  var packet = [tag, time, data];
  var options = {};
  if (self.requireAckResponse) {
    options = {
      chunk: crypto.randomBytes(16).toString('base64')
    };
    packet.push(options);
  }
  return {
    packet: msgpack.encode(packet),
    tag: tag,
    time: time,
    data: data,
    options: options
  };
};

FluentSender.prototype._connect = function(callback){
  var self = this;
  if (self._socket === null) {
    self._socket = new net.Socket();
    self._socket.setTimeout(self.timeout);
    self._socket.on('error', function(err) {
      if (self._socket) {
        self._socket.destroy();
        self._socket = null;
        self._handleError(err, 'error', null);
      }
    });
    self._socket.on('data', function(data) {
      self._data = data;
    });
    if (self.path) {
      self._socket.connect(self.path, callback);
    } else {
      self._socket.connect(self.port, self.host, callback);
    }
  } else {
    if (!self._socket.writable) {
      self._socket.destroy();
      self._socket = null;
      process.nextTick(function() {
        self._connect(callback);
      });
    } else {
      process.nextTick(function() {
        callback();
      });
    }
  }
};

FluentSender.prototype._flushSendQueue = function() {
  var self = this;
  var pos = self._sendQueue.length - self._sendQueueTail - 1;
  var item = self._sendQueue[pos];
  if (item === undefined) {
    // nothing written;
  } else {
    self._sendQueueTail--;
    self._sendQueue.shift();
    self._socket.write(new Buffer(item.packet), function(){
      if (self.requireAckResponse) {
        var intervalId = setInterval(function() {
          if (self._data) {
            var response = msgpack.decode(self._data);
            self._data = null;
            clearInterval(intervalId);
            if (response.ack !== item.options.chunk) {
              var error = new FluentLoggerError.ResponseError('ack in response and chunk id in sent data are different',
                                                              { ack: response.ack, chunk: item.options.chunk });
              self._handleError(error, 'error', item.callback);
            }
          }
        }, 100);
        setTimeout(function() {
          var error = new FluentLoggerError.ResponseTimeout('ack response timeout');
          self._handleError(error, 'error', item.callback);
          clearInterval(intervalId);
        }, self.ackResponseTimeout);
      }
      item.callback && item.callback();
    });
    process.nextTick(function() {
      // socket is still available
      if (self._socket && self._socket.writable) {
        self._flushSendQueue();
      }
    });
    // TODO: how should we recorver if dequeued items are not sent.
  }
};

FluentSender.prototype._handleError = function(error, signal, callback) {
  var self = this;
  callback && callback(error);
  if (self._eventEmitter.listenerCount(signal) > 0) {
    self._eventEmitter.emit(signal, error);
  }
};

FluentSender.prototype._setupErrorHandler = function() {
  var self = this;
  if (!self.reconnectInterval) {
    return;
  }
  self.on('error', function(error) {
    console.error('Fluentd error', error);
    console.info('Fluentd will reconnect after ' + self.reconnectInterval / 1000 + ' seconds');
    setTimeout(function() {
      console.info("Fluentd is reconnecting...");
      self._connect(function() {
        console.info('Fluentd reconnection finished!!');
      });
    }, self.reconnectInterval);
  });
};

module.exports = exports = {};
exports.FluentSender = FluentSender;
<commit_msg>Invoke callback properly<commit_after>'use strict';
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var msgpack = require('msgpack-lite');
var net = require('net');
var crypto = require('crypto');
var FluentLoggerError = require('./logger-error');

function FluentSender(tag_prefix, options){
  options = options || {};
  this.tag_prefix = tag_prefix;
  this.host = options.host || 'localhost';
  this.port = options.port || 24224;
  this.path = options.path;
  this.timeout = options.timeout || 3.0;
  this.reconnectInterval = options.reconnectInterval || 600000; // Default is 10 minutes
  this.requireAckResponse = options.requireAckResponse;
  this.ackResponseTimeout = options.ackResponseTimeout || 190000; // Default is 190 seconds
  this._timeResolution = options.milliseconds ? 1 : 1000;
  this._socket = null;
  this._data = null;
  this._sendQueue  = [];    // queue for items waiting for being sent.
  this._sendQueueTail = -1;
  this._eventEmitter = new EventEmitter();
}

FluentSender.prototype.emit = function(/*[label] <data>, [timestamp], [callback] */){
  var label, data, timestamp, callback;
  var args = Array.prototype.slice.call(arguments);
  // Label must be string always
  if (typeof args[0] === "string") label = args.shift();

  // Data can be almost anything
  data = args.shift();

  // Date can be either timestamp number or Date object
  if (typeof args[0] !== "function") timestamp = args.shift();

  // Last argument is an optional callback
  if (typeof args[0] === "function") callback = args.shift();

  var self = this;
  var item = self._makePacketItem(label, data, timestamp);

  if (item.tag === null) {
    var error = new FluentLoggerError.MissingTag('tag is missing',
                                                 { tag_prefix: self.tag_prefix, label: label });
    self._handleError(error, 'error', callback);
  }

  item.callback = callback;

  self._sendQueue.push(item);
  self._sendQueueTail++;
  self._connect(function(){
    self._flushSendQueue();
  });
};

['addListener', 'on', 'once', 'removeListener', 'removeAllListeners', 'setMaxListeners', 'getMaxListeners'].forEach(function(attr, i){
  FluentSender.prototype[attr] = function(){
    return this._eventEmitter[attr].apply(this._eventEmitter, Array.prototype.slice.call(arguments));
  };
});

FluentSender.prototype.end = function(label, data, callback){
  var self = this;
  if ((label != null && data != null)) {
    self.emit(label, data, function(err) {
      self._close();
      if (err) {
        self._handleError(err, 'error', callback);
      } else {
        callback && callback();
      }
    });
  } else {
    process.nextTick(function() {
      self._close();
      callback && callback();
    });
  }
};

FluentSender.prototype._close = function() {
  if (this._socket) {
    this._socket.end();
    this._socket = null;
  }
};

FluentSender.prototype._makePacketItem = function(label, data, time){
  var self = this;
  var tag = null;
  if (self.tag_prefix && label) {
    tag = [self.tag_prefix, label].join('.');
  } else if (self.tag_prefix) {
    tag = self.tag_prefix;
  } else if (label) {
    tag = label;
  }

  if (typeof time != "number") {
    time = Math.floor((time ? time.getTime() : Date.now()) / this._timeResolution);
  }

  var packet = [tag, time, data];
  var options = {};
  if (self.requireAckResponse) {
    options = {
      chunk: crypto.randomBytes(16).toString('base64')
    };
    packet.push(options);
  }
  return {
    packet: msgpack.encode(packet),
    tag: tag,
    time: time,
    data: data,
    options: options
  };
};

FluentSender.prototype._connect = function(callback){
  var self = this;
  if (self._socket === null) {
    self._socket = new net.Socket();
    self._socket.setTimeout(self.timeout);
    self._socket.on('error', function(err) {
      if (self._socket) {
        self._socket.destroy();
        self._socket = null;
        self._handleError(err, 'error', null);
      }
    });
    self._socket.on('data', function(data) {
      self._data = data;
    });
    if (self.path) {
      self._socket.connect(self.path, callback);
    } else {
      self._socket.connect(self.port, self.host, callback);
    }
  } else {
    if (!self._socket.writable) {
      self._socket.destroy();
      self._socket = null;
      process.nextTick(function() {
        self._connect(callback);
      });
    } else {
      process.nextTick(function() {
        callback();
      });
    }
  }
};

FluentSender.prototype._flushSendQueue = function() {
  var self = this;
  var pos = self._sendQueue.length - self._sendQueueTail - 1;
  var item = self._sendQueue[pos];
  if (item === undefined) {
    // nothing written;
  } else {
    self._sendQueueTail--;
    self._sendQueue.shift();
    self._socket.write(new Buffer(item.packet), function(){
      if (self.requireAckResponse) {
        var intervalId = setInterval(function() {
          if (self._data) {
            var response = msgpack.decode(self._data);
            self._data = null;
            clearInterval(intervalId);
            if (response.ack !== item.options.chunk) {
              var error = new FluentLoggerError.ResponseError('ack in response and chunk id in sent data are different',
                                                              { ack: response.ack, chunk: item.options.chunk });
              self._handleError(error, 'error', item.callback);
            }
          }
        }, 100);
        setTimeout(function() {
          var error = new FluentLoggerError.ResponseTimeout('ack response timeout');
          self._handleError(error, 'error', item.callback);
          clearInterval(intervalId);
        }, self.ackResponseTimeout);
      }
      item.callback && item.callback();
    });
    process.nextTick(function() {
      // socket is still available
      if (self._socket && self._socket.writable) {
        self._flushSendQueue();
      }
    });
    // TODO: how should we recorver if dequeued items are not sent.
  }
};

FluentSender.prototype._handleError = function(error, signal, callback) {
  var self = this;
  callback && callback(error);
  if (self._eventEmitter.listenerCount(signal) > 0) {
    self._eventEmitter.emit(signal, error);
  }
};

FluentSender.prototype._setupErrorHandler = function() {
  var self = this;
  if (!self.reconnectInterval) {
    return;
  }
  self.on('error', function(error) {
    console.error('Fluentd error', error);
    console.info('Fluentd will reconnect after ' + self.reconnectInterval / 1000 + ' seconds');
    setTimeout(function() {
      console.info("Fluentd is reconnecting...");
      self._connect(function() {
        console.info('Fluentd reconnection finished!!');
      });
    }, self.reconnectInterval);
  });
};

module.exports = exports = {};
exports.FluentSender = FluentSender;
<|endoftext|>


<commit_before>;(function(global) {       // IIFE for legacy non-module usage
'use strict'

var tagNameRegex = /^([a-z1-6]+)(?:\:([a-z]+))?/    // matches 'input' or 'input:text'
var propsRegex = /((?:#|\.|@)[\w-]+)|(\[.*?\])/g    // matches all further properties
var attrRegex = /\[([\w-]+)(?:=([^\]]+))?\]/        // matches '[foo=bar]' or '[foo]'
var autoKeyGenRegex = /\^$/                         // matches 'anything^'
var protoSlice = Array.prototype.slice

// Error subclass to throw for parsing errors
function ParseError(input) {
    this.message = input
    this.stack = new Error().stack
}
ParseError.prototype = Object.create(Error.prototype)
ParseError.prototype.name = 'JSnoXParseError'

// A simple module-level cache for parseTagSpec().
// Subsequent re-parsing of the same input string will be pulled
// from this cache for an increase in performance.
var specCache = {}

// Convert a tag specification string into an object
// eg. 'input:checkbox#foo.bar[name=asdf]' produces the output:
// {
//   tagName: 'input',
//   props: {
//     type: 'checkbox',
//     id: 'foo',
//     className: 'bar',
//     name: 'asdf'
//   }
// }
function parseTagSpec(specString) {
    if (!specString || !specString.match) throw new ParseError(specString)
    if (specCache[specString]) return specCache[specString]

    // Parse tagName, and optional type attribute
    var tagMatch = specString.match(tagNameRegex)
    if (!tagMatch) {
        if (specString.match(propsRegex)) tagMatch = ['div', 'div'] // create <div> if tagname omitted
        else throw new ParseError(specString)
    }
    var tagName = tagMatch[1]
    var props = {}
    var classes = []

    if (specString.match(autoKeyGenRegex)) props.key = specString
    if (tagMatch[2]) props.type = tagMatch[2]
    else if (tagName === 'button') props.type = 'button' // Saner default for <button>

    var matches = specString.match(propsRegex)
    matches && matches.forEach(function getRegexMatches(str) {
        if (!str) return
        else if (str[0] === '#') props.id = str.slice(1)
        else if (str[0] === '@') props.ref = str.slice(1)
        else if (str[0] === '.') classes.push(str.slice(1))
        else if (str[0] === '[') {
            var match = str.match(attrRegex)
            if (match) props[match[1]] = match[2] || true    // If no attr value given, use true
        }
    })
    if (classes.length) props.className = classes.join(' ')

    var spec = {
        tagName: tagName,
        props: props
    }

    specCache[specString] = spec
    return spec
}

// Merge two objects, producing a new object with their properties
//
// Note:
// * the className property is treated as a special case and is merged
// * arguments are assumed to be object literals, which is why there are
//   no hasOwnProperty() checks (see af/JSnoX/issues/3)
function extend(obj1, obj2) {
    var output = {}
    obj1 = obj1 || {}
    obj2 = obj2 || {}

    for (var k in obj1) output[k] = obj1[k]
    for (var l in obj2) output[l] = obj2[l]

    // className is a special case: we want to return the combination
    // of strings if both objects contain className
    var combinedClass = (typeof obj1.className === 'string') &&
                        (typeof obj2.className === 'string') &&
                        [obj1.className, obj2.className].join(' ')
    output.className = combinedClass || obj1.className || obj2.className

    return output
}

// Main exported function.
// Returns a "client", which is a function that can be used to compose
// ReactElement trees directly.
function jsnox(React) {
    var client = function jsnoxClient(componentType, props, children) {
        // Special $renderIf prop allows you to conditionally render an element:
        if (props && typeof props.$renderIf !== 'undefined') {
            if (props.$renderIf) delete props.$renderIf     // Don't pass down to components
            else return null
        }

        // Handle case where an array of children is given as the second argument:
        if (Array.isArray(props) || typeof props !== 'object') {
            children = props
            props = null
        }

        // Handle case where props object (second arg) is omitted
        var arg2IsReactElement = (props && typeof props === 'object' &&
                                  typeof props.ref !== 'undefined' &&
                                  typeof props.props === 'object')

        var finalProps = props
        if (typeof componentType === 'string' || !componentType) {
            // Parse the provided string into a hash of props
            // If componentType is invalid (undefined, empty string, etc),
            // parseTagSpec should throw.
            var spec = parseTagSpec(componentType)
            componentType = spec.tagName
            finalProps = arg2IsReactElement ? spec.props : extend(spec.props, props)
        }

        // If more than three args are given, assume args 3..n are ReactElement
        // children. You can also pass an array of children as the 3rd argument,
        // but in that case each child should have a unique key to avoid warnings.
        var args = protoSlice.call(arguments)
        if (args.length > 3 || arg2IsReactElement) {
            args[0] = componentType
            if (arg2IsReactElement) {
                args.splice(1, 0, finalProps || null)
            } else {
                args[1] = finalProps
            }
            return React.createElement.apply(React, args)
        } else {
            return React.createElement(componentType, finalProps, children)
        }
    }
    client.ParseError = ParseError
    return client
}

// Export for CommonJS, or else add a global jsnox variable:
/* global define */
if (typeof(module) !== 'undefined') module.exports = jsnox
else if (typeof define === 'function' && define.amd) define([], function(){return jsnox;})
else global.jsnox = jsnox

}(this))
<commit_msg>Style tweaks<commit_after>;(function(global) {       // IIFE for legacy non-module usage
'use strict'

var tagNameRegex = /^([a-z1-6]+)(?:\:([a-z]+))?/    // matches 'input' or 'input:text'
var propsRegex = /((?:#|\.|@)[\w-]+)|(\[.*?\])/g    // matches all further properties
var attrRegex = /\[([\w-]+)(?:=([^\]]+))?\]/        // matches '[foo=bar]' or '[foo]'
var autoKeyGenRegex = /\^$/                         // matches 'anything^'
var protoSlice = Array.prototype.slice

// Error subclass to throw for parsing errors
function ParseError(input) {
    this.message = input
    this.stack = new Error().stack
}
ParseError.prototype = Object.create(Error.prototype)
ParseError.prototype.name = 'JSnoXParseError'

// A simple module-level cache for parseTagSpec().
// Subsequent re-parsing of the same input string will be pulled
// from this cache for an increase in performance.
var specCache = {}

// Convert a tag specification string into an object
// eg. 'input:checkbox#foo.bar[name=asdf]' produces the output:
// {
//   tagName: 'input',
//   props: {
//     type: 'checkbox',
//     id: 'foo',
//     className: 'bar',
//     name: 'asdf'
//   }
// }
function parseTagSpec(specString) {
    if (!specString || !specString.match) throw new ParseError(specString)
    if (specCache[specString]) return specCache[specString]

    // Parse tagName, and optional type attribute
    var tagMatch = specString.match(tagNameRegex)
    if (!tagMatch) {
        if (specString.match(propsRegex)) tagMatch = ['div', 'div'] // create <div> if tagname omitted
        else throw new ParseError(specString)
    }
    var tagName = tagMatch[1]
    var props = {}
    var classes = []

    if (specString.match(autoKeyGenRegex)) props.key = specString
    if (tagMatch[2]) props.type = tagMatch[2]
    else if (tagName === 'button') props.type = 'button' // Saner default for <button>

    var matches = specString.match(propsRegex)
    matches && matches.forEach(function getRegexMatches(str) {
        if (!str) return
        else if (str[0] === '#') props.id = str.slice(1)
        else if (str[0] === '@') props.ref = str.slice(1)
        else if (str[0] === '.') classes.push(str.slice(1))
        else if (str[0] === '[') {
            var match = str.match(attrRegex)
            if (match) props[match[1]] = match[2] || true    // If no attr value given, use true
        }
    })
    if (classes.length) props.className = classes.join(' ')

    var spec = {
        tagName: tagName,
        props: props
    }

    specCache[specString] = spec
    return spec
}

// Merge two objects, producing a new object with their properties
//
// Note:
// * the className property is treated as a special case and is merged
// * arguments are assumed to be object literals, which is why there are
//   no hasOwnProperty() checks (see af/JSnoX/issues/3)
function extend(obj1, obj2) {
    var output = {}
    obj1 = obj1 || {}
    obj2 = obj2 || {}

    for (var k in obj1) output[k] = obj1[k]
    for (var l in obj2) output[l] = obj2[l]

    // className is a special case: we want to return the combination
    // of strings if both objects contain className
    var combinedClass = (typeof obj1.className === 'string') &&
                        (typeof obj2.className === 'string') &&
                        [obj1.className, obj2.className].join(' ')
    output.className = combinedClass || obj1.className || obj2.className

    return output
}

// Main exported function.
// Returns a "client", which is a function that can be used to compose
// ReactElement trees directly.
function jsnox(React) {
    var client = function jsnoxClient(componentType, props, children) {
        // Special $renderIf prop allows you to conditionally render an element:
        if (props && typeof props.$renderIf !== 'undefined') {
            if (props.$renderIf) delete props.$renderIf     // Don't pass down to components
            else return null
        }

        // Handle case where an array of children is given as the second argument:
        if (Array.isArray(props) || typeof props !== 'object') {
            children = props
            props = null
        }

        // Handle case where props object (second arg) is omitted
        var arg2IsReactElement = (props && typeof props === 'object' &&
                                  typeof props.ref !== 'undefined' &&
                                  typeof props.props === 'object')

        var finalProps = props
        if (typeof componentType === 'string' || !componentType) {
            // Parse the provided string into a hash of props
            // If componentType is invalid (undefined, empty string, etc),
            // parseTagSpec should throw.
            var spec = parseTagSpec(componentType)
            componentType = spec.tagName
            finalProps = arg2IsReactElement ? spec.props : extend(spec.props, props)
        }

        // If more than three args are given, assume args 3..n are ReactElement
        // children. You can also pass an array of children as the 3rd argument,
        // but in that case each child should have a unique key to avoid warnings.
        var args = protoSlice.call(arguments)
        if (args.length > 3 || arg2IsReactElement) {
            args[0] = componentType
            if (arg2IsReactElement) {
                args.splice(1, 0, finalProps || null)
            } else {
                args[1] = finalProps
            }
            return React.createElement.apply(React, args)
        } else {
            return React.createElement(componentType, finalProps, children)
        }
    }
    client.ParseError = ParseError
    return client
}

// Export for CommonJS, or else add a global jsnox variable:
if (typeof(module) !== 'undefined') module.exports = jsnox
else if (typeof global.define === 'function' && global.define.amd) {
    global.define([], function() { return jsnox })      // AMD Support
} else global.jsnox = jsnox

}(this))
<|endoftext|>


<commit_before>/*jshint -W083 */
// Blank array for all the filtered markers
var markers_filter = [];

function resizeMap() {
    try {
        document.getElementById("map");
        google.maps.event.trigger(map, "resize");
    } catch (err) {
        console.log("unable to trigger resize");
    }
}

// This function is used for class bindings
function ViewModel() {
    var self = this;

    // If the filter window is to be shown
    self.shouldShowMessage = ko.observable(true);

    //  click binding for showing filter location pane
    self.showWindow = function() {
        self.shouldShowMessage(!self.shouldShowMessage());
        resizeMap();
    };

    // returns class for left pane
    self.optionStatus = ko.pureComputed(function() {
        var width = $(window).width();
        if (width > 529) {
            return self.shouldShowMessage() ? "options-box" : "options-box-hide";
        } else {

            return self.shouldShowMessage() ? "options-box" : "options-box-hide-with-filter";
        }
    }, ViewModel);

    //returns class for right pane
    self.mapStatus = ko.pureComputed(function() {

        var width = $(window).width();

        if (width > 529) {
            return self.shouldShowMessage() ? "map_wrapper" : "map-only";
        } else {
            return !self.shouldShowMessage() ? "map_wrapper-with-filter" : "map_wrapper";
        }
    }, ViewModel);
}

//This function is used for binding user data such as filtered location.
function MapsModel() {
    var self = this;

    // This variable is used for binding input text for filter search
    self.filterLocation = ko.observable();

    // True if left pane visible
    self.isListVisible = ko.observable(false);

    self.defaultItems = ko.observableArray([{
            "title": "Rashtrapati Bhavan",
            "location": {
                "lat": 28.6144,
                "lng": 77.1996
            }
        },
        {
            "title": "National Zoological Park",
            "location": {
                "lat": 28.6030,
                "lng": 77.2465
            }
        }, {
            "title": "Khan Market",
            "location": {
                "lat": 28.6001,
                "lng": 77.2270
            }
        }, {
            "title": "Jawaharlal Nehru Stadium",
            "location": {
                "lat": 28.5828,
                "lng": 77.2344
            }
        }, {
            "title": "India Gate",
            "location": {
                "lat": 28.6129,
                "lng": 77.2295
            }
        }
    ]);

    self.setMarkerForDefaultList = function() {
        var largeInfowindow = new google.maps.InfoWindow();

        // hideListings(markers_filter)
        self.hideListings();

        var defaultIcon = makeMarkerIcon('0091ff');
        var marker = new google.maps.Marker({
            position: this.location,
            title: this.title,
            animation: google.maps.Animation.DROP,
            id: 1,
            map: map,
            icon: defaultIcon,
            optimized: false // stops the marker from flashing
        });

        // Create a "highlighted location" marker color for when the user
        // mouses over the marker.
        var highlightedIcon = makeMarkerIcon('FFFF24');

        // Two event listeners - one for mouseover, one for mouseout,
        // to change the colors back and forth.
        marker.addListener('mouseover', function() {
            this.setIcon(highlightedIcon);
        });
        marker.addListener('mouseout', function() {
            this.setIcon(defaultIcon);
        });
        marker.addListener('click', function() {
            populateInfoWindow(marker, largeInfowindow);
        });

        map.setCenter(this.location);
        map.setZoom(15);

        markers_filter.push(marker);

        populateInfoWindow(marker, largeInfowindow);

    };
    // List of all the location for `self.fliterLocation`
    self.items = ko.observableArray();

    // Sanity check
    self.throttledFilterLocation = ko.computed(self.filterLocation)
        .extend({ rateLimit: { timeout: 500, method: "notifyWhenChangesStop" } });

    self.filterDefaultLocation = ko.observable();

    // Used to filter default locations from the `self.defaultItems`. This is case sensitive.
    this.filterDefaultLocationList = ko.computed(function() {

        return ko.utils.arrayFilter(self.defaultItems(), function(item) {
            if (self.filterDefaultLocation() == undefined)
                return true;
            else if (item.title.indexOf(self.filterDefaultLocation()) === -1)
                return false;
            else
                return true;
        });
    });

    this.filterDefaultLocationList.subscribe(function (list) {
        // var marker_filter = [];

                self.hideListings();
        var defaultIcon = makeMarkerIcon('0091ff');
        var highlightedIcon = makeMarkerIcon('FFFF24');
        for (var index = 0; index < list.length; index++) {
                                var marker = new google.maps.Marker({
                        position: list[index].location,
                        title: list[index].titlle,
                        animation: google.maps.Animation.DROP,
                        id: index,
                        map:map,
                        optimized: false // stops the marker from flashing
                    });
                    var largeInfowindow = new google.maps.InfoWindow();

                    marker.addListener('click', function onClickFunction() {
                        populateInfoWindow(this, largeInfowindow);
                    });
                    // Two event listeners - one for mouseover, one for mouseout,
                    // to change the colors back and forth.
                    marker.addListener('mouseover', function() {
                        this.setIcon(highlightedIcon);
                    });
                    marker.addListener('mouseout', function() {
                        this.setIcon(defaultIcon);
                    });

                    markers_filter.push(marker);

                    // self.items.push(marker);
                }
        // showListings(markers_filter);
    })

    // Fetches locations using google maps api and populates the `markers_filter`.
    // This function waits untill user has finished typing.
    self.throttledFilterLocation.subscribe(function(newValue) {
        self.filterDefaultLocation('');
        if (self.filterLocation().length <= 0) {
            return;
        }

        self.hideListings();

        self.items([]);
        markers_filter = [];

        // Return the geocoding for filtered locations
        zoomToArea(newValue).then(function(response) {
            if (response.status) {

                var list = response.results;

                var defaultIcon = makeMarkerIcon('0091ff');

                // Create a "highlighted location" marker color for when the user
                // mouses over the marker.
                var highlightedIcon = makeMarkerIcon('FFFF24');

                for (var index = 0; index < list.length; index++) {
                    var add;
                    var item = {
                        location: list[index].geometry.location,
                        address: list[index].formatted_address
                    };

                    var marker = new google.maps.Marker({
                        position: list[index].geometry.location,
                        title: list[index].address_components[0].short_name,
                        animation: google.maps.Animation.DROP,
                        id: index,
                        icon: defaultIcon,
                        optimized: false // stops the marker from flashing
                    });
                    var largeInfowindow = new google.maps.InfoWindow();

                    marker.addListener('click', function onClickFunction() {
                        populateInfoWindow(this, largeInfowindow);
                    });
                    // Two event listeners - one for mouseover, one for mouseout,
                    // to change the colors back and forth.
                    marker.addListener('mouseover', function() {
                        this.setIcon(highlightedIcon);
                    });
                    marker.addListener('mouseout', function() {
                        this.setIcon(defaultIcon);
                    });

                    markers_filter.push(marker);

                    self.items.push(marker);
                }

                showListings(markers_filter);
                self.isListVisible(true);
            } else {
                alert('Ooppsss, Something Went wrong!!');
            }
        });
    });

    // List Item that is selected
    self.selectedItem = function() {
        debugger;

        var location = { lat: this.position.lat(), lng: this.position.lng() };

        // populateInfoWindow(this,google.maps.InfoWindow());
        // this.trigger('click');
        map.setCenter(location);
        map.setZoom(15);
        var event = new google.maps.event.trigger(this, 'click');
        self.items([]);
        self.isListVisible(false);
        self.filterLocation('');
    };

    // Binding to show listings
    self.showListings = function() {
        self.filterLocation('');
        showListings(markers);
        if (markers_filter.length)
            showListings(markers_filter);

    };

    //Binding to hide listings
    self.hideListings = function() {

        if (markers.length)
            hideListings(markers);

        // If filtered locations are present then clear
        if (markers_filter.length) {
            hideListings(markers_filter);
            markers_filter = [];
            self.items([]);
            self.isListVisible(false);
            // self.filterLocation('');
        }
    };
}

var RootModel = {
    view: new ViewModel(),
    maps: new MapsModel()
};
ko.applyBindings(RootModel);

$(window).resize(function() {
    resizeMap();
});<commit_msg>Removed breakpoints<commit_after>/*jshint -W083 */
// Blank array for all the filtered markers
var markers_filter = [];

function resizeMap() {
    try {
        document.getElementById("map");
        google.maps.event.trigger(map, "resize");
    } catch (err) {
        console.log("unable to trigger resize");
    }
}

// This function is used for class bindings
function ViewModel() {
    var self = this;

    // If the filter window is to be shown
    self.shouldShowMessage = ko.observable(true);

    //  click binding for showing filter location pane
    self.showWindow = function() {
        self.shouldShowMessage(!self.shouldShowMessage());
        resizeMap();
    };

    // returns class for left pane
    self.optionStatus = ko.pureComputed(function() {
        var width = $(window).width();
        if (width > 529) {
            return self.shouldShowMessage() ? "options-box" : "options-box-hide";
        } else {

            return self.shouldShowMessage() ? "options-box" : "options-box-hide-with-filter";
        }
    }, ViewModel);

    //returns class for right pane
    self.mapStatus = ko.pureComputed(function() {

        var width = $(window).width();

        if (width > 529) {
            return self.shouldShowMessage() ? "map_wrapper" : "map-only";
        } else {
            return !self.shouldShowMessage() ? "map_wrapper-with-filter" : "map_wrapper";
        }
    }, ViewModel);
}

//This function is used for binding user data such as filtered location.
function MapsModel() {
    var self = this;

    // This variable is used for binding input text for filter search
    self.filterLocation = ko.observable();

    // True if left pane visible
    self.isListVisible = ko.observable(false);

    self.defaultItems = ko.observableArray([{
            "title": "Rashtrapati Bhavan",
            "location": {
                "lat": 28.6144,
                "lng": 77.1996
            }
        },
        {
            "title": "National Zoological Park",
            "location": {
                "lat": 28.6030,
                "lng": 77.2465
            }
        }, {
            "title": "Khan Market",
            "location": {
                "lat": 28.6001,
                "lng": 77.2270
            }
        }, {
            "title": "Jawaharlal Nehru Stadium",
            "location": {
                "lat": 28.5828,
                "lng": 77.2344
            }
        }, {
            "title": "India Gate",
            "location": {
                "lat": 28.6129,
                "lng": 77.2295
            }
        }
    ]);

    self.setMarkerForDefaultList = function() {
        var largeInfowindow = new google.maps.InfoWindow();

        // hideListings(markers_filter)
        self.hideListings();

        var defaultIcon = makeMarkerIcon('0091ff');
        var marker = new google.maps.Marker({
            position: this.location,
            title: this.title,
            animation: google.maps.Animation.DROP,
            id: 1,
            map: map,
            icon: defaultIcon,
            optimized: false // stops the marker from flashing
        });

        // Create a "highlighted location" marker color for when the user
        // mouses over the marker.
        var highlightedIcon = makeMarkerIcon('FFFF24');

        // Two event listeners - one for mouseover, one for mouseout,
        // to change the colors back and forth.
        marker.addListener('mouseover', function() {
            this.setIcon(highlightedIcon);
        });
        marker.addListener('mouseout', function() {
            this.setIcon(defaultIcon);
        });
        marker.addListener('click', function() {
            populateInfoWindow(marker, largeInfowindow);
        });

        map.setCenter(this.location);
        map.setZoom(15);

        markers_filter.push(marker);

        populateInfoWindow(marker, largeInfowindow);

    };
    // List of all the location for `self.fliterLocation`
    self.items = ko.observableArray();

    // Sanity check
    self.throttledFilterLocation = ko.computed(self.filterLocation)
        .extend({ rateLimit: { timeout: 500, method: "notifyWhenChangesStop" } });

    self.filterDefaultLocation = ko.observable();

    // Used to filter default locations from the `self.defaultItems`. This is case sensitive.
    this.filterDefaultLocationList = ko.computed(function() {

        return ko.utils.arrayFilter(self.defaultItems(), function(item) {
            if (self.filterDefaultLocation() == undefined)
                return true;
            else if (item.title.indexOf(self.filterDefaultLocation()) === -1)
                return false;
            else
                return true;
        });
    });

    this.filterDefaultLocationList.subscribe(function (list) {
        // var marker_filter = [];

                self.hideListings();
        var defaultIcon = makeMarkerIcon('0091ff');
        var highlightedIcon = makeMarkerIcon('FFFF24');
        for (var index = 0; index < list.length; index++) {
                                var marker = new google.maps.Marker({
                        position: list[index].location,
                        title: list[index].titlle,
                        animation: google.maps.Animation.DROP,
                        id: index,
                        map:map,
                        optimized: false // stops the marker from flashing
                    });
                    var largeInfowindow = new google.maps.InfoWindow();

                    marker.addListener('click', function onClickFunction() {
                        populateInfoWindow(this, largeInfowindow);
                    });
                    // Two event listeners - one for mouseover, one for mouseout,
                    // to change the colors back and forth.
                    marker.addListener('mouseover', function() {
                        this.setIcon(highlightedIcon);
                    });
                    marker.addListener('mouseout', function() {
                        this.setIcon(defaultIcon);
                    });

                    markers_filter.push(marker);

                    // self.items.push(marker);
                }
        // showListings(markers_filter);
    });

    // Fetches locations using google maps api and populates the `markers_filter`.
    // This function waits untill user has finished typing.
    self.throttledFilterLocation.subscribe(function(newValue) {
        self.filterDefaultLocation('');
        if (self.filterLocation().length <= 0) {
            return;
        }

        self.hideListings();

        self.items([]);
        markers_filter = [];

        // Return the geocoding for filtered locations
        zoomToArea(newValue).then(function(response) {
            if (response.status) {

                var list = response.results;

                var defaultIcon = makeMarkerIcon('0091ff');

                // Create a "highlighted location" marker color for when the user
                // mouses over the marker.
                var highlightedIcon = makeMarkerIcon('FFFF24');

                for (var index = 0; index < list.length; index++) {
                    var add;
                    var item = {
                        location: list[index].geometry.location,
                        address: list[index].formatted_address
                    };

                    var marker = new google.maps.Marker({
                        position: list[index].geometry.location,
                        title: list[index].address_components[0].short_name,
                        animation: google.maps.Animation.DROP,
                        id: index,
                        icon: defaultIcon,
                        optimized: false // stops the marker from flashing
                    });
                    var largeInfowindow = new google.maps.InfoWindow();

                    marker.addListener('click', function onClickFunction() {
                        populateInfoWindow(this, largeInfowindow);
                    });
                    // Two event listeners - one for mouseover, one for mouseout,
                    // to change the colors back and forth.
                    marker.addListener('mouseover', function() {
                        this.setIcon(highlightedIcon);
                    });
                    marker.addListener('mouseout', function() {
                        this.setIcon(defaultIcon);
                    });

                    markers_filter.push(marker);

                    self.items.push(marker);
                }

                showListings(markers_filter);
                self.isListVisible(true);
            } else {
                alert('Ooppsss, Something Went wrong!!');
            }
        });
    });

    // List Item that is selected
    self.selectedItem = function() {
        var location = { lat: this.position.lat(), lng: this.position.lng() };

        // populateInfoWindow(this,google.maps.InfoWindow());
        // this.trigger('click');
        map.setCenter(location);
        map.setZoom(15);
        var event = new google.maps.event.trigger(this, 'click');
        self.items([]);
        self.isListVisible(false);
        self.filterLocation('');
    };

    // Binding to show listings
    self.showListings = function() {
        self.filterLocation('');
        showListings(markers);
        if (markers_filter.length)
            showListings(markers_filter);

    };

    //Binding to hide listings
    self.hideListings = function() {

        if (markers.length)
            hideListings(markers);

        // If filtered locations are present then clear
        if (markers_filter.length) {
            hideListings(markers_filter);
            markers_filter = [];
            self.items([]);
            self.isListVisible(false);
            // self.filterLocation('');
        }
    };
}

var RootModel = {
    view: new ViewModel(),
    maps: new MapsModel()
};
ko.applyBindings(RootModel);

$(window).resize(function() {
    resizeMap();
});<|endoftext|>


<commit_before>(function() {
  module.exports = {
    foo: function() {
      return console.log('test');
    }
  };

}).call(this);
<commit_msg>Didn't mean to add this file...<commit_after><|endoftext|>


<commit_before><commit_msg>Update project webtorrent to 0.77.0<commit_after><|endoftext|>


<commit_before>/**
 * Copyright reelyActive 2014-2015
 * We believe in an open Internet of Things
 */

var midi = require('midi');
var util = require('util');
var events = require('events');

var VIRTUAL_PORT_NAME = "reelyActive";
var DEFAULT_MIDI_PORT_NUMBER = 0;
var DEFAULT_NOTE = 60;
var DEFAULT_VELOCITY = 127;
var STATUS_NOTE_ON = 0x90;
var STATUS_NOTE_OFF = 0x80;

/**
 * MIDIoT Class
 * Musical Instrument Digital Interface of Things.
 * @param {Object} options The options as a JSON object.
 * @constructor
 */
function MIDIoT(options) {
  var self = this;
  options = options || {};

  this.midiOut = new midi.output();
  this.midiOut.openVirtualPort(VIRTUAL_PORT_NAME);

  events.EventEmitter.call(this);
};
util.inherits(MIDIoT, events.EventEmitter);

/**
 * Bind to the given data stream.
 * @param {Object} options The options as a JSON object.
 */
MIDIoT.prototype.bind = function(options) {
  options = options || {};
  var self = this;

  if(options.barnowl) {
    self.middleware = options.barnowl;
    self.middleware.on('visibilityEvent', function(tiraid) {
      handleNotification(self, 'decoding', tiraid);
    });
  }
  if(options.barnacles) {
    self.notifications = options.barnacles;
    self.notifications.on('appearance', function(tiraid) {
      handleNotification(self, 'appearance', tiraid);
    });
    self.notifications.on('displacement', function(tiraid) {
      handleNotification(self, 'displacement', tiraid);
    });
    self.notifications.on('disappearance', function(tiraid) {
      handleNotification(self, 'disappearance', tiraid);
    });
  }
}

/**
 * Return the available output ports as a JSON object.
 */
MIDIoT.prototype.getPorts = function() {
  var self = this;
  var ports = {};
  var numberOfPorts = this.midiOut.getPortCount();

  for(var cPort = 0; cPort < numberOfPorts; cPort++) {
    ports[cPort] = self.midiOut.getPortName(cPort);
  }
  return ports;
}

/**
 * Open the given output port.
 * @param {Number} portNumber The port number.
 */
MIDIoT.prototype.openPort = function(portNumber) {
  portNumber = portNumber || DEFAULT_MIDI_PORT_NUMBER;
  this.midiOut.openPort(portNumber);
}

/**
 * Output a MIDI message.
 * @param {Object} message The MIDI message as a JSON object.
 */
MIDIoT.prototype.outputMessage = function(message) {
  message = message || {};
  var self = this;

  if(message.noteOn) {
    self.midiOut.sendMessage(getMessageCodes('noteOn', message.noteOn));
  }
  else if(message.noteOff) {
    self.midiOut.sendMessage(getMessageCodes('noteOff', message.noteOff));
  }
  else {
    self.midiOut.sendMessage(getMessageCodes());
  }
}

/**
 * Handle a notification from barnowl or barnacle
 * @param {MIDIoT} instance The given MIDIoT instance.
 * @param {String} type The notification type.
 * @param {Object} tiraid The notification tiraid.
 */
function handleNotification(instance, type, tiraid) {
  var id = tiraid.identifier.value;
  var rssi = tiraid.radioDecodings[0].rssi;
  var strongestDecoder = tiraid.radioDecodings[0].identifier.value;
  var decoders = tiraid.radioDecodings.length;
  var decodings = {};
  for(var cDecoding = 0; cDecoding < decoders; cDecoding++) {
    var decoderId = tiraid.radioDecodings[cDecoding].identifier.value;
    var decoderRssi = tiraid.radioDecodings[cDecoding].rssi;
    decodings[decoderId] = decoderRssi;
  }
  instance.emit('event', { id: id, rssi: rssi,
                           strongestDecoder: strongestDecoder,
                           decodings: decodings });
}

/**
 * Convert a message type and options into the corresponding MIDI code
 * @param {String} type The message type.
 * @param {Object} options The message options.
 */
function getMessageCodes(type, options) {
  switch(type) {
    case "noteOn":
      var channel = (options.channel % 16) || 0;
      var status = STATUS_NOTE_ON + channel;
      var data1 = (options.key % 127) || DEFAULT_NOTE;
      var data2 = (options.velocity % 127) || DEFAULT_VELOCITY;
      return [status, data1, data2];
    case "noteOff":
      var channel = (options.channel % 16) || 0;
      var status = STATUS_NOTE_OFF + channel;
      var data1 = (options.key % 127) || DEFAULT_NOTE;
      var data2 = (options.velocity % 127) || DEFAULT_VELOCITY;
      return [status, data1, data2];
    default:
      return [STATUS_NOTE_ON, DEFAULT_NOTE, DEFAULT_VELOCITY];
  }
}

module.exports = MIDIoT;
<commit_msg>Added keep-alive event functionality<commit_after>/**
 * Copyright reelyActive 2014-2015
 * We believe in an open Internet of Things
 */

var midi = require('midi');
var util = require('util');
var events = require('events');

var VIRTUAL_PORT_NAME = "reelyActive";
var DEFAULT_MIDI_PORT_NUMBER = 0;
var DEFAULT_NOTE = 60;
var DEFAULT_VELOCITY = 127;
var STATUS_NOTE_ON = 0x90;
var STATUS_NOTE_OFF = 0x80;

/**
 * MIDIoT Class
 * Musical Instrument Digital Interface of Things.
 * @param {Object} options The options as a JSON object.
 * @constructor
 */
function MIDIoT(options) {
  var self = this;
  options = options || {};

  this.midiOut = new midi.output();
  this.midiOut.openVirtualPort(VIRTUAL_PORT_NAME);

  events.EventEmitter.call(this);
};
util.inherits(MIDIoT, events.EventEmitter);

/**
 * Bind to the given data stream.
 * @param {Object} options The options as a JSON object.
 */
MIDIoT.prototype.bind = function(options) {
  options = options || {};
  var self = this;

  if(options.barnowl) {
    self.middleware = options.barnowl;
    self.middleware.on('visibilityEvent', function(tiraid) {
      handleNotification(self, 'decoding', tiraid);
    });
  }
  if(options.barnacles) {
    self.notifications = options.barnacles;
    self.notifications.on('appearance', function(tiraid) {
      handleNotification(self, 'appearance', tiraid);
    });
    self.notifications.on('keep-alive', function(tiraid) {
      handleNotification(self, 'keep-alive', tiraid);
    });
    self.notifications.on('displacement', function(tiraid) {
      handleNotification(self, 'displacement', tiraid);
    });
    self.notifications.on('disappearance', function(tiraid) {
      handleNotification(self, 'disappearance', tiraid);
    });
  }
}

/**
 * Return the available output ports as a JSON object.
 */
MIDIoT.prototype.getPorts = function() {
  var self = this;
  var ports = {};
  var numberOfPorts = this.midiOut.getPortCount();

  for(var cPort = 0; cPort < numberOfPorts; cPort++) {
    ports[cPort] = self.midiOut.getPortName(cPort);
  }
  return ports;
}

/**
 * Open the given output port.
 * @param {Number} portNumber The port number.
 */
MIDIoT.prototype.openPort = function(portNumber) {
  portNumber = portNumber || DEFAULT_MIDI_PORT_NUMBER;
  this.midiOut.openPort(portNumber);
}

/**
 * Output a MIDI message.
 * @param {Object} message The MIDI message as a JSON object.
 */
MIDIoT.prototype.outputMessage = function(message) {
  message = message || {};
  var self = this;

  if(message.noteOn) {
    self.midiOut.sendMessage(getMessageCodes('noteOn', message.noteOn));
  }
  else if(message.noteOff) {
    self.midiOut.sendMessage(getMessageCodes('noteOff', message.noteOff));
  }
  else {
    self.midiOut.sendMessage(getMessageCodes());
  }
}

/**
 * Handle a notification from barnowl or barnacle
 * @param {MIDIoT} instance The given MIDIoT instance.
 * @param {String} type The notification type.
 * @param {Object} tiraid The notification tiraid.
 */
function handleNotification(instance, type, tiraid) {
  var id = tiraid.identifier.value;
  var rssi = tiraid.radioDecodings[0].rssi;
  var strongestDecoder = tiraid.radioDecodings[0].identifier.value;
  var decoders = tiraid.radioDecodings.length;
  var decodings = {};
  for(var cDecoding = 0; cDecoding < decoders; cDecoding++) {
    var decoderId = tiraid.radioDecodings[cDecoding].identifier.value;
    var decoderRssi = tiraid.radioDecodings[cDecoding].rssi;
    decodings[decoderId] = decoderRssi;
  }
  instance.emit('event', { id: id, rssi: rssi,
                           strongestDecoder: strongestDecoder,
                           decodings: decodings });
}

/**
 * Convert a message type and options into the corresponding MIDI code
 * @param {String} type The message type.
 * @param {Object} options The message options.
 */
function getMessageCodes(type, options) {
  switch(type) {
    case "noteOn":
      var channel = (options.channel % 16) || 0;
      var status = STATUS_NOTE_ON + channel;
      var data1 = (options.key % 127) || DEFAULT_NOTE;
      var data2 = (options.velocity % 127) || DEFAULT_VELOCITY;
      return [status, data1, data2];
    case "noteOff":
      var channel = (options.channel % 16) || 0;
      var status = STATUS_NOTE_OFF + channel;
      var data1 = (options.key % 127) || DEFAULT_NOTE;
      var data2 = (options.velocity % 127) || DEFAULT_VELOCITY;
      return [status, data1, data2];
    default:
      return [STATUS_NOTE_ON, DEFAULT_NOTE, DEFAULT_VELOCITY];
  }
}

module.exports = MIDIoT;
<|endoftext|>


<commit_before>/*
---

name: PictureSlider

description: Animated picture slider.

license: MIT-style

authors:
- Peter Kuma

requires:
- core/1.4.3: [Class, Element.Style, Fx.Tween]

provides: PictureSlider

...
*/

var PictureSlider = new Class({
	Implements: [Options,Events],

	options: {
		arrows: 'medium',
		duration: 'short',
		center: true,
		controls: {
			opacity: 0.8,
			duration: 'short'
		},
		caption: {
			opacity: 0.8,
			duration: 'short'
		},
		text: {
			duration: 200
		}
	},

	initialize: function(obj, images, options) {
		this.setOptions(options);
		var this_ = this;

		this.images = [];
		this.current = null;

		this.obj = obj;
		obj.addClass('picture-slider');

		/* Determine width and height. */
		this.width = obj.getStyle('width').toInt();
		this.height = obj.getStyle('height').toInt();

		/* Sheet. */
		this.sheet = new Element('div');
		this.sheet.addClass('ps-sheet');
		this.sheet.setStyle('width', this.width);
		this.sheet.setStyle('height', this.height);
		obj.appendChild(this.sheet);

		/* Place images on the sheet. */
		images.each(function(image) { this_.appendImage(image); });

		/* Bottom description panel. */
		this.caption = new Element('div');
		this.caption.addClass('ps-caption');
		this.caption.setStyle('height', 0);
		this.caption.setStyle('opacity', this.options.caption.opacity);
		this.caption.p = new Element('p');
		this.caption.p.set('tween', {duration: this.options.caption.duration});
		this.caption.appendChild(this.caption.p);
		this.obj.appendChild(this.caption);

		/* Controls. */
		this.controls = new Element('div');
		this.controls.addClass('ps-controls');
		this.controls.setStyle('width', this.width);
		this.controls.setStyle('height', this.height);
		this.controls.setStyle('opacity', 0);
		this.controls.set('tween',  {duration: this.options.controls.duration});
		this.obj.appendChild(this.controls);

		this.leftArrow = new Element('div');
		this.leftArrow.addClass('ps-left');
		if (this.options.arrows)
			this.leftArrow.addClass('ps-left-'+this.options.arrows);
		//this.leftArrow.setStyle('width', this.width*0.3);
		this.leftArrow.setStyle('height', this.height);
		this.leftArrow.setStyle('opacity', 0);
		this.leftArrow.addEvent('click', function() { this_.left(); });
		this.controls.appendChild(this.leftArrow);

		this.rightArrow = new Element('div');
		this.rightArrow.addClass('ps-right');
		if (this.options.arrows)
			this.rightArrow.addClass('ps-right-'+this.options.arrows);
		//this.rightArrow.setStyle('width', this.width*0.3);
		this.rightArrow.setStyle('height', this.height);
		this.rightArrow.setStyle('opacity', 0);
		this.rightArrow.addEvent('click', function() { this_.right(); });
		this.controls.appendChild(this.rightArrow);

		this.obj.addEvent('mouseover', function() { this_.activateControls(); });
		this.obj.addEvent('mouseout', function() { this_.deactivateControls(); });

		/* Keyboard control. */
		this.kb = null;
		if (typeof Keyboard != 'undefined') {
			this.kb = new Keyboard({
				defaultEventType: 'keydown',
				events: {
					'left': function() { this_.left(); },
					'right': function() { this_.right(); }
				}
			});
			this.kb.activate();
		}

		/* Switch to the first image. */
		this.switchTo(0);
	},

	activateControls: function() {
		this.controls.fade(this.options.controls.opacity);
		/* The last to get focus gets the keyboard. */
		if (this.kb) this.kb.activate();
	},

	deactivateControls: function() {
		this.controls.fade(0);
	},

	/*
	 * Switches to the image number n.
	 */
	switchTo: function(n) {
		if (!(n >= 0 && n < this.images.length))
			return this.current;

		this.current = this.images[n];

		var fx = new Fx.Tween(this.sheet, {
			duration: this.options.duration,
			property: 'left'
		});
		fx.start(-n*this.width);

		/* If at the beginning, hide left arrow. */
		if (n == 0)
			this.leftArrow.fade(0);
		else
			this.leftArrow.fade(1);

		/* If at the end, hide right arrow. */
		if (n == this.images.length - 1)
			this.rightArrow.fade(0);
		else
			this.rightArrow.fade(1);

		this.setCaption(this.current.caption);
		this.n = n;

		this.fireEvent('change', this.current);

		return this.current;
	},

	/*
	 * Switches to the previous image.
	 */
	left: function() {
		return this.switchTo(this.n - 1);
	},

	/*
	 * Switches to the next image.
	 */
	right: function() {
		return this.switchTo(this.n + 1);
	},

	/*
	 * Appends image to the end.
	 */
	appendImage: function(image) {
		var frame;
		if (image.link) {
			frame = new Element('a');
			frame.href = image.link;
		} else {
			frame = new Element('div');
		}
		frame.addClass('ps-frame');
		frame.setStyle('left', this.width*this.images.length);
		frame.setStyle('width', this.width);
		frame.setStyle('height', this.height);
		this.sheet.appendChild(frame);

		var center = this.options.center;
		if (typeof image.center != 'undefined')
			center = image.center;

		if (image.src) {
			var img = new Element('img');
			img.addClass('ps-frame-image');
			img.src = image.src;
			frame.appendChild(img);
			var this_ = this;
			img.addEvent('load', function() {
				if (img.width/img.height > this_.width/this_.height) {
					img.width = this_.width;
				} else {
					img.height = this_.height;
				}
				if (center)
					img.setStyle('top', (this_.height-img.height)/2);
			});
		}

		if (image.content) {
			var content = new Element('div');
			content.addClass('ps-frame-content');
			frame.appendChild(content);
			if (typeof image.content == 'string') {
				content.innerHTML = image.content;
			}
			var w = content.getStyle('width').toInt();
			var pad = content.getStyle('padding-left').toInt() +
		    		  content.getStyle('padding-right').toInt();
		 	var mar = content.getStyle('margin-left').toInt() +
		   			  content.getStyle('margin-right').toInt();
			content.setStyle('left', (this.width-w-pad-mar)/2);
			if (center) {
				var h = content.getStyle('height').toInt();
				var pad = content.getStyle('padding-top').toInt() +
		    			  content.getStyle('padding-bottom').toInt();
		 		var mar = content.getStyle('margin-top').toInt() +
		   				  content.getStyle('margin-bottom').toInt();
		   		var top = (this.height-h-pad-mar)/2;
		   		if (top > 0)
					content.setStyle('top', (this.height-h-pad-mar)/2);
			}
		}

		this.images.push(image);
	},

	/*
	 * Set caption to text.
	 */
	setCaption: function(text) {
		var fx = new Fx.Tween(this.caption, {
			duration: this.options.text.duration,
			property: 'height',
			link: 'chain'
		});

		if (text) {
			var this_ = this;
			fx.addEvent('complete', function() {
				this_.caption.p.innerHTML = text;
				this_.caption.p.fade(1);
			});
			this.caption.p.fade(0);
			var tmpcaption = new Element('div');
			tmpcaption.addClass('ps-caption');
			tmpcaption.setStyle('visibility', 'hidden');
			tmpcaption.p = new Element('p');
			tmpcaption.p.innerHTML = text;
			tmpcaption.appendChild(tmpcaption.p);
			this.obj.appendChild(tmpcaption);
			h = tmpcaption.getStyle('height');
			this.obj.removeChild(tmpcaption);
			fx.start(h);
		} else {
			this.caption.p.innerHTML = '';
			this.caption.p.fade(0);
			fx.start(0);
		}
	}
});

<commit_msg>Fix issue with IE7 -- set innerHTML via mootools.<commit_after>/*
---

name: PictureSlider

description: Animated picture slider.

license: MIT-style

authors:
- Peter Kuma

requires:
- core/1.4.3: [Class, Element.Style, Fx.Tween]

provides: PictureSlider

...
*/

var PictureSlider = new Class({
	Implements: [Options,Events],

	options: {
		arrows: 'medium',
		duration: 'short',
		center: true,
		controls: {
			opacity: 0.8,
			duration: 'short'
		},
		caption: {
			opacity: 0.8,
			duration: 'short'
		},
		text: {
			duration: 200
		}
	},

	initialize: function(obj, images, options) {
		this.setOptions(options);
		var this_ = this;

		this.images = [];
		this.current = null;

		this.obj = obj;
		obj.addClass('picture-slider');

		/* Determine width and height. */
		this.width = obj.getStyle('width').toInt();
		this.height = obj.getStyle('height').toInt();

		/* Sheet. */
		this.sheet = new Element('div');
		this.sheet.addClass('ps-sheet');
		this.sheet.setStyle('width', this.width);
		this.sheet.setStyle('height', this.height);
		obj.appendChild(this.sheet);

		/* Place images on the sheet. */
		images.each(function(image) { this_.appendImage(image); });

		/* Bottom description panel. */
		this.caption = new Element('div');
		this.caption.addClass('ps-caption');
		this.caption.setStyle('height', 0);
		this.caption.setStyle('opacity', this.options.caption.opacity);
		this.caption.p = new Element('p');
		this.caption.p.set('tween', {duration: this.options.caption.duration});
		this.caption.appendChild(this.caption.p);
		this.obj.appendChild(this.caption);

		/* Controls. */
		this.controls = new Element('div');
		this.controls.addClass('ps-controls');
		this.controls.setStyle('width', this.width);
		this.controls.setStyle('height', this.height);
		this.controls.setStyle('opacity', 0);
		this.controls.set('tween',  {duration: this.options.controls.duration});
		this.obj.appendChild(this.controls);

		this.leftArrow = new Element('div');
		this.leftArrow.addClass('ps-left');
		if (this.options.arrows)
			this.leftArrow.addClass('ps-left-'+this.options.arrows);
		//this.leftArrow.setStyle('width', this.width*0.3);
		this.leftArrow.setStyle('height', this.height);
		this.leftArrow.setStyle('opacity', 0);
		this.leftArrow.addEvent('click', function() { this_.left(); });
		this.controls.appendChild(this.leftArrow);

		this.rightArrow = new Element('div');
		this.rightArrow.addClass('ps-right');
		if (this.options.arrows)
			this.rightArrow.addClass('ps-right-'+this.options.arrows);
		//this.rightArrow.setStyle('width', this.width*0.3);
		this.rightArrow.setStyle('height', this.height);
		this.rightArrow.setStyle('opacity', 0);
		this.rightArrow.addEvent('click', function() { this_.right(); });
		this.controls.appendChild(this.rightArrow);

		this.obj.addEvent('mouseover', function() { this_.activateControls(); });
		this.obj.addEvent('mouseout', function() { this_.deactivateControls(); });

		/* Keyboard control. */
		this.kb = null;
		if (typeof Keyboard != 'undefined') {
			this.kb = new Keyboard({
				defaultEventType: 'keydown',
				events: {
					'left': function() { this_.left(); },
					'right': function() { this_.right(); }
				}
			});
			this.kb.activate();
		}

		/* Switch to the first image. */
		this.switchTo(0);
	},

	activateControls: function() {
		this.controls.fade(this.options.controls.opacity);
		/* The last to get focus gets the keyboard. */
		if (this.kb) this.kb.activate();
	},

	deactivateControls: function() {
		this.controls.fade(0);
	},

	/*
	 * Switches to the image number n.
	 */
	switchTo: function(n) {
		if (!(n >= 0 && n < this.images.length))
			return this.current;

		this.current = this.images[n];

		var fx = new Fx.Tween(this.sheet, {
			duration: this.options.duration,
			property: 'left'
		});
		fx.start(-n*this.width);

		/* If at the beginning, hide left arrow. */
		if (n == 0)
			this.leftArrow.fade(0);
		else
			this.leftArrow.fade(1);

		/* If at the end, hide right arrow. */
		if (n == this.images.length - 1)
			this.rightArrow.fade(0);
		else
			this.rightArrow.fade(1);

		this.setCaption(this.current.caption);
		this.n = n;

		this.fireEvent('change', this.current);

		return this.current;
	},

	/*
	 * Switches to the previous image.
	 */
	left: function() {
		return this.switchTo(this.n - 1);
	},

	/*
	 * Switches to the next image.
	 */
	right: function() {
		return this.switchTo(this.n + 1);
	},

	/*
	 * Appends image to the end.
	 */
	appendImage: function(image) {
		var frame;
		if (image.link) {
			frame = new Element('a');
			frame.href = image.link;
		} else {
			frame = new Element('div');
		}
		frame.addClass('ps-frame');
		frame.setStyle('left', this.width*this.images.length);
		frame.setStyle('width', this.width);
		frame.setStyle('height', this.height);
		this.sheet.appendChild(frame);

		var center = this.options.center;
		if (typeof image.center != 'undefined')
			center = image.center;

		if (image.src) {
			var img = new Element('img');
			img.addClass('ps-frame-image');
			img.src = image.src;
			frame.appendChild(img);
			var this_ = this;
			img.addEvent('load', function() {
				if (img.width/img.height > this_.width/this_.height) {
					img.width = this_.width;
				} else {
					img.height = this_.height;
				}
				if (center)
					img.setStyle('top', (this_.height-img.height)/2);
			});
		}

		if (image.content) {
			var content = new Element('div');
			content.addClass('ps-frame-content');
			frame.appendChild(content);
			if (typeof image.content == 'string') {
				content.set('html', image.content);
			}
			var w = content.getStyle('width').toInt();
			var pad = content.getStyle('padding-left').toInt() +
		    		  content.getStyle('padding-right').toInt();
		 	var mar = content.getStyle('margin-left').toInt() +
		   			  content.getStyle('margin-right').toInt();
			content.setStyle('left', (this.width-w-pad-mar)/2);
			if (center) {
				var h = content.getStyle('height').toInt();
				var pad = content.getStyle('padding-top').toInt() +
		    			  content.getStyle('padding-bottom').toInt();
		 		var mar = content.getStyle('margin-top').toInt() +
		   				  content.getStyle('margin-bottom').toInt();
		   		var top = (this.height-h-pad-mar)/2;
		   		if (top > 0)
					content.setStyle('top', (this.height-h-pad-mar)/2);
			}
		}

		this.images.push(image);
	},

	/*
	 * Set caption to text.
	 */
	setCaption: function(text) {
		var fx = new Fx.Tween(this.caption, {
			duration: this.options.text.duration,
			property: 'height',
			link: 'chain'
		});

		if (text) {
			var this_ = this;
			fx.addEvent('complete', function() {
				this_.caption.p.innerHTML = text;
				this_.caption.p.fade(1);
			});
			this.caption.p.fade(0);
			var tmpcaption = new Element('div');
			tmpcaption.addClass('ps-caption');
			tmpcaption.setStyle('visibility', 'hidden');
			tmpcaption.p = new Element('p');
			tmpcaption.p.innerHTML = text;
			tmpcaption.appendChild(tmpcaption.p);
			this.obj.appendChild(tmpcaption);
			h = tmpcaption.getStyle('height');
			this.obj.removeChild(tmpcaption);
			fx.start(h);
		} else {
			this.caption.p.innerHTML = '';
			this.caption.p.fade(0);
			fx.start(0);
		}
	}
});

<|endoftext|>