<commit_before>/** @module TickerView */

define([
    'streamhub-zepto',
    'streamhub-ticker/views/FeedTickerView',
    'streamhub-sdk',
    'streamhub-sdk/view',
    'streamhub-sdk/util',
    'text!streamhub-ticker/main.css'],
function($, FeedTickerView, Hub, View, Util, css) {

	/**
	 * TickerView is a view of Streamhub data that is structured as a horizontal ticker, similar to
	 * television media's ticker, time based, LTR. When the feedCollection option is specified, the
	 * ticker view will use the content items in the feedCollection to populate the Y-axis of the
	 * ticker, stacking all feedCollection items above the appropriate Ticker items, based on the
	 * create date of the content.
	 * @alias module:TickerView
	 * @constructor
	 * @param {Object.<string, *>} opts A set of options to configure this instance.
	 * @param {Hub.Collection|undefined} opts.feedStreamName The feed collection that this ticker will
	 *        use to populate it's Y axis.
	 * @param {Object.<string, *>} opts.sources A set of source specific options.
	 * @param {string} opts.metaElement The selector of an element inside the bodyHtml of each content
	 *        item that contains the meta data for this content item.
     * @param {string} opts.className The css class name that this object will apply to it's holding
     *        element (defaults to "hub-TickerView").
	 */
	var TickerView = function(opts) {
        opts = opts || {};
        View.call(this, opts);
        var self = this;
        this.$el = $(this.el);
        this.$el.addClass(opts.className || "hub-TickerView");
        this.$el.hide();
        this.$el.fadeIn();
        this.includeCss = opts.includeCss == false ? false : true;
        // Include CSS
        if (this.includeCss) {
            $('').text(css).prependTo('head');
        }

        var TickerContentAdder = {
            add: function(content, stream) {
                self.add.apply(self, arguments);
            }
        };
        var FeedTickerContentAdder = {
            add: function(content, stream) {
                self.addFeedItem.apply(self, arguments);
            }
        };
        this.main = TickerContentAdder;
        this.feed = FeedTickerContentAdder;

        this.childViews = {};
        this.metaElement = opts.metaElement;
    };
    $.extend(TickerView.prototype, View.prototype);

	/**
	 * Inserts a new piece of content into the dom. Used as a callback handler
	 * for collection.add events.
	 * @param {Object} item A piece of content that was streamed to this view from Streamhub.
	 * @return {Object} The $html element that was inserted.
	 * @protected
	 */
	TickerView.prototype.add = function (item) {
	    if (!item.author) { return; }

	    var contentView = this.createContentView(item);
	    contentView.render();

	    var feedEl = $(document.createElement('div'));
	    feedEl.addClass('item-feed-view');

	    var contentEl = $(contentView.el);
	    contentEl.addClass('item-content-view');

	    var itemEl = $(document.createElement('div'));
	    itemEl.append(feedEl);
	    itemEl.append(contentEl);

	    var itemMetaEl = $('
' + item.body + '
').find(this.metaElement);
	    var itemMeta = {};
	    try { itemMeta = JSON.parse(itemMetaEl.text()) || {}; } catch (ex) {}

	    itemEl
	      .addClass('hub-item')
	      .attr('data-hub-contentid', item.id)
	      .attr('data-hub-createdAt', item.createdAt)
	      .attr('data-hub-source-id', item.source);

	    if (itemMeta.eventType) {
	        itemEl.attr('data-hub-event-type', itemMeta.eventType);
	    }
	    if (itemMeta.eventUrl) {
	        itemEl.attr('data-hub-event-url', itemMeta.eventUrl);
	        contentEl.css('background', 'url(' + itemMeta.eventUrl + ') no-repeat 0px 0px');
	    }
	    if (itemMeta.eventImportant) {
	        itemEl.attr('data-hub-event-important', itemMeta.eventImportant);
	    }

	    var feedView = new FeedTickerView({el: feedEl.get(0)});

	    var key = item.createdAt*1000;
	    while (this.childViews[key]) {
	       key++;
	    }
	    key = key+"";
	    this.childViews[key] = {feedView:feedView, item: item, itemEl: itemEl};

	    this._animateAdd(key);

	    return itemEl;
	};

	/**
	 * Helper function to abstract the animation process on insertion. At this point in time,
	 * the item's main element has not been inserted into the DOM. It is the responsibility of this
	 * method to add the element to the DOM in any manner that it sees fit.
	 * @param {number|string} key The key to the childViews set for the item to be inserted.
	 * @protected
	 */
	TickerView.prototype._animateAdd = function(key) {
	    var keys = Object.keys(this.childViews);
	    keys.sort();

	    var itemEl = this.childViews[key].itemEl;
        itemEl.attr('data-hub-key', key);

	    var index = $.inArray(key, keys);
	    var prevEl;
	    for (var i = index; i >= 0; i--) {
		    var prev = this.childViews[keys[i]].item;
	    	prevEl = prev ? this.$el.find('.hub-item[data-hub-key="' + keys[i] + '"]') : null;
	    	if (prevEl && prevEl.length) {
	    	    break;
	    	}
	    }

	    var origScrollWidth = this.el.scrollWidth;

	    if (prevEl && prevEl.length > 0) {
	        itemEl.insertAfter(prevEl);
	    } else {
	        this.$el.prepend(itemEl);
	    }
	    var newScrollWidth = this.$el[0].scrollWidth;
	    var diff = newScrollWidth - origScrollWidth;
	    //var scrollWindowWidth = Util.outerWidth(this.$el);
        var itemLeft = itemEl.position().left;

	    if (!this.paused && itemLeft >= 0 && diff >= 0) {
            this.scrollDiff = (this.scrollDiff || 0) + diff;

            if (!this.isScrolling) {
		        var self = this;
                this.isScrolling = true;
		        this.animator = function() {
                    self.$el.animateScrollLeft(
                        self.$el[0].scrollLeft + self.scrollDiff,
                        300, function() {
                        if (self.scrollDiff > 0) {
                            setTimeout(self.animator, 1);
                        } else {
                            self.isScrolling = false;
                        }
                    });

	                self.scrollDiff = 0;
	            };
	            this.animator();
            }
	    } else {
	        this.$el.scrollLeft(this.$el.scrollLeft() + diff);
	    }
	};

	/**
	 * Adds feedCollection items to the appropriate collection for the child FeedTickerViews.
	 * @param {Object} item The new feed item that is to be inserted into the child.
	 * @param {Backbone.Collection} col A reference to the feedCollection that item came from.
	 * @protected
	 */
	TickerView.prototype.addFeedItem = function(item, stream) {
	    // parse the tree
	    var itemCreatedAt = item.createdAt*1000;
	    var keys = Object.keys(this.childViews).sort();

	    if (keys.length === 0) {
	        return;
	    }

	    for (var i = 0; i < keys.length; i++) {
	        if (itemCreatedAt >= parseInt(keys[i]) && (i == keys.length - 1 || itemCreatedAt < parseInt(keys[i+1]))) {
	            var feedView = this.childViews[keys[i]].feedView;
			    feedView.emit('add', item, stream);
	            break;
	        }
	    }
	};

	/**
	 * Sets the scrollLeft the TickerView such that the element containing the specified contentId
	 * aligns to the right of the current window.
	 * @param {number|string} contentId The id of the piece of content to scroll to.
	 * @return The item that was scrolled to matching contentId
	 */
	TickerView.prototype.scrollTo = function(contentId) {
	    var itemEl = this.$el.find('.hub-item[data-hub-contentid="'+ contentId +'"]');
	    if (itemEl.length < 0) {
	    	return null;
	    }

	    this.isScrolling = true;
	    var self = this;

        this.$el.animateScrollLeft(
            this.$el[0].scrollLeft + itemEl.position().left - Util.outerWidth(itemEl),
            300, function() {
	        self.isScrolling = false;
        });
	    return itemEl;
	};

    /* Extend Zepto */
    (function($, undefined) {
        var interpolate = function (source, target, shift) {
            return (source + (target - source) * shift);
        };

        var easing = function (pos) {
            return (-Math.cos(pos * Math.PI) / 2) + .5;
        };

        var scroll = function(endX, duration, callback) {
            endX = (typeof endX !== 'undefined') ? endX : 0;
            duration = (typeof duration !== 'undefined') ? duration : 200;

            if (duration === 0) {
                this[0].scrollLeft = endX;
                if (typeof callback === 'function') callback();
                return;
            }

            var startX = this[0].scrollLeft,
            startT = Date.now(),
            finishT = startT + duration;

            var self = this;
            var animate = function() {
                var now = Date.now(),
                    shift = (now > finishT) ? 1 : (now - startT) / duration;

                self[0].scrollLeft = interpolate(startX, endX, easing(shift));

                if (now < finishT) {
                    setTimeout(animate, 15);
                }
                else {
                    if (typeof callback === 'function') callback();
                }
            };

            animate();
        };

        $.fn.animateScrollLeft = function() {
            scroll.apply(this, arguments);
            return this;
        };
    })($);

	return TickerView;
});

<commit_msg>Update TickerView.js<commit_after>/** @module TickerView */

define([
    'jquery',
    'streamhub-ticker/views/FeedTickerView',
    'streamhub-sdk',
    'streamhub-sdk/view',
    'streamhub-sdk/util',
    'text!streamhub-ticker/main.css'],
function($, FeedTickerView, Hub, View, Util, css) {

	/**
	 * TickerView is a view of Streamhub data that is structured as a horizontal ticker, similar to
	 * television media's ticker, time based, LTR. When the feedCollection option is specified, the
	 * ticker view will use the content items in the feedCollection to populate the Y-axis of the
	 * ticker, stacking all feedCollection items above the appropriate Ticker items, based on the
	 * create date of the content.
	 * @alias module:TickerView
	 * @constructor
	 * @param {Object.<string, *>} opts A set of options to configure this instance.
	 * @param {Hub.Collection|undefined} opts.feedStreamName The feed collection that this ticker will
	 *        use to populate it's Y axis.
	 * @param {Object.<string, *>} opts.sources A set of source specific options.
	 * @param {string} opts.metaElement The selector of an element inside the bodyHtml of each content
	 *        item that contains the meta data for this content item.
     * @param {string} opts.className The css class name that this object will apply to it's holding
     *        element (defaults to "hub-TickerView").
	 */
	var TickerView = function(opts) {
        opts = opts || {};
        View.call(this, opts);
        var self = this;
        this.$el = $(this.el);
        this.$el.addClass(opts.className || "hub-TickerView");
        this.$el.hide();
        this.$el.fadeIn();
        this.includeCss = opts.includeCss == false ? false : true;
        // Include CSS
        if (this.includeCss) {
            $('').text(css).prependTo('head');
        }

        var TickerContentAdder = {
            add: function(content, stream) {
                self.add.apply(self, arguments);
            }
        };
        var FeedTickerContentAdder = {
            add: function(content, stream) {
                self.addFeedItem.apply(self, arguments);
            }
        };
        this.main = TickerContentAdder;
        this.feed = FeedTickerContentAdder;

        this.childViews = {};
        this.metaElement = opts.metaElement;
    };
    $.extend(TickerView.prototype, View.prototype);

	/**
	 * Inserts a new piece of content into the dom. Used as a callback handler
	 * for collection.add events.
	 * @param {Object} item A piece of content that was streamed to this view from Streamhub.
	 * @return {Object} The $html element that was inserted.
	 * @protected
	 */
	TickerView.prototype.add = function (item) {
	    if (!item.author) { return; }

	    var contentView = this.createContentView(item);
	    contentView.render();

	    var feedEl = $(document.createElement('div'));
	    feedEl.addClass('item-feed-view');

	    var contentEl = $(contentView.el);
	    contentEl.addClass('item-content-view');

	    var itemEl = $(document.createElement('div'));
	    itemEl.append(feedEl);
	    itemEl.append(contentEl);

	    var itemMetaEl = $('
' + item.body + '
').find(this.metaElement);
	    var itemMeta = {};
	    try { itemMeta = JSON.parse(itemMetaEl.text()) || {}; } catch (ex) {}

	    itemEl
	      .addClass('hub-item')
	      .attr('data-hub-contentid', item.id)
	      .attr('data-hub-createdAt', item.createdAt)
	      .attr('data-hub-source-id', item.source);

	    if (itemMeta.eventType) {
	        itemEl.attr('data-hub-event-type', itemMeta.eventType);
	    }
	    if (itemMeta.eventUrl) {
	        itemEl.attr('data-hub-event-url', itemMeta.eventUrl);
	        contentEl.css('background', 'url(' + itemMeta.eventUrl + ') no-repeat 0px 0px');
	    }
	    if (itemMeta.eventImportant) {
	        itemEl.attr('data-hub-event-important', itemMeta.eventImportant);
	    }

	    var feedView = new FeedTickerView({el: feedEl.get(0)});

	    var key = item.createdAt*1000;
	    while (this.childViews[key]) {
	       key++;
	    }
	    key = key+"";
	    this.childViews[key] = {feedView:feedView, item: item, itemEl: itemEl};

	    this._animateAdd(key);

	    return itemEl;
	};

	/**
	 * Helper function to abstract the animation process on insertion. At this point in time,
	 * the item's main element has not been inserted into the DOM. It is the responsibility of this
	 * method to add the element to the DOM in any manner that it sees fit.
	 * @param {number|string} key The key to the childViews set for the item to be inserted.
	 * @protected
	 */
	TickerView.prototype._animateAdd = function(key) {
	    var keys = Object.keys(this.childViews);
	    keys.sort();

	    var itemEl = this.childViews[key].itemEl;
        itemEl.attr('data-hub-key', key);

	    var index = $.inArray(key, keys);
	    var prevEl;
	    for (var i = index; i >= 0; i--) {
		    var prev = this.childViews[keys[i]].item;
	    	prevEl = prev ? this.$el.find('.hub-item[data-hub-key="' + keys[i] + '"]') : null;
	    	if (prevEl && prevEl.length) {
	    	    break;
	    	}
	    }

	    var origScrollWidth = this.el.scrollWidth;

	    if (prevEl && prevEl.length > 0) {
	        itemEl.insertAfter(prevEl);
	    } else {
	        this.$el.prepend(itemEl);
	    }
	    var newScrollWidth = this.$el[0].scrollWidth;
	    var diff = newScrollWidth - origScrollWidth;
	    //var scrollWindowWidth = Util.outerWidth(this.$el);
        var itemLeft = itemEl.position().left;

	    if (!this.paused && itemLeft >= 0 && diff >= 0) {
            this.scrollDiff = (this.scrollDiff || 0) + diff;

            if (!this.isScrolling) {
		        var self = this;
                this.isScrolling = true;
		        this.animator = function() {
                    self.$el.animateScrollLeft(
                        self.$el[0].scrollLeft + self.scrollDiff,
                        300, function() {
                        if (self.scrollDiff > 0) {
                            setTimeout(self.animator, 1);
                        } else {
                            self.isScrolling = false;
                        }
                    });

	                self.scrollDiff = 0;
	            };
	            this.animator();
            }
	    } else {
	        this.$el.scrollLeft(this.$el.scrollLeft() + diff);
	    }
	};

	/**
	 * Adds feedCollection items to the appropriate collection for the child FeedTickerViews.
	 * @param {Object} item The new feed item that is to be inserted into the child.
	 * @param {Backbone.Collection} col A reference to the feedCollection that item came from.
	 * @protected
	 */
	TickerView.prototype.addFeedItem = function(item, stream) {
	    // parse the tree
	    var itemCreatedAt = item.createdAt*1000;
	    var keys = Object.keys(this.childViews).sort();

	    if (keys.length === 0) {
	        return;
	    }

	    for (var i = 0; i < keys.length; i++) {
	        if (itemCreatedAt >= parseInt(keys[i]) && (i == keys.length - 1 || itemCreatedAt < parseInt(keys[i+1]))) {
	            var feedView = this.childViews[keys[i]].feedView;
			    feedView.emit('add', item, stream);
	            break;
	        }
	    }
	};

	/**
	 * Sets the scrollLeft the TickerView such that the element containing the specified contentId
	 * aligns to the right of the current window.
	 * @param {number|string} contentId The id of the piece of content to scroll to.
	 * @return The item that was scrolled to matching contentId
	 */
	TickerView.prototype.scrollTo = function(contentId) {
	    var itemEl = this.$el.find('.hub-item[data-hub-contentid="'+ contentId +'"]');
	    if (itemEl.length < 0) {
	    	return null;
	    }

	    this.isScrolling = true;
	    var self = this;

        this.$el.animateScrollLeft(
            this.$el[0].scrollLeft + itemEl.position().left - Util.outerWidth(itemEl),
            300, function() {
	        self.isScrolling = false;
        });
	    return itemEl;
	};

    /* Extend Zepto */
    (function($, undefined) {
        var interpolate = function (source, target, shift) {
            return (source + (target - source) * shift);
        };

        var easing = function (pos) {
            return (-Math.cos(pos * Math.PI) / 2) + .5;
        };

        var scroll = function(endX, duration, callback) {
            endX = (typeof endX !== 'undefined') ? endX : 0;
            duration = (typeof duration !== 'undefined') ? duration : 200;

            if (duration === 0) {
                this[0].scrollLeft = endX;
                if (typeof callback === 'function') callback();
                return;
            }

            var startX = this[0].scrollLeft,
            startT = Date.now(),
            finishT = startT + duration;

            var self = this;
            var animate = function() {
                var now = Date.now(),
                    shift = (now > finishT) ? 1 : (now - startT) / duration;

                self[0].scrollLeft = interpolate(startX, endX, easing(shift));

                if (now < finishT) {
                    setTimeout(animate, 15);
                }
                else {
                    if (typeof callback === 'function') callback();
                }
            };

            animate();
        };

        $.fn.animateScrollLeft = function() {
            scroll.apply(this, arguments);
            return this;
        };
    })($);

	return TickerView;
});

<|endoftext|>


<commit_before>var CentsView = (function () {

  function CentsView() {

    ViewContextAndStyle.apply(this,arguments);

    this.cvs.width  = 400;
    this.cvs.height = 200;

    this.centerX       = this.cvs.width / 2;
    this.centerY       = this.cvs.height;
    this.circumference = 1000;
    this.radius        = this.circumference / (2*Math.PI);
    this.quadrantArc   = this.circumference / 4;

    this.needleColor   = "rgb(58,58,58)";
    this.dotColor      = "rgb(58,58,58)";
    this.dotRadius     = 3;
    this.zeroDotColor  = "rgb(44,114,158)";
    this.zeroDotRadius = 5;
    this.markStep      = 50;
  };

  CentsView.prototype.background = function() {

    this.ctx.beginPath();
    this.ctx.arc(this.centerX,this.centerY,10,0,Math.PI,true);
    this.ctx.fillStyle = this.needleColor;
    this.ctx.fill();

    for(var arc=0; arc <= this.circumference / 2; arc+= this.markStep){
      var markRadius = this.dotRadius;
      var fillStyle  = this.dotColor;

      this.ctx.beginPath();
      var alfa = arc / this.radius;

      if (arc == this.quadrantArc){
        markRadius = this.zeroDotRadius;
        fillStyle  = this.zeroDotColor;
      }

      var x = this.centerX - this.radius * Math.cos(alfa);
      var y = this.centerY - this.radius * Math.sin(alfa);

      this.ctx.arc(x,y,markRadius,0,2*Math.PI,true);
      this.ctx.fillStyle = fillStyle;
      this.ctx.fill();
    }
  };

  CentsView.prototype.run = function() {

    var arc  = this.quadrantArc - this.peek.cents;
    var alfa = arc / this.radius;

    var x = this.centerX + this.radius * Math.cos(alfa);
    var y = this.centerY - this.radius * Math.sin(alfa);

    this.ctx.clearRect(0,0,this.cvs.width,this.cvs.height);

    this.background();

    this.ctx.font      = this.noteFont;
    this.ctx.fillStyle = this.color;
    this.ctx.fillText(this.peek.note.name,20,50);

    this.ctx.font = this.freqFont;
    this.ctx.fillText(this.peek.frequency.toFixed(2) + " Hz",this.cvs.width-110,40);

    this.ctx.beginPath();
    this.ctx.moveTo(this.centerX,this.centerY);
    this.ctx.lineTo(x,y);
    this.ctx.strokeStyle = this.needleColor;
    this.ctx.stroke();

    window.requestAnimationFrame(this.run.bind(this));
  };

  CentsView.prototype.update = function (element) {

    this.peek = element.peek;

  };

  return CentsView;

}());<commit_msg>Make CentsView a singleton.<commit_after>var CentsView = (function (containerID) {

  function CentsView() {

    ViewContextAndStyle.apply(this,arguments);

    this.cvs.width  = 400;
    this.cvs.height = 200;

    this.centerX       = this.cvs.width / 2;
    this.centerY       = this.cvs.height;
    this.circumference = 1000;
    this.radius        = this.circumference / (2*Math.PI);
    this.quadrantArc   = this.circumference / 4;

    this.needleColor   = "rgb(58,58,58)";
    this.dotColor      = "rgb(58,58,58)";
    this.dotRadius     = 3;
    this.zeroDotColor  = "rgb(44,114,158)";
    this.zeroDotRadius = 5;
    this.markStep      = 50;
  };

  CentsView.prototype.background = function() {

    this.ctx.beginPath();
    this.ctx.arc(this.centerX,this.centerY,10,0,Math.PI,true);
    this.ctx.fillStyle = this.needleColor;
    this.ctx.fill();

    for(var arc=0; arc <= this.circumference / 2; arc+= this.markStep){
      var markRadius = this.dotRadius;
      var fillStyle  = this.dotColor;

      this.ctx.beginPath();
      var alfa = arc / this.radius;

      if (arc == this.quadrantArc){
        markRadius = this.zeroDotRadius;
        fillStyle  = this.zeroDotColor;
      }

      var x = this.centerX - this.radius * Math.cos(alfa);
      var y = this.centerY - this.radius * Math.sin(alfa);

      this.ctx.arc(x,y,markRadius,0,2*Math.PI,true);
      this.ctx.fillStyle = fillStyle;
      this.ctx.fill();
    }
  };

  CentsView.prototype.run = function() {

    var arc  = this.quadrantArc - this.peek.cents;
    var alfa = arc / this.radius;

    var x = this.centerX + this.radius * Math.cos(alfa);
    var y = this.centerY - this.radius * Math.sin(alfa);

    this.ctx.clearRect(0,0,this.cvs.width,this.cvs.height);

    this.background();

    this.ctx.font      = this.noteFont;
    this.ctx.fillStyle = this.color;
    this.ctx.fillText(this.peek.note.name,20,50);

    this.ctx.font = this.freqFont;
    this.ctx.fillText(this.peek.frequency.toFixed(2) + " Hz",this.cvs.width-110,40);

    this.ctx.beginPath();
    this.ctx.moveTo(this.centerX,this.centerY);
    this.ctx.lineTo(x,y);
    this.ctx.strokeStyle = this.needleColor;
    this.ctx.stroke();

    window.requestAnimationFrame(this.run.bind(this));
  };

  CentsView.prototype.update = function (element) {

    this.peek = element.peek;

  };

  if (!this.instance) {
    this.instance = new CentsView(containerID);
  } else {
    console.log("An instance of CentsGauge already exists.");
  }

  return this.instance;

});<|endoftext|>


<commit_before>if ($("tbl_widget_content").getElementsByTagName("tfoot")[0]) {
	$("tbl_widget_content").getElementsByTagName("tfoot")[0].style.display = "none";
}
var currentImageEdit = -1;

var widgetImages = new Array();
var oldsave = $("saveWidgetProperty").onclick;

if (typeof $("saveWidgetProperty").onclick != "function") {
    $("saveWidgetProperty").onclick = commitwidgetImages;
}
else {
    $("saveWidgetProperty").onclick = function ()
    {
        commitwidgetImages();
        oldsave();
    }
}

// Load image carousel widget images into sub table

fetchImages();
iterateImages();
$('image_carousel_widget_images').show();

function addWidgetImage ()
{
    currentImageEdit = -1;
    $("image_carousel_image").value = "";
	$("image_carousel_imagei").src= "../images/no_image.gif";
    $("image_carousel_button_title").value = "";
	$("image_carousel_button_subtitle").value = "";
    $("image_carousel_link").value = "";
    $("image_carousel_link_title").value = "";
    $("lb_widget_content").getElementsByTagName("tfoot")[0].style.display = "";
    $("image_carousel_widget_images").style.display = "none";
    $("widgetImageDelete").style.display = "none";
}

function editWidgetImage (widgetImageID)
{
	currentImageEdit = widgetImageID;

    if (widgetImages[currentImageEdit][0] != null) {
        $("image_carousel_image").value = widgetImages[currentImageEdit][0];
    }
    if (widgetImages[currentImageEdit][0] != null) {
        $("image_carousel_imagei").src = 'http://'+$('DOMAIN').value+'/images/'+widgetImages[currentImageEdit][0];
    }
    if (widgetImages[currentImageEdit][1] != null) {
        $("image_carousel_button_title").value = widgetImages[currentImageEdit][1];
    }
	 if (widgetImages[currentImageEdit][2] != null) {
        $("image_carousel_button_subtitle").value = widgetImages[currentImageEdit][2];
    }
    if (widgetImages[currentImageEdit][3] != null) {
        $("image_carousel_link").value = widgetImages[currentImageEdit][3];
    }
    if (widgetImages[currentImageEdit][4] != null) {
        $("image_carousel_link_title").value = widgetImages[currentImageEdit][4];
    }
    $("lb_widget_content").getElementsByTagName("tfoot")[0].style.display = "";
    $("image_carousel_widget_images").style.display = "none";
    $("widgetImageDelete").style.display = "";
}

function saveWidgetImage ()
{
	// check all required fields have been entered
	var errors = false;

	if ($("image_carousel_button_title").value.length == 0) {
		errors = true;
	}
	else if ($("image_carousel_button_subtitle").value.length == 0) {
		errors = true;
	}
        else if ($("image_carousel_link").value.length == 0) {
		errors = true;
	}
        else if ($("image_carousel_link_title").value.length == 0) {
		errors = true;
	}

	if (!errors) {
	    if (currentImageEdit == -1) {
	        widgetImages.push(new Array($("image_carousel_image").value, $("image_carousel_button_title").value, $("image_carousel_button_subtitle").value, $("image_carousel_link").value, $("image_carousel_link_title").value));
	        // add new row
	        addImageRow (widgetImages.length - 1, widgetImages[widgetImages.length - 1]);
	    }
	    else {
	        widgetImages[currentImageEdit][0] = $("image_carousel_image").value;
	        widgetImages[currentImageEdit][1] = $("image_carousel_button_title").value;
			widgetImages[currentImageEdit][2] = $("image_carousel_button_subtitle").value;
	        widgetImages[currentImageEdit][3] = $("image_carousel_link").value;
			widgetImages[currentImageEdit][4] = $("image_carousel_link_title").value;
	        $("widgetImageText" + currentImageEdit).title = $("image_carousel_button_title").value;
	        $("widgetImageText" + currentImageEdit).innerHTML = $("image_carousel_button_title").value;
	    }

	    $("lb_widget_content").getElementsByTagName("tfoot")[0].style.display = "none";
	    $("image_carousel_widget_images").style.display = "";
	}
	else {
		alert("Please enter all required field!");
	}
}

function deleteWidgetImage ()
{
    widgetImages[currentImageEdit] = -1;

    $("widgetImageText" + currentImageEdit).parentNode.parentNode.parentNode.removeChild($("widgetImageText" + currentImageEdit).parentNode.parentNode);

    $("lb_widget_content").getElementsByTagName("tfoot")[0].style.display = "none";
    $("image_carousel_widget_images").style.display = "";
}

function closeSlide ()
{
    $("lb_widget_content").getElementsByTagName("tfoot")[0].style.display = "none";
    $("image_carousel_widget_images").style.display = "";
}

function addImageRow (ImageID, ImageObj)
{
    var tr = document.createElement("tr");
    var td = document.createElement("td");
    td.className = "label_cell";
    var aLink = document.createElement("a");
    aLink.id = "widgetImageText" + ImageID;
    aLink.href = "#";
    aLink.onclick = function ()
    {
        editWidgetImage(this.id.replace(/widgetImageText/gi, ""));
        return false;
    }
    aLink.innerHTML = ImageObj[1];
    aLink.title = ImageObj[1];
    td.appendChild(aLink);
    tr.appendChild(td);
    td = document.createElement("td");
    td.className = "data_cell";
    var moveButton = document.createElement("a");
    moveButton.href = "#";
    moveButton.id = "widgetLinkDownText" + ImageID;
    moveButton.innerHTML = "Move Down";
    moveButton.onclick = function ()
    {
        moveDown(this.id.replace(/widgetLinkDownText/gi, ""));
        return false;
    }
    td.appendChild(moveButton);
	td.appendChild(document.createTextNode("\u00a0"));
    moveButton = document.createElement("a");
    moveButton.href = "#";
    moveButton.id = "widgetLinkUpText" + ImageID;
    moveButton.innerHTML = "Move Up";
    moveButton.onclick = function ()
    {
        moveUp(this.id.replace(/widgetLinkUpText/gi, ""));
        return false;
    }
    td.appendChild(moveButton);
    tr.appendChild(td);
    $("image_carousel_widget_images").appendChild(tr);
}

function iterateImages ()
{
    for (var i = 0; i < widgetImages.length; i++) {
        addImageRow(i, widgetImages[i]);
    }
}

function fetchImages ()
{
    widgetImages.clear();
    for (var wImage in widgetItems[activeWidget].settings) {
        if (wImage.indexOf("image") >= 0 && wImage.indexOf("buttonTitle") >= 0) {
            widgetImages.push(new Array(widgetItems[activeWidget].settings[wImage.replace(/buttonTitle/gi, "imageSrc")], widgetItems[activeWidget].settings[wImage], widgetItems[activeWidget].settings[wImage.replace(/buttonTitle/gi, "buttonSubtitle")], widgetItems[activeWidget].settings[wImage.replace(/buttonTitle/gi, "link")], widgetItems[activeWidget].settings[wImage.replace(/buttonTitle/gi, "link_title")]));
        }
    }
}

function commitwidgetImages ()
{
    widgetItems[activeWidget].settings = new Object();

    for (var i = 0; i < widgetImages.length; i++) {
    	if (widgetImages[i][0] != undefined) {
	        widgetItems[activeWidget].settings["image" + i + "imageSrc"] = widgetImages[i][0];
	        widgetItems[activeWidget].settings["image" + i + "buttonTitle"] = widgetImages[i][1];
			widgetItems[activeWidget].settings["image" + i + "buttonSubtitle"] = widgetImages[i][2];
	        widgetItems[activeWidget].settings["image" + i + "link"] = widgetImages[i][3];
	        widgetItems[activeWidget].settings["image" + i + "link_title"] = widgetImages[i][4];
    	}
    }

    $("image_carousel_image").parentNode.removeChild($("image_carousel_image"));
    $("image_carousel_link").parentNode.removeChild($("image_carousel_link"));
	$("image_carousel_link_title").parentNode.removeChild($("image_carousel_link_title"));
    $("image_carousel_button_title").parentNode.removeChild($("image_carousel_button_title"));
    $("image_carousel_button_subtitle").parentNode.removeChild($("image_carousel_button_subtitle"));
}

function moveUp (widgetImageID)
{
    var tempLink = null;
    if (widgetImageID > 0) {
        tempLink = widgetImages[widgetImageID - 1];
        widgetImages[widgetImageID - 1] = widgetImages[widgetImageID];
        widgetImages[widgetImageID] = tempLink;
        if ( $("image_carousel_widget_images").hasChildNodes() ) {
            while ( $("image_carousel_widget_images").childNodes.length >= 1 ) {
                $("image_carousel_widget_images").removeChild( $("image_carousel_widget_images").firstChild );
            }
        }
        iterateImages();
    }
}

function moveDown (widgetImageID)
{
    var tempLink = null;
    widgetImageID = parseInt(widgetImageID);
    if (widgetImageID < widgetImages.length - 1) {
        tempLink = widgetImages[widgetImageID + 1];
        widgetImages[widgetImageID + 1] = widgetImages[widgetImageID];
        widgetImages[widgetImageID] = tempLink;
        if ($("image_carousel_widget_images").hasChildNodes()) {
	        while ($("image_carousel_widget_images").childNodes.length >= 1) {
                $("image_carousel_widget_images").removeChild($("image_carousel_widget_images").firstChild);
            }
        }
        iterateImages();
    }
}<commit_msg>Major Refactor of the secure.js file.<commit_after>if ($("tbl_widget_content").getElementsByTagName("tfoot")[0]) {
	$("tbl_widget_content").getElementsByTagName("tfoot")[0].style.display = "none";
}
var currentEventEdit = -1;

var widgetEvents = new Array();
var oldsave = $("saveWidgetProperty").onclick;

if (typeof $("saveWidgetProperty").onclick != "function") {
    $("saveWidgetProperty").onclick = commitwidgetEvents;
}
else {
    $("saveWidgetProperty").onclick = function ()
    {
        commitWidgetEvents();
        oldsave();
    }
}

fetchEvents();
iterateEvents();
$('date_widget_dates').show();

function addWidgetEvent ()
{
    currentEventEdit = -1;
    $("event_date").value = "";
	$("event_name").value = "";
    $("event_semester").value = "";
    $(".event_terms").value = "";
    $("tbl_widget_content").getElementsByTagName("tfoot")[0].style.display = "";
    $("date_widget_dates").style.display = "none";
    $("widgetEventDelete").style.display = "none";
}

function editWidgetEvent (widgetEventId)
{
	currentEventEdit = widgetEventId;

    if (widgetEvents[currentEventEdit][0] != null) {
        $("event_date").value = widgetEvents[currentEventEdit][1];
    }
	 if (widgetEvents[currentEventEdit][1] != null) {
        $("event_name").value = widgetEvents[currentEventEdit][2];
    }
    if (widgetEvents[currentEventEdit][2] != null) {
        $("event_semester").value = widgetEvents[currentEventEdit][3];
    }
    if (widgetEvents[currentEventEdit][3] != null) {
        $(".event_terms").value = widgetEvents[currentEventEdit][4];
    }
    $("tbl_widget_content").getElementsByTagName("tfoot")[0].style.display = "";
    $("date_widget_dates").style.display = "none";
    $("widgetEventDelete").style.display = "";
}

function saveWidgetEvent ()
{
	// check all required fields have been entered
	var errors = false;

	if ($("event_date").value.length == 0) {
		errors = true;
	}
	else if ($("event_name").value.length == 0) {
		errors = true;
	}
    else if ($("event_semester").value.length == 0) {
		errors = true;
	}
    else if ($("event_year").value.length == 0) {
        errors = true;
    }
    else if ($$(".event_terms").value.length == 0) {
		errors = true;
	}

	if (!errors) {
	    if (currentEventEdit == -1) {
	        widgetEvents.push(new Array($("event_year").value, $("event_date").value, $("event_name").value, $("event_semester").value, $$(".event_terms").value));
	        // add new row
	        addImageRow (widgetEvents.length - 1, widgetEvents[widgetEvents.length - 1]);
	    }
	    else {
            widgetEvents[currentEventEdit][0] = $("event_year").value;
	        widgetEvents[currentEventEdit][1] = $("event_date").value;
			widgetEvents[currentEventEdit][2] = $("event_name").value;
	        widgetEvents[currentEventEdit][3] = $("event_semester").value;
			widgetEvents[currentEventEdit][4] = $$(".event_terms").value;
	    }

	    $("tbl_widget_content").getElementsByTagName("tfoot")[0].style.display = "none";
	    $("date_widget_dates").style.display = "";
	}
	else {
		alert("Please enter all required field!");
	}
}

function deleteWidgetEvent ()
{
    widgetEvents[currentEventEdit] = -1;

    $(currentEventEdit).parentNode.parentNode.parentNode.removeChild($(currentEventEdit).parentNode.parentNode);

    $("tbl_widget_content").getElementsByTagName("tfoot")[0].style.display = "none";
    $("date_widget_dates").style.display = "";
}

function closeEvent ()
{
    $("tbl_widget_content").getElementsByTagName("tfoot")[0].style.display = "none";
    $("date_widget_dates").style.display = "";
}

function addEventRow (EventID, EventObj)
{
    var tr = document.createElement("tr");
    var td = document.createElement("td");
    td.className = "label_cell";
    var aLink = document.createElement("a");
    aLink.id = "widgetEvent" + EventID;
    aLink.href = "#";
    aLink.onclick = function ()
    {
        editWidgetImage(this.id.replace(/widgetEvent/gi, ""));
        return false;
    }
    aLink.innerHTML = EventObj[2];
    aLink.title = EventObj[2];
    td.appendChild(aLink);
    tr.appendChild(td);
    td = document.createElement("td");
    td.className = "data_cell";
    var moveButton = document.createElement("a");
    moveButton.href = "#";
    moveButton.id = "widgetLinkDownText" + EventID;
    moveButton.innerHTML = "Move Down";
    moveButton.onclick = function ()
    {
        moveDown(this.id.replace(/widgetLinkDownText/gi, ""));
        return false;
    }
    td.appendChild(moveButton);
	td.appendChild(document.createTextNode("\u00a0"));
    moveButton = document.createElement("a");
    moveButton.href = "#";
    moveButton.id = "widgetLinkUpText" + EventID;
    moveButton.innerHTML = "Move Up";
    moveButton.onclick = function ()
    {
        moveUp(this.id.replace(/widgetLinkUpText/gi, ""));
        return false;
    }
    td.appendChild(moveButton);
    tr.appendChild(td);
    $("date_widget_dates").appendChild(tr);
}

function iterateEvents ()
{
    for (var i = 0; i < widgetEvents.length; i++) {
        addImageRow(i, widgetEvents[i]);
    }
}

function fetchEvents ()
{
    widgetEvents.clear();
    for (var wImage in widgetItems[activeWidget].settings) {
        if (wImage.indexOf("image") >= 0 && wImage.indexOf("buttonTitle") >= 0) {
            widgetEvents.push(new Array(widgetItems[activeWidget].settings[wImage.replace(/buttonTitle/gi, "imageSrc")], widgetItems[activeWidget].settings[wImage], widgetItems[activeWidget].settings[wImage.replace(/buttonTitle/gi, "buttonSubtitle")], widgetItems[activeWidget].settings[wImage.replace(/buttonTitle/gi, "link")], widgetItems[activeWidget].settings[wImage.replace(/buttonTitle/gi, "link_title")]));
        }
    }
}

function commitWidgetEvents ()
{
    widgetItems[activeWidget].settings = new Object();

    for (var i = 0; i < widgetEvents.length; i++) {
    	if (widgetEvents[i][0] != undefined) {
	        widgetItems[activeWidget].settings["image" + i + "imageSrc"] = widgetEvents[i][0];
	        widgetItems[activeWidget].settings["image" + i + "buttonTitle"] = widgetEvents[i][1];
			widgetItems[activeWidget].settings["image" + i + "buttonSubtitle"] = widgetEvents[i][2];
	        widgetItems[activeWidget].settings["image" + i + "link"] = widgetEvents[i][3];
	        widgetItems[activeWidget].settings["image" + i + "link_title"] = widgetEvents[i][4];
    	}
    }

    $("event_semester").parentNode.removeChild($("event_semester"));
	$(".event_terms").parentNode.removeChild($(".event_terms"));
    $("event_date").parentNode.removeChild($("event_date"));
    $("event_name").parentNode.removeChild($("event_name"));
}<|endoftext|>


<commit_before>$(function () {

	// Module for the status bar plugin.
	module("status-bar plugin");

		test("should provide no conflict", function () {
			// See if it response to noConflict call.
			var status_bar = $.fn.statusBar.noConflict();

			// Assert the result we wanted.
			ok(!$.fn.statusBar, 'status bar was set back to undefined (org value)');

			// Reset the value.
			$.fn.statusBar = status_bar;
		});

		test("should be defined on jquery object", function () {
			// Ensure that it's applied as a jQuery plugin.
			ok($(document.body).statusBar, 'status-bar method is defined');
		});

		test("should return element", function () {
			// Ensure that it binds to an element as expected.
			// Pass in the constructor argument for the test.
			ok($(document.body).statusBar({'statusBarFor':'test'})[0] == document.body, 'document.body returned');
		});

		test("should assign the right API endpoint", function() {
			// Assert that the correct endpoint it picked up.
			var status_bar = $('

').statusBar({'statusBarFor':'test'});

			// Assert that an endpoint was created as planned.
			equal(status_bar.data('statusBar').endpoint, '//api.sorryapp.com/1/pages/test/apologies/current', 'The correct API endpoint was assigned.');
		});

	// Tests for the basic utility methods.
	module("utility methods", {
		setup: function() {
			// prepare something for all following tests
			// Ask the plugin to provide the path
			status_bar = $('

').statusBar({'statusBarFor':'test'}).data('statusBar');
		}
	});

		test("should return path of the JS script", function() {
			// Ask the status bar for it's path.
			var path = status_bar.getpath();

			// Assert that the path is absolute related to current location as epected.
			// NOTE: This will fail if the project is moved to a new home - could do with being better written.
			equal(path, 'file:///Users/robertrawlins/Projects/status-bar/dist/', 'path was as expected.');
		});

		test("should load the approriate CSS asset in to the DOM.", function () {
			// Count the number of CSS includes already on the page.
			var existing_css_includes = $("link").length;

			// Ask the plugin to add the elements to the DOM.
			// NOTE this will load a CSS asset which cannot be found, due to the path not being right.
			status_bar.loadcss()

			// Assert the includes have incremented by one.
			equal($("link").length - existing_css_includes, 1, 'The CSS was not appened to the document.');
		});

});<commit_msg>Changes to get the specs passing.<commit_after>$(function () {

	// Module for the status bar plugin.
	module("status-bar plugin");

		test("should provide no conflict", function () {
			// See if it response to noConflict call.
			var status_bar = $.fn.statusBar.noConflict();

			// Assert the result we wanted.
			ok(!$.fn.statusBar, 'status bar was set back to undefined (org value)');

			// Reset the value.
			$.fn.statusBar = status_bar;
		});

		test("should be defined on jquery object", function () {
			// Ensure that it's applied as a jQuery plugin.
			ok($(document.body).statusBar, 'status-bar method is defined');
		});

		test("should return element", function () {
			// Ensure that it binds to an element as expected.
			// Pass in the constructor argument for the test.
			ok($(document.body).statusBar({'statusBarFor':'test'})[0] == document.body, 'document.body returned');
		});

		test("should assign the right API endpoint", function() {
			// Assert that the correct endpoint it picked up.
			var status_bar = $('

').statusBar({'statusBarFor':'test'});

			// Assert that an endpoint was created as planned.
			equal(status_bar.data('statusBar').endpoint, '//api.sorryapp.com/1/pages/test/apologies/current', 'The correct API endpoint was assigned.');
		});

	// Tests for the basic utility methods.
	module("utility methods", {
		setup: function() {
			// prepare something for all following tests
			// Ask the plugin to provide the path
			status_bar = $('

').statusBar({'statusBarFor':'test'}).data('statusBar');
		}
	});

		test("should return path of the JS script", function() {
			// Ask the status bar for it's path.
			var path = status_bar.getpath();

			// Assert that the path is absolute related to current location as epected.
			// NOTE: This will fail if the project is moved to a new home - could do with being better written.
			equal(path, 'file:///Users/robertrawlins/Sites/status-bar/dist/', 'path was as expected.');
		});

		test("should load the approriate CSS asset in to the DOM.", function () {
			// Count the number of CSS includes already on the page.
			var existing_css_includes = $("link").length;

			// Ask the plugin to add the elements to the DOM.
			// NOTE this will load a CSS asset which cannot be found, due to the path not being right.
			status_bar.loadcss()

			// Assert the includes have incremented by one.
			equal($("link").length - existing_css_includes, 1, 'The CSS was not appened to the document.');
		});

});<|endoftext|>


<commit_before>var exports = {};

var fs = require('fs');

var db = require('./db');
var errands = db.use('errands');

exports.add = function (pathToRecording, description, tags, phone_number, timestamp, callback) {
    errands.insert({
        description: description,
        tags: tags,
        phone_number: phone_number,
        timestamp: timestamp
    }, function (err, body) {
        if (err) {
            return callback(err);
        }

        fs.createReadStream(pathToRecording).pipe(
            errands.attachment.insert(body.id, 'recording.wav', null, 'audio/wav', { rev: body.rev })
        ).on('end', function () {
            callback(null, body);
        });
    });
};

exports.getAll = function (callback) {
    errands.list({include_docs: true}, function (err, result) {
        if (err) {
            callback(err);
        }

        callback(null, result);
    });
};

module.exports = exports;
<commit_msg>get from errands<commit_after>var exports = {};

var fs = require('fs');

var db = require('./db');
var errands = db.use('errands');

exports.add = function (pathToRecording, description, tags, phone_number, timestamp, callback) {
    errands.insert({
        description: description,
        tags: tags,
        phone_number: phone_number,
        timestamp: timestamp
    }, function (err, body) {
        if (err) {
            return callback(err);
        }

        fs.createReadStream(pathToRecording).pipe(
            errands.attachment.insert(body.id, 'recording.wav', null, 'audio/wav', { rev: body.rev })
        ).on('end', function () {
            callback(null, body);
        });
    });
};

exports.get = function (id, callback) {
    errands.get(id, function (err, body) {
        if (err) {
            return callback(err);
        }

        callback(null, body);
    });
};

exports.getAll = function (callback) {
    errands.list({include_docs: true}, function (err, result) {
        if (err) {
            callback(err);
        }

        callback(null, result);
    });
};

module.exports = exports;
<|endoftext|>


<commit_before>import {
    event as d3_event,
    select as d3_select
} from 'd3-selection';
import { dispatch as d3_dispatch } from 'd3-dispatch';

import { d3keybinding as d3_keybinding } from '../lib/d3.keybinding.js';

import { t, textDirection } from '../util/locale';
import { tooltip } from '../util/tooltip';

import { behaviorHash } from '../behavior';
import { modeBrowse } from '../modes';
import { services } from '../services';
import { svgDefs, svgIcon } from '../svg';
import { utilGetDimensions } from '../util/dimensions';
import { utilRebind } from '../util';

import { uiAccount } from './account';
import { uiAttribution } from './attribution';
import { uiBackground } from './background';
import { uiContributors } from './contributors';
import { uiFeatureInfo } from './feature_info';
import { uiFullScreen } from './full_screen';
import { uiGeolocate } from './geolocate';
import { uiHelp } from './help';
import { uiInfo } from './info';
import { uiIntro } from './intro';
import { uiLoading } from './loading';
import { uiMapData } from './map_data';
import { uiMapInMap } from './map_in_map';
import { uiModes } from './modes';
import { uiNotice } from './notice';
import { uiRestore } from './restore';
import { uiSave } from './save';
import { uiScale } from './scale';
import { uiShortcuts } from './shortcuts';
import { uiSidebar } from './sidebar';
import { uiSpinner } from './spinner';
import { uiSplash } from './splash';
import { uiStatus } from './status';
import { uiUndoRedo } from './undo_redo';
import { uiVersion } from './version';
import { uiZoom } from './zoom';
import { uiCmd } from './cmd';

function buildResizeListener(target, eventName, dispatch, options) {
    var resizeOnX = !!options.resizeOnX;
    var resizeOnY = !!options.resizeOnY;
    var startX;
    var startY;
    var startWidth;
    var startHeight;

    function startResize() {
        if (resizeOnX) {
            target.style('width', (startWidth + d3_event.clientX - startX) + 'px');
        }

        if (resizeOnY) {
            target.style('height', (startHeight + startY - d3_event.clientY) + 'px');
        }

        dispatch.call(eventName, target);
    }

    function stopResize() {
        d3_select(window)
            .on('.' + eventName, null);
    }

    return function initResize() {
        startX = d3_event.clientX;
        startY = d3_event.clientY;
        startWidth = target.node().getBoundingClientRect().width;
        startHeight = target.node().getBoundingClientRect().height;

        d3_select(window)
            .on('mousemove.' + eventName, startResize, false)
            .on('mouseup.' + eventName, stopResize, false);
    };
}

export function uiInit(context) {
    var uiInitCounter = 0;
    var dispatch = d3_dispatch('photoviewerResize');

    function render(container) {
        container
            .attr('dir', textDirection);

        var map = context.map();

        var hash = behaviorHash(context);
        hash();

        if (!hash.hadHash) {
            map.centerZoom([0, 0], 2);
        }

        container
            .append('svg')
            .attr('id', 'defs')
            .call(svgDefs(context));

        container
            .append('div')
            .attr('id', 'sidebar')
            .attr('class', 'col4')
            .call(ui.sidebar);

        var content = container
            .append('div')
            .attr('id', 'content')
            .attr('class', 'active');

        var bar = content
            .append('div')
            .attr('id', 'bar')
            .attr('class', 'fillD');

        content
            .append('div')
            .attr('id', 'map')
            .attr('dir', 'ltr')
            .call(map);

        content
            .call(uiMapInMap(context))
            .call(uiInfo(context))
            .call(uiNotice(context));

        bar
            .append('div')
            .attr('class', 'spacer col4');

        var limiter = bar.append('div')
            .attr('class', 'limiter');

        limiter
            .append('div')
            .attr('class', 'button-wrap joined col3')
            .call(uiModes(context), limiter);

        limiter
            .append('div')
            .attr('class', 'button-wrap joined col1')
            .call(uiUndoRedo(context));

        limiter
            .append('div')
            .attr('class', 'button-wrap col1')
            .call(uiSave(context));

        bar
            .append('div')
            .attr('class', 'full-screen')
            .call(uiFullScreen(context));

        bar
            .append('div')
            .attr('class', 'spinner')
            .call(uiSpinner(context));

        var controls = bar
            .append('div')
            .attr('class', 'map-controls');

        controls
            .append('div')
            .attr('class', 'map-control zoombuttons')
            .call(uiZoom(context));

        controls
            .append('div')
            .attr('class', 'map-control geolocate-control')
            .call(uiGeolocate(context));

        controls
            .append('div')
            .attr('class', 'map-control background-control')
            .call(uiBackground(context));

        controls
            .append('div')
            .attr('class', 'map-control map-data-control')
            .call(uiMapData(context));

        controls
            .append('div')
            .attr('class', 'map-control help-control')
            .call(uiHelp(context));

        var about = content
            .append('div')
            .attr('id', 'about');

        about
            .append('div')
            .attr('id', 'attrib')
            .attr('dir', 'ltr')
            .call(uiAttribution(context));

        about
            .append('div')
            .attr('class', 'api-status')
            .call(uiStatus(context));

        var footer = about
            .append('div')
            .attr('id', 'footer')
            .attr('class', 'fillD');

        footer
            .append('div')
            .attr('id', 'flash-wrap')
            .attr('class', 'footer-hide');

        var footerWrap = footer
            .append('div')
            .attr('id', 'footer-wrap')
            .attr('class', 'footer-show');

        footerWrap
            .append('div')
            .attr('id', 'scale-block')
            .call(uiScale(context));

        var aboutList = footerWrap
            .append('div')
            .attr('id', 'info-block')
            .append('ul')
            .attr('id', 'about-list');

        if (!context.embed()) {
            aboutList
                .call(uiAccount(context));
        }

        aboutList
            .append('li')
            .attr('class', 'version')
            .call(uiVersion(context));

        var issueLinks = aboutList
            .append('li');

        issueLinks
            .append('a')
            .attr('target', '_blank')
            .attr('tabindex', -1)
            .attr('href', 'https://github.com/openstreetmap/iD/issues')
            .call(svgIcon('#iD-icon-bug', 'light'))
            .call(tooltip().title(t('report_a_bug')).placement('top'));

        issueLinks
            .append('a')
            .attr('target', '_blank')
            .attr('tabindex', -1)
            .attr('href', 'https://github.com/openstreetmap/iD/blob/master/CONTRIBUTING.md#translating')
            .call(svgIcon('#iD-icon-translate', 'light'))
            .call(tooltip().title(t('help_translate')).placement('top'));

        aboutList
            .append('li')
            .attr('class', 'feature-warning')
            .attr('tabindex', -1)
            .call(uiFeatureInfo(context));

        aboutList
            .append('li')
            .attr('class', 'user-list')
            .attr('tabindex', -1)
            .call(uiContributors(context));

        var photoviewer = content
            .append('div')
            .attr('id', 'photoviewer')
            .classed('al', true)       // 'al'=left,  'ar'=right
            .classed('hide', true);

        photoviewer
            .append('button')
            .attr('class', 'thumb-hide')
            .on('click', function () {
                if (services.streetside) { services.streetside.hideViewer(); }
                if (services.mapillary) { services.mapillary.hideViewer(); }
                if (services.openstreetcam) { services.openstreetcam.hideViewer(); }
            })
            .append('div')
            .call(svgIcon('#iD-icon-close'));

        photoviewer
            .append('button')
            .attr('class', 'resize-handle-xy')
            .on(
                'mousedown',
                buildResizeListener(photoviewer, 'photoviewerResize', dispatch, { resizeOnX: true, resizeOnY: true })
            );

        photoviewer
            .append('button')
            .attr('class', 'resize-handle-x')
            .on(
                'mousedown',
                buildResizeListener(photoviewer, 'photoviewerResize', dispatch, { resizeOnX: true })
            );

        photoviewer
            .append('button')
            .attr('class', 'resize-handle-y')
            .on(
                'mousedown',
                buildResizeListener(photoviewer, 'photoviewerResize', dispatch, { resizeOnY: true })
            );

        window.onbeforeunload = function() {
            return context.save();
        };

        window.onunload = function() {
            context.history().unlock();
        };

        var mapDimensions = map.dimensions();

        function onResize() {
            mapDimensions = utilGetDimensions(content, true);
            map.dimensions(mapDimensions);
        }

        d3_select(window)
            .on('resize.editor', onResize);

        onResize();

        function pan(d) {
            return function() {
                d3_event.preventDefault();
                context.pan(d, 100);
            };
        }

        // pan amount
        var pa = 80;

        var keybinding = d3_keybinding('main')
            .on('⌫', function() { d3_event.preventDefault(); })
            .on('←', pan([pa, 0]))
            .on('↑', pan([0, pa]))
            .on('→', pan([-pa, 0]))
            .on('↓', pan([0, -pa]))
            .on(['⇧←', uiCmd('⌘←')], pan([mapDimensions[0], 0]))
            .on(['⇧↑', uiCmd('⌘↑')], pan([0, mapDimensions[1]]))
            .on(['⇧→', uiCmd('⌘→')], pan([-mapDimensions[0], 0]))
            .on(['⇧↓', uiCmd('⌘↓')], pan([0, -mapDimensions[1]]));

        d3_select(document)
            .call(keybinding);

        context.enter(modeBrowse(context));

        if (!uiInitCounter++) {
            if (!hash.startWalkthrough) {
                context.container()
                    .call(uiSplash(context))
                    .call(uiRestore(context));
            }

            context.container()
                .call(uiShortcuts(context));
        }

        var osm = context.connection(),
            auth = uiLoading(context).message(t('loading_auth')).blocking(true);

        if (osm && auth) {
            osm
                .on('authLoading.ui', function() {
                    context.container()
                        .call(auth);
                })
                .on('authDone.ui', function() {
                    auth.close();
                });
        }

        uiInitCounter++;

        if (hash.startWalkthrough) {
            hash.startWalkthrough = false;
            context.container().call(uiIntro(context));
        }
    }

    var renderCallback;

    function ui(node, callback) {
        renderCallback = callback;
        var container = d3_select(node);
        context.container(container);
        context.loadLocale(function(err) {
            if (!err) {
                render(container);
            }
            if (callback) {
                callback(err);
            }
        });
    }

    ui.restart = function(arg) {
        context.locale(arg);
        context.loadLocale(function(err) {
            if (!err) {
                context.container().selectAll('*').remove();
                render(context.container());
                if (renderCallback) renderCallback();
            }
        });
    };

    ui.sidebar = uiSidebar(context);

    return utilRebind(ui, dispatch, 'on');
}
<commit_msg>Add minimum resize height/width<commit_after>import {
    event as d3_event,
    select as d3_select
} from 'd3-selection';
import { dispatch as d3_dispatch } from 'd3-dispatch';

import { d3keybinding as d3_keybinding } from '../lib/d3.keybinding.js';

import { t, textDirection } from '../util/locale';
import { tooltip } from '../util/tooltip';

import { behaviorHash } from '../behavior';
import { modeBrowse } from '../modes';
import { services } from '../services';
import { svgDefs, svgIcon } from '../svg';
import { utilGetDimensions } from '../util/dimensions';
import { utilRebind } from '../util';

import { uiAccount } from './account';
import { uiAttribution } from './attribution';
import { uiBackground } from './background';
import { uiContributors } from './contributors';
import { uiFeatureInfo } from './feature_info';
import { uiFullScreen } from './full_screen';
import { uiGeolocate } from './geolocate';
import { uiHelp } from './help';
import { uiInfo } from './info';
import { uiIntro } from './intro';
import { uiLoading } from './loading';
import { uiMapData } from './map_data';
import { uiMapInMap } from './map_in_map';
import { uiModes } from './modes';
import { uiNotice } from './notice';
import { uiRestore } from './restore';
import { uiSave } from './save';
import { uiScale } from './scale';
import { uiShortcuts } from './shortcuts';
import { uiSidebar } from './sidebar';
import { uiSpinner } from './spinner';
import { uiSplash } from './splash';
import { uiStatus } from './status';
import { uiUndoRedo } from './undo_redo';
import { uiVersion } from './version';
import { uiZoom } from './zoom';
import { uiCmd } from './cmd';

function buildResizeListener(target, eventName, dispatch, options) {
    var resizeOnX = !!options.resizeOnX;
    var resizeOnY = !!options.resizeOnY;
    var minHeight = options.minHeight || 240;
    var minWidth = options.minWidth || 320;
    var startX;
    var startY;
    var startWidth;
    var startHeight;

    function startResize() {
        if (resizeOnX) {
            var newWidth = Math.max(minWidth, startWidth + d3_event.clientX - startX);
            target.style('width', newWidth + 'px');
        }

        if (resizeOnY) {
            var newHeight = Math.max(minHeight, startHeight + startY - d3_event.clientY);
            target.style('height', newHeight + 'px');
        }

        dispatch.call(eventName, target);
    }

    function stopResize() {
        d3_select(window)
            .on('.' + eventName, null);
    }

    return function initResize() {
        startX = d3_event.clientX;
        startY = d3_event.clientY;
        startWidth = target.node().getBoundingClientRect().width;
        startHeight = target.node().getBoundingClientRect().height;

        d3_select(window)
            .on('mousemove.' + eventName, startResize, false)
            .on('mouseup.' + eventName, stopResize, false);
    };
}

export function uiInit(context) {
    var uiInitCounter = 0;
    var dispatch = d3_dispatch('photoviewerResize');

    function render(container) {
        container
            .attr('dir', textDirection);

        var map = context.map();

        var hash = behaviorHash(context);
        hash();

        if (!hash.hadHash) {
            map.centerZoom([0, 0], 2);
        }

        container
            .append('svg')
            .attr('id', 'defs')
            .call(svgDefs(context));

        container
            .append('div')
            .attr('id', 'sidebar')
            .attr('class', 'col4')
            .call(ui.sidebar);

        var content = container
            .append('div')
            .attr('id', 'content')
            .attr('class', 'active');

        var bar = content
            .append('div')
            .attr('id', 'bar')
            .attr('class', 'fillD');

        content
            .append('div')
            .attr('id', 'map')
            .attr('dir', 'ltr')
            .call(map);

        content
            .call(uiMapInMap(context))
            .call(uiInfo(context))
            .call(uiNotice(context));

        bar
            .append('div')
            .attr('class', 'spacer col4');

        var limiter = bar.append('div')
            .attr('class', 'limiter');

        limiter
            .append('div')
            .attr('class', 'button-wrap joined col3')
            .call(uiModes(context), limiter);

        limiter
            .append('div')
            .attr('class', 'button-wrap joined col1')
            .call(uiUndoRedo(context));

        limiter
            .append('div')
            .attr('class', 'button-wrap col1')
            .call(uiSave(context));

        bar
            .append('div')
            .attr('class', 'full-screen')
            .call(uiFullScreen(context));

        bar
            .append('div')
            .attr('class', 'spinner')
            .call(uiSpinner(context));

        var controls = bar
            .append('div')
            .attr('class', 'map-controls');

        controls
            .append('div')
            .attr('class', 'map-control zoombuttons')
            .call(uiZoom(context));

        controls
            .append('div')
            .attr('class', 'map-control geolocate-control')
            .call(uiGeolocate(context));

        controls
            .append('div')
            .attr('class', 'map-control background-control')
            .call(uiBackground(context));

        controls
            .append('div')
            .attr('class', 'map-control map-data-control')
            .call(uiMapData(context));

        controls
            .append('div')
            .attr('class', 'map-control help-control')
            .call(uiHelp(context));

        var about = content
            .append('div')
            .attr('id', 'about');

        about
            .append('div')
            .attr('id', 'attrib')
            .attr('dir', 'ltr')
            .call(uiAttribution(context));

        about
            .append('div')
            .attr('class', 'api-status')
            .call(uiStatus(context));

        var footer = about
            .append('div')
            .attr('id', 'footer')
            .attr('class', 'fillD');

        footer
            .append('div')
            .attr('id', 'flash-wrap')
            .attr('class', 'footer-hide');

        var footerWrap = footer
            .append('div')
            .attr('id', 'footer-wrap')
            .attr('class', 'footer-show');

        footerWrap
            .append('div')
            .attr('id', 'scale-block')
            .call(uiScale(context));

        var aboutList = footerWrap
            .append('div')
            .attr('id', 'info-block')
            .append('ul')
            .attr('id', 'about-list');

        if (!context.embed()) {
            aboutList
                .call(uiAccount(context));
        }

        aboutList
            .append('li')
            .attr('class', 'version')
            .call(uiVersion(context));

        var issueLinks = aboutList
            .append('li');

        issueLinks
            .append('a')
            .attr('target', '_blank')
            .attr('tabindex', -1)
            .attr('href', 'https://github.com/openstreetmap/iD/issues')
            .call(svgIcon('#iD-icon-bug', 'light'))
            .call(tooltip().title(t('report_a_bug')).placement('top'));

        issueLinks
            .append('a')
            .attr('target', '_blank')
            .attr('tabindex', -1)
            .attr('href', 'https://github.com/openstreetmap/iD/blob/master/CONTRIBUTING.md#translating')
            .call(svgIcon('#iD-icon-translate', 'light'))
            .call(tooltip().title(t('help_translate')).placement('top'));

        aboutList
            .append('li')
            .attr('class', 'feature-warning')
            .attr('tabindex', -1)
            .call(uiFeatureInfo(context));

        aboutList
            .append('li')
            .attr('class', 'user-list')
            .attr('tabindex', -1)
            .call(uiContributors(context));

        var photoviewer = content
            .append('div')
            .attr('id', 'photoviewer')
            .classed('al', true)       // 'al'=left,  'ar'=right
            .classed('hide', true);

        photoviewer
            .append('button')
            .attr('class', 'thumb-hide')
            .on('click', function () {
                if (services.streetside) { services.streetside.hideViewer(); }
                if (services.mapillary) { services.mapillary.hideViewer(); }
                if (services.openstreetcam) { services.openstreetcam.hideViewer(); }
            })
            .append('div')
            .call(svgIcon('#iD-icon-close'));

        photoviewer
            .append('button')
            .attr('class', 'resize-handle-xy')
            .on(
                'mousedown',
                buildResizeListener(photoviewer, 'photoviewerResize', dispatch, { resizeOnX: true, resizeOnY: true })
            );

        photoviewer
            .append('button')
            .attr('class', 'resize-handle-x')
            .on(
                'mousedown',
                buildResizeListener(photoviewer, 'photoviewerResize', dispatch, { resizeOnX: true })
            );

        photoviewer
            .append('button')
            .attr('class', 'resize-handle-y')
            .on(
                'mousedown',
                buildResizeListener(photoviewer, 'photoviewerResize', dispatch, { resizeOnY: true })
            );

        window.onbeforeunload = function() {
            return context.save();
        };

        window.onunload = function() {
            context.history().unlock();
        };

        var mapDimensions = map.dimensions();

        function onResize() {
            mapDimensions = utilGetDimensions(content, true);
            map.dimensions(mapDimensions);
        }

        d3_select(window)
            .on('resize.editor', onResize);

        onResize();

        function pan(d) {
            return function() {
                d3_event.preventDefault();
                context.pan(d, 100);
            };
        }

        // pan amount
        var pa = 80;

        var keybinding = d3_keybinding('main')
            .on('⌫', function() { d3_event.preventDefault(); })
            .on('←', pan([pa, 0]))
            .on('↑', pan([0, pa]))
            .on('→', pan([-pa, 0]))
            .on('↓', pan([0, -pa]))
            .on(['⇧←', uiCmd('⌘←')], pan([mapDimensions[0], 0]))
            .on(['⇧↑', uiCmd('⌘↑')], pan([0, mapDimensions[1]]))
            .on(['⇧→', uiCmd('⌘→')], pan([-mapDimensions[0], 0]))
            .on(['⇧↓', uiCmd('⌘↓')], pan([0, -mapDimensions[1]]));

        d3_select(document)
            .call(keybinding);

        context.enter(modeBrowse(context));

        if (!uiInitCounter++) {
            if (!hash.startWalkthrough) {
                context.container()
                    .call(uiSplash(context))
                    .call(uiRestore(context));
            }

            context.container()
                .call(uiShortcuts(context));
        }

        var osm = context.connection(),
            auth = uiLoading(context).message(t('loading_auth')).blocking(true);

        if (osm && auth) {
            osm
                .on('authLoading.ui', function() {
                    context.container()
                        .call(auth);
                })
                .on('authDone.ui', function() {
                    auth.close();
                });
        }

        uiInitCounter++;

        if (hash.startWalkthrough) {
            hash.startWalkthrough = false;
            context.container().call(uiIntro(context));
        }
    }

    var renderCallback;

    function ui(node, callback) {
        renderCallback = callback;
        var container = d3_select(node);
        context.container(container);
        context.loadLocale(function(err) {
            if (!err) {
                render(container);
            }
            if (callback) {
                callback(err);
            }
        });
    }

    ui.restart = function(arg) {
        context.locale(arg);
        context.loadLocale(function(err) {
            if (!err) {
                context.container().selectAll('*').remove();
                render(context.container());
                if (renderCallback) renderCallback();
            }
        });
    };

    ui.sidebar = uiSidebar(context);

    return utilRebind(ui, dispatch, 'on');
}
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) 2010 M-Way Solutions GmbH. All rights reserved.
// Creator:   Sebastian
// Date:      02.11.2010
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

/**
 * @class
 *
 * M.PageView is the prototype of any page. It is the seconds 'highest' view, right after
 * M.Application. A page is the container view for all other views.
 *
 * @extends M.View
 */
M.PageView = M.View.extend(
/** @scope M.PageView.prototype */ {

    /**
     * The type of this object.
     *
     * @type String
     */
    type: 'M.PageView',

    /**
     * States whether a page is loaded the first time or not. It is automatically set to NO
     * once the page was first loaded.
     *
     * @type Boolean
     */
    isFirstLoad: YES,

    /**
     * This property can be used to set the page's beforeLoad action.
     *
     * @type Object
     */
    beforeLoad: null,

    /**
     * This property can be used to set the page's onLoad action.
     *
     * @type Object
     */
    onLoad: null,

    /**
     * This property can be used to set the page's beforeHide action.
     *
     * @type Object
     */
    beforeHide: null,

    /**
     * This property can be used to set the page's onHide action.
     *
     * @type Object
     */
    onHide: null,

    /**
     * This property can be used to set the page's onOrientationChange action.
     *
     * @type Object
     */
    onOrientationChange: null,

    /**
     * Indicates whether the page has a tab bar or not.
     *
     * @type Boolean
     */
    hasTabBarView: NO,

    /**
     * The page's tab bar.
     *
     * @type M.TabBarView
     */
    tabBarView: null,

    /**
     * Renders in three steps:
     * 1. Rendering Opening div tag with corresponding data-role
     * 2. Triggering render process of child views
     * 3. Rendering closing tag
     *
     * @private
     * @returns {String} The page view's html representation.
     */
    render: function() {
        this.html += '
';

        this.renderChildViews();

        this.html += '
';

        this.writeToDOM();
        this.theme();
    },

    /**
     * This method writes the view's html string into the DOM. M.Page is the only view that does
     * that. All other views just deliver their html representation to a page view.
     */
    writeToDOM: function() {
        document.write(this.html);
    },

    /**
     * This method is called right before the page is loaded. If a beforeLoad-action is defined
     * for the page, it is now called.
     */
    pageWillLoad: function() {
        /* if this is the first page to be loaded, check if there is a tab bar and an active tab
           specified and switch to this tab. also reload this page to have a stable location hash. */
        if(M.Application.isFirstLoad) {
            M.Application.isFirstLoad = NO;
            var currentPage = M.ViewManager.getCurrentPage();
            if(currentPage && currentPage.hasTabBarView) {
                var tabBarView = currentPage.tabBarView;
                var activePage = M.ViewManager.getPage(tabBarView.activeTab.page);
                if(activePage !== currentPage) {
                    M.Controller.switchToPage(tabBarView.activeTab.page, M.TRANSITION.NONE, NO, YES);
                }
            }
        }

        /* initialize the loader for later use (if not already done) */
        if(M.LoaderView) {
            M.LoaderView.initialize();
        }

        if(this.beforeLoad) {
            this.beforeLoad.target[this.beforeLoad.action](this.isFirstLoad);
        }
    },

    /**
     * This method is called right after the page was loaded. If a onLoad-action is defined
     * for the page, it is now called.
     */
    pageDidLoad: function() {
        if(this.onLoad) {
            this.onLoad.target[this.onLoad.action](this.isFirstLoad);
        }

        /* if there is a list on the page, reset it: deactivate possible active list items */
        $('#' + this.id).find('.ui-btn-active').each(function() {
            if(M.ViewManager.getViewById($(this).attr('id')) && M.ViewManager.getViewById($(this).attr('id')).type === 'M.ListItemView') {
                var listItem = M.ViewManager.getViewById($(this).attr('id'));
                listItem.removeCssClass('ui-btn-active');
            }
        });

        this.isFirstLoad = NO;
    },

    /**
     * This method is called right before the page is hidden. If a beforeHide-action is defined
     * for the page, it is now called.
     */
    pageWillHide: function() {
        if(this.beforeHide) {
            this.beforeHide.target[this.beforeHide.action]();
        }
    },

    /**
     * This method is called right after the page was hidden. If a onHide-action is defined
     * for the page, it is now called.
     */
    pageDidHide: function() {
        if(this.onHide) {
            this.onHide.target[this.onHide.action]();
        }
    },

    /**
     * This method is called if the device's orientation changed.
     */
    orientationDidChange: function() {
        if(this.onOrientationChange) {
            this.onOrientationChange.target[this.onOrientationChange.action](M.Environment.getOrientation());
        }
    },

    /**
     * Triggers the rendering engine, jQuery mobile, to style the page and call the theme() of
     * its child views.
     *
     * @private
     */
    theme: function() {
        $('#' + this.id).page();
        this.themeChildViews();
    },

    /**
     * Applies some style-attributes to the page.
     *
     * @private
     * @returns {String} The page's styling as html representation.
     */
    style: function() {
        var html = '';
        if(this.cssClass) {
            if(!html) {
                html += ' class="';
            }
            html += this.cssClass;
        }
        if(html) {
            html += '"';
        }
        return html;
    }

});<commit_msg>fix: page events can only be called once a second (this solves startup problems with new bootstrapping script)<commit_after>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) 2010 M-Way Solutions GmbH. All rights reserved.
// Creator:   Sebastian
// Date:      02.11.2010
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

/**
 * @class
 *
 * M.PageView is the prototype of any page. It is the seconds 'highest' view, right after
 * M.Application. A page is the container view for all other views.
 *
 * @extends M.View
 */
M.PageView = M.View.extend(
/** @scope M.PageView.prototype */ {

    /**
     * The type of this object.
     *
     * @type String
     */
    type: 'M.PageView',

    /**
     * States whether a page is loaded the first time or not. It is automatically set to NO
     * once the page was first loaded.
     *
     * @type Boolean
     */
    isFirstLoad: YES,

    /**
     * This property can be used to set the page's beforeLoad action.
     *
     * @type Object
     */
    beforeLoad: null,

    /**
     * This property can be used to set the page's onLoad action.
     *
     * @type Object
     */
    onLoad: null,

    /**
     * This property can be used to set the page's beforeHide action.
     *
     * @type Object
     */
    beforeHide: null,

    /**
     * This property can be used to set the page's onHide action.
     *
     * @type Object
     */
    onHide: null,

    /**
     * This property can be used to set the page's onOrientationChange action.
     *
     * @type Object
     */
    onOrientationChange: null,

    /**
     * Indicates whether the page has a tab bar or not.
     *
     * @type Boolean
     */
    hasTabBarView: NO,

    /**
     * The page's tab bar.
     *
     * @type M.TabBarView
     */
    tabBarView: null,

    lastPageWillLoad: null,

    lastPageDidLoad: null,

    lastPageWillHide: null,

    lastPageDidHide: null,

    /**
     * Renders in three steps:
     * 1. Rendering Opening div tag with corresponding data-role
     * 2. Triggering render process of child views
     * 3. Rendering closing tag
     *
     * @private
     * @returns {String} The page view's html representation.
     */
    render: function() {
        this.html += '
';

        this.renderChildViews();

        this.html += '
';

        this.writeToDOM();
        this.theme();
    },

    /**
     * This method writes the view's html string into the DOM. M.Page is the only view that does
     * that. All other views just deliver their html representation to a page view.
     */
    writeToDOM: function() {
        document.write(this.html);
    },

    /**
     * This method is called right before the page is loaded. If a beforeLoad-action is defined
     * for the page, it is now called.
     */
    pageWillLoad: function() {
        if(this.lastPageWillLoad && this.lastPageWillLoad.timeBetween(M.Date.now()) < 1000) {
            return;
        }
        this.lastPageWillLoad = M.Date.now();
        /* if this is the first page to be loaded, check if there is a tab bar and an active tab
           specified and switch to this tab. also reload this page to have a stable location hash. */
        if(M.Application.isFirstLoad) {
            M.Application.isFirstLoad = NO;
            var currentPage = M.ViewManager.getCurrentPage();
            if(currentPage && currentPage.hasTabBarView) {
                var tabBarView = currentPage.tabBarView;
                var activePage = M.ViewManager.getPage(tabBarView.activeTab.page);
                if(activePage !== currentPage) {
                    M.Controller.switchToPage(tabBarView.activeTab.page, M.TRANSITION.NONE, NO, YES);
                }
            }
        }

        /* initialize the loader for later use (if not already done) */
        if(M.LoaderView) {
            M.LoaderView.initialize();
        }

        if(this.beforeLoad) {
            this.beforeLoad.target[this.beforeLoad.action](this.isFirstLoad);
        }
    },

    /**
     * This method is called right after the page was loaded. If a onLoad-action is defined
     * for the page, it is now called.
     */
    pageDidLoad: function() {
        if(this.lastPageDidLoad && this.lastPageDidLoad.timeBetween(M.Date.now()) < 1000) {
            return;
        }
        this.lastPageDidLoad = M.Date.now();
        if(this.onLoad) {
            this.onLoad.target[this.onLoad.action](this.isFirstLoad);
        }

        /* if there is a list on the page, reset it: deactivate possible active list items */
        $('#' + this.id).find('.ui-btn-active').each(function() {
            if(M.ViewManager.getViewById($(this).attr('id')) && M.ViewManager.getViewById($(this).attr('id')).type === 'M.ListItemView') {
                var listItem = M.ViewManager.getViewById($(this).attr('id'));
                listItem.removeCssClass('ui-btn-active');
            }
        });

        this.isFirstLoad = NO;
    },

    /**
     * This method is called right before the page is hidden. If a beforeHide-action is defined
     * for the page, it is now called.
     */
    pageWillHide: function() {
        if(this.lastPageWillHide && this.lastPageWillHide.timeBetween(M.Date.now()) < 1000) {
            return;
        }
        this.lastPageWillHide = M.Date.now();
        if(this.beforeHide) {
            this.beforeHide.target[this.beforeHide.action]();
        }
    },

    /**
     * This method is called right after the page was hidden. If a onHide-action is defined
     * for the page, it is now called.
     */
    pageDidHide: function() {
        if(this.lastPageDidHide && this.lastPageDidHide.timeBetween(M.Date.now()) < 1000) {
            return;
        }
        this.lastPageDidHide = M.Date.now();
        if(this.onHide) {
            this.onHide.target[this.onHide.action]();
        }
    },

    /**
     * This method is called if the device's orientation changed.
     */
    orientationDidChange: function() {
        if(this.onOrientationChange) {
            this.onOrientationChange.target[this.onOrientationChange.action](M.Environment.getOrientation());
        }
    },

    /**
     * Triggers the rendering engine, jQuery mobile, to style the page and call the theme() of
     * its child views.
     *
     * @private
     */
    theme: function() {
        $('#' + this.id).page();
        this.themeChildViews();
    },

    /**
     * Applies some style-attributes to the page.
     *
     * @private
     * @returns {String} The page's styling as html representation.
     */
    style: function() {
        var html = '';
        if(this.cssClass) {
            if(!html) {
                html += ' class="';
            }
            html += this.cssClass;
        }
        if(html) {
            html += '"';
        }
        return html;
    }

});<|endoftext|>


<commit_before>// Prints results of each kartlib call with test data
var kartlib = require('../lib/kartlib.js');

function f1() {
    console.log('kartlib.findRacerIdByName("F4$T3R_486")');
    kartlib.findRacerIdByName('F4$T3R_486', function(id) {
        console.log(id);
        console.log('');
        f2();
    });
}

function f2() {
    console.log('kartlib.findRacerIdByEmail("everettcaleb95@gmail.com")');
    kartlib.findRacerIdByEmail('everettcaleb95@gmail.com', function(id) {
        console.log(id);
        console.log('');
        f3();
    });
}

function f3() {
    console.log('kartlib.getRacerHistoryById(2103578)');
    kartlib.getRacerHistoryById(2103578, function(data) {
        console.log(data);
    });
}

f1();
<commit_msg>More retrieval stuff, updated README, new data storage module<commit_after>// Prints results of each kartlib call with test data
var kartlib = require('../lib/kartlib.js'),
    kls = require('../lib/kartlib-storage.js');

function f1() {
    console.log('kartlib.findRacerIdByName("F4$T3R_486")');
    kartlib.findRacerIdByName('F4$T3R_486', function(id) {
        console.log(id);
        console.log('');
        f2();
    });
}

function f2() {
    console.log('kartlib.findRacerIdByEmail("everettcaleb95@gmail.com")');
    kartlib.findRacerIdByEmail('everettcaleb95@gmail.com', function(id) {
        console.log(id);
        console.log('');
        f3();
    });
}

function f3() {
    console.log('kartlib.getRacerHistoryById(2103578)');
    kartlib.getRacerHistoryById(2103578, function(data) {
        console.log(JSON.stringify(data));
        console.log('');
        f4();
    });
}

function f4() {
    console.log('kartlib.getHeatDetailsById(72964)');
    kartlib.getHeatDetailsById(72964, function(data) {
        console.log(JSON.stringify(data));
        f5();
    });
}

function f5() {
    console.log('storage csv');
    kartlib.getRacerHistoryById(2103578, function(data) {
        kls.insertRacerHistory(data);
        var csv = kls.getDataAsCsv();
        console.log(csv.racers);
        console.log('');
        console.log(csv.heats);
        console.log('');
        console.log(csv.heatRacers);
    });
}

f5();
<|endoftext|>