<commit_before>/**
 * @author Ryan Johnson <http://syntacticx.com/>
 * @copyright 2008 PersonalGrid Corporation <http://personalgrid.com/>
 * @package LivePipe UI
 * @license MIT
 * @url http://livepipe.net/core
 * @require prototype.js
 */

if(typeof(Control) == 'undefined')
	Control = {};

var $proc = function(proc){
	return typeof(proc) == 'function' ? proc : function(){return proc};
};

var $value = function(value){
	return typeof(value) == 'function' ? value() : value;
};

Object.Event = {
	extend: function(object){
		object._objectEventSetup = function(event_name){
			this._observers = this._observers || {};
			this._observers[event_name] = this._observers[event_name] || [];
		};
		object.observe = function(event_name,observer){
			if(typeof(event_name) == 'string' && typeof(observer) != 'undefined'){
				this._objectEventSetup(event_name);
				if(!this._observers[event_name].include(observer))
					this._observers[event_name].push(observer);
			}else
				for(var e in event_name)
					this.observe(e,event_name[e]);
		};
		object.stopObserving = function(event_name,observer){
			this._objectEventSetup(event_name);
			if(event_name && observer)
				this._observers[event_name] = this._observers[event_name].without(observer);
			else if(event_name)
				this._observers[event_name] = [];
			else
				this._observers = {};
		};
		object.observeOnce = function(event_name,outer_observer){
			var inner_observer = function(){
				outer_observer.apply(this,arguments);
				this.stopObserving(event_name,inner_observer);
			}.bind(this);
			this._objectEventSetup(event_name);
			this._observers[event_name].push(inner_observer);
		};
		object.notify = function(event_name){
			this._objectEventSetup(event_name);
			var collected_return_values = [];
			var args = $A(arguments).slice(1);
			try{
				for(var i = 0; i < this._observers[event_name].length; ++i)
					collected_return_values.push(this._observers[event_name][i].apply(this._observers[event_name][i],args) || null);
			}catch(e){
				if(e == $break)
					return false;
				else
					throw e;
			}
			return collected_return_values;
		};
		if(object.prototype){
			object.prototype._objectEventSetup = object._objectEventSetup;
			object.prototype.observe = object.observe;
			object.prototype.stopObserving = object.stopObserving;
			object.prototype.observeOnce = object.observeOnce;
			object.prototype.notify = function(event_name){
				if(object.notify){
					var args = $A(arguments).slice(1);
					args.unshift(this);
					args.unshift(event_name);
					object.notify.apply(object,args);
				}
				this._objectEventSetup(event_name);
				var args = $A(arguments).slice(1);
				var collected_return_values = [];
				try{
					if(this.options && this.options[event_name] && typeof(this.options[event_name]) == 'function')
						collected_return_values.push(this.options[event_name].apply(this,args) || null);
					for(var i = 0; i < this._observers[event_name].length; ++i)
						collected_return_values.push(this._observers[event_name][i].apply(this._observers[event_name][i],args) || null);
				}catch(e){
					if(e == $break)
						return false;
					else
						throw e;
				}
				return collected_return_values;
			};
		}
	}
};

/* Begin Core Extensions */

//Element.observeOnce
Element.addMethods({
	observeOnce: function(element,event_name,outer_callback){
		var inner_callback = function(){
			outer_callback.apply(this,arguments);
			Element.stopObserving(element,event_name,inner_callback);
		};
		Element.observe(element,event_name,inner_callback);
	}
});

//mouseenter, mouseleave
//from http://dev.rubyonrails.org/attachment/ticket/8354/event_mouseenter_106rc1.patch
Object.extend(Event, (function() {
	var cache = Event.cache;

	function getEventID(element) {
		if (element._prototypeEventID) return element._prototypeEventID[0];
		arguments.callee.id = arguments.callee.id || 1;
		return element._prototypeEventID = [++arguments.callee.id];
	}

	function getDOMEventName(eventName) {
		if (eventName && eventName.include(':')) return "dataavailable";
		//begin extension
		if(!Prototype.Browser.IE){
			eventName = {
				mouseenter: 'mouseover',
				mouseleave: 'mouseout'
			}[eventName] || eventName;
		}
		//end extension
		return eventName;
	}

	function getCacheForID(id) {
		return cache[id] = cache[id] || { };
	}

	function getWrappersForEventName(id, eventName) {
		var c = getCacheForID(id);
		return c[eventName] = c[eventName] || [];
	}

	function createWrapper(element, eventName, handler) {
		var id = getEventID(element);
		var c = getWrappersForEventName(id, eventName);
		if (c.pluck("handler").include(handler)) return false;

		var wrapper = function(event) {
			if (!Event || !Event.extend ||
				(event.eventName && event.eventName != eventName))
					return false;

			Event.extend(event);
			handler.call(element, event);
		};

		//begin extension
		if(!(Prototype.Browser.IE) && ['mouseenter','mouseleave'].include(eventName)){
			wrapper = wrapper.wrap(function(proceed,event) {
				var rel = event.relatedTarget;
				var cur = event.currentTarget;
				if(rel && rel.nodeType == Node.TEXT_NODE)
					rel = rel.parentNode;
				if(rel && rel != cur && !rel.descendantOf(cur))
					return proceed(event);
			});
		}
		//end extension

		wrapper.handler = handler;
		c.push(wrapper);
		return wrapper;
	}

	function findWrapper(id, eventName, handler) {
		var c = getWrappersForEventName(id, eventName);
		return c.find(function(wrapper) { return wrapper.handler == handler });
	}

	function destroyWrapper(id, eventName, handler) {
		var c = getCacheForID(id);
		if (!c[eventName]) return false;
		c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
	}

	function destroyCache() {
		for (var id in cache)
			for (var eventName in cache[id])
				cache[id][eventName] = null;
	}

	if (window.attachEvent) {
		window.attachEvent("onunload", destroyCache);
	}

	return {
		observe: function(element, eventName, handler) {
			element = $(element);
			var name = getDOMEventName(eventName);

			var wrapper = createWrapper(element, eventName, handler);
			if (!wrapper) return element;

			if (element.addEventListener) {
				element.addEventListener(name, wrapper, false);
			} else {
				element.attachEvent("on" + name, wrapper);
			}

			return element;
		},

		stopObserving: function(element, eventName, handler) {
			element = $(element);
			var id = getEventID(element), name = getDOMEventName(eventName);

			if (!handler && eventName) {
				getWrappersForEventName(id, eventName).each(function(wrapper) {
					element.stopObserving(eventName, wrapper.handler);
				});
				return element;

			} else if (!eventName) {
				Object.keys(getCacheForID(id)).each(function(eventName) {
					element.stopObserving(eventName);
				});
				return element;
			}

			var wrapper = findWrapper(id, eventName, handler);
			if (!wrapper) return element;

			if (element.removeEventListener) {
				element.removeEventListener(name, wrapper, false);
			} else {
				element.detachEvent("on" + name, wrapper);
			}

			destroyWrapper(id, eventName, handler);

			return element;
		},

		fire: function(element, eventName, memo) {
			element = $(element);
			if (element == document && document.createEvent && !element.dispatchEvent)
				element = document.documentElement;

			var event;
			if (document.createEvent) {
				event = document.createEvent("HTMLEvents");
				event.initEvent("dataavailable", true, true);
			} else {
				event = document.createEventObject();
				event.eventType = "ondataavailable";
			}

			event.eventName = eventName;
			event.memo = memo || { };

			if (document.createEvent) {
				element.dispatchEvent(event);
			} else {
				element.fireEvent(event.eventType, event);
			}

			return Event.extend(event);
		}
	};
})());

Object.extend(Event, Event.Methods);

Element.addMethods({
	fire:			Event.fire,
	observe:		Event.observe,
	stopObserving:	Event.stopObserving
});

Object.extend(document, {
	fire:			Element.Methods.fire.methodize(),
	observe:		Element.Methods.observe.methodize(),
	stopObserving:	Element.Methods.stopObserving.methodize()
});

//mouse:wheel
(function(){
	function wheel(event){
		var delta;
		// normalize the delta
		if(event.wheelDelta) // IE & Opera
			delta = event.wheelDelta / 120;
		else if (event.detail) // W3C
			delta =- event.detail / 3;
		if(!delta)
			return;
		var custom_event = event.element().fire('mouse:wheel',{
			delta: delta
		});
		if(custom_event.stopped){
			event.stop();
			return false;
		}
	}
	document.observe('mousewheel',wheel);
	document.observe('DOMMouseScroll',wheel);
})();

/* End Core Extensions */

//from PrototypeUI
var IframeShim = Class.create({
	initialize: function() {
		this.element = new Element('iframe',{
			style: 'position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);display:none',
			src: 'javascript:void(0);',
			frameborder: 0
		});
		$(document.body).insert(this.element);
	},
	hide: function() {
		this.element.hide();
		return this;
	},
	show: function() {
		this.element.show();
		return this;
	},
	positionUnder: function(element) {
		var element = $(element);
		var offset = element.cumulativeOffset();
		var dimensions = element.getDimensions();
		this.element.setStyle({
			left: offset[0] + 'px',
			top: offset[1] + 'px',
			width: dimensions.width + 'px',
			height: dimensions.height + 'px',
			zIndex: element.getStyle('zIndex') - 1
		}).show();
		return this;
	},
	setBounds: function(bounds) {
		for(prop in bounds)
			bounds[prop] += 'px';
		this.element.setStyle(bounds);
		return this;
	},
	destroy: function() {
		if(this.element)
			this.element.remove();
		return this;
	}
});<commit_msg>Updated livepipe. This will require testing to ensure this didn't break anything for you. My testing shows that it appears to work fine where it is used in refinery.<commit_after>/**
 * @author Ryan Johnson <http://syntacticx.com/>
 * @copyright 2008 PersonalGrid Corporation <http://personalgrid.com/>
 * @package LivePipe UI
 * @license MIT
 * @url http://livepipe.net/core
 * @require prototype.js
 */

if(typeof(Control) == 'undefined')
    Control = {};

var $proc = function(proc){
    return typeof(proc) == 'function' ? proc : function(){return proc};
};

var $value = function(value){
    return typeof(value) == 'function' ? value() : value;
};

Object.Event = {
    extend: function(object){
        object._objectEventSetup = function(event_name){
            this._observers = this._observers || {};
            this._observers[event_name] = this._observers[event_name] || [];
        };
        object.observe = function(event_name,observer){
            if(typeof(event_name) == 'string' && typeof(observer) != 'undefined'){
                this._objectEventSetup(event_name);
                if(!this._observers[event_name].include(observer))
                    this._observers[event_name].push(observer);
            }else
                for(var e in event_name)
                    this.observe(e,event_name[e]);
        };
        object.stopObserving = function(event_name,observer){
            this._objectEventSetup(event_name);
            if(event_name && observer)
                this._observers[event_name] = this._observers[event_name].without(observer);
            else if(event_name)
                this._observers[event_name] = [];
            else
                this._observers = {};
        };
        object.observeOnce = function(event_name,outer_observer){
            var inner_observer = function(){
                outer_observer.apply(this,arguments);
                this.stopObserving(event_name,inner_observer);
            }.bind(this);
            this._objectEventSetup(event_name);
            this._observers[event_name].push(inner_observer);
        };
        object.notify = function(event_name){
            this._objectEventSetup(event_name);
            var collected_return_values = [];
            var args = $A(arguments).slice(1);
            try{
                for(var i = 0; i < this._observers[event_name].length; ++i)
                    collected_return_values.push(this._observers[event_name][i].apply(this._observers[event_name][i],args) || null);
            }catch(e){
                if(e == $break)
                    return false;
                else
                    throw e;
            }
            return collected_return_values;
        };
        if(object.prototype){
            object.prototype._objectEventSetup = object._objectEventSetup;
            object.prototype.observe = object.observe;
            object.prototype.stopObserving = object.stopObserving;
            object.prototype.observeOnce = object.observeOnce;
            object.prototype.notify = function(event_name){
                if(object.notify){
                    var args = $A(arguments).slice(1);
                    args.unshift(this);
                    args.unshift(event_name);
                    object.notify.apply(object,args);
                }
                this._objectEventSetup(event_name);
                var args = $A(arguments).slice(1);
                var collected_return_values = [];
                try{
                    if(this.options && this.options[event_name] && typeof(this.options[event_name]) == 'function')
                        collected_return_values.push(this.options[event_name].apply(this,args) || null);
                    for(var i = 0; i < this._observers[event_name].length; ++i)
                        collected_return_values.push(this._observers[event_name][i].apply(this._observers[event_name][i],args) || null);
                }catch(e){
                    if(e == $break)
                        return false;
                    else
                        throw e;
                }
                return collected_return_values;
            };
        }
    }
};

/* Begin Core Extensions */

//Element.observeOnce
Element.addMethods({
    observeOnce: function(element,event_name,outer_callback){
        var inner_callback = function(){
            outer_callback.apply(this,arguments);
            Element.stopObserving(element,event_name,inner_callback);
        };
        Element.observe(element,event_name,inner_callback);
    }
});

//mouseenter, mouseleave
//from http://dev.rubyonrails.org/attachment/ticket/8354/event_mouseenter_106rc1.patch
Object.extend(Event, (function() {
    var cache = Event.cache;

    function getEventID(element) {
        if (element._prototypeEventID) return element._prototypeEventID[0];
        arguments.callee.id = arguments.callee.id || 1;
        return element._prototypeEventID = [++arguments.callee.id];
    }

    function getDOMEventName(eventName) {
        if (eventName && eventName.include(':')) return "dataavailable";
        //begin extension
        if(!Prototype.Browser.IE){
            eventName = {
                mouseenter: 'mouseover',
                mouseleave: 'mouseout'
            }[eventName] || eventName;
        }
        //end extension
        return eventName;
    }

    function getCacheForID(id) {
        return cache[id] = cache[id] || { };
    }

    function getWrappersForEventName(id, eventName) {
        var c = getCacheForID(id);
        return c[eventName] = c[eventName] || [];
    }

    function createWrapper(element, eventName, handler) {
        var id = getEventID(element);
        var c = getWrappersForEventName(id, eventName);
        if (c.pluck("handler").include(handler)) return false;

        var wrapper = function(event) {
            if (!Event || !Event.extend ||
                (event.eventName && event.eventName != eventName))
                    return false;

            Event.extend(event);
            handler.call(element, event);
        };

        //begin extension
        if(!(Prototype.Browser.IE) && ['mouseenter','mouseleave'].include(eventName)){
            wrapper = wrapper.wrap(function(proceed,event) {
                var rel = event.relatedTarget;
                var cur = event.currentTarget;
                if(rel && rel.nodeType == Node.TEXT_NODE)
                    rel = rel.parentNode;
                if(rel && rel != cur && !rel.descendantOf(cur))
                    return proceed(event);
            });
        }
        //end extension

        wrapper.handler = handler;
        c.push(wrapper);
        return wrapper;
    }

    function findWrapper(id, eventName, handler) {
        var c = getWrappersForEventName(id, eventName);
        return c.find(function(wrapper) { return wrapper.handler == handler });
    }

    function destroyWrapper(id, eventName, handler) {
        var c = getCacheForID(id);
        if (!c[eventName]) return false;
        c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
    }

    function destroyCache() {
        for (var id in cache)
            for (var eventName in cache[id])
                cache[id][eventName] = null;
    }

    if (window.attachEvent) {
        window.attachEvent("onunload", destroyCache);
    }

    return {
        observe: function(element, eventName, handler) {
            element = $(element);
            var name = getDOMEventName(eventName);

            var wrapper = createWrapper(element, eventName, handler);
            if (!wrapper) return element;

            if (element.addEventListener) {
                element.addEventListener(name, wrapper, false);
            } else {
                element.attachEvent("on" + name, wrapper);
            }

            return element;
        },

        stopObserving: function(element, eventName, handler) {
            element = $(element);
            var id = getEventID(element), name = getDOMEventName(eventName);

            if (!handler && eventName) {
                getWrappersForEventName(id, eventName).each(function(wrapper) {
                    element.stopObserving(eventName, wrapper.handler);
                });
                return element;

            } else if (!eventName) {
                Object.keys(getCacheForID(id)).each(function(eventName) {
                    element.stopObserving(eventName);
                });
                return element;
            }

            var wrapper = findWrapper(id, eventName, handler);
            if (!wrapper) return element;

            if (element.removeEventListener) {
                element.removeEventListener(name, wrapper, false);
            } else {
                element.detachEvent("on" + name, wrapper);
            }

            destroyWrapper(id, eventName, handler);

            return element;
        },

        fire: function(element, eventName, memo) {
            element = $(element);
            if (element == document && document.createEvent && !element.dispatchEvent)
                element = document.documentElement;

            var event;
            if (document.createEvent) {
                event = document.createEvent("HTMLEvents");
                event.initEvent("dataavailable", true, true);
            } else {
                event = document.createEventObject();
                event.eventType = "ondataavailable";
            }

            event.eventName = eventName;
            event.memo = memo || { };

            if (document.createEvent) {
                element.dispatchEvent(event);
            } else {
                element.fireEvent(event.eventType, event);
            }

            return Event.extend(event);
        }
    };
})());

Object.extend(Event, Event.Methods);

Element.addMethods({
    fire:            Event.fire,
    observe:        Event.observe,
    stopObserving:    Event.stopObserving
});

Object.extend(document, {
    fire:            Element.Methods.fire.methodize(),
    observe:        Element.Methods.observe.methodize(),
    stopObserving:    Element.Methods.stopObserving.methodize()
});

//mouse:wheel
(function(){
    function wheel(event){
        var delta;
        // normalize the delta
        if(event.wheelDelta) // IE & Opera
            delta = event.wheelDelta / 120;
        else if (event.detail) // W3C
            delta =- event.detail / 3;
        if(!delta)
            return;
        var custom_event = Event.element(event).fire('mouse:wheel',{
            delta: delta
        });
        if(custom_event.stopped){
            Event.stop(event);
            return false;
        }
    }
    document.observe('mousewheel',wheel);
    document.observe('DOMMouseScroll',wheel);
})();

/* End Core Extensions */

//from PrototypeUI
var IframeShim = Class.create({
    initialize: function() {
        this.element = new Element('iframe',{
            style: 'position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);display:none',
            src: 'javascript:void(0);',
            frameborder: 0
        });
        $(document.body).insert(this.element);
    },
    hide: function() {
        this.element.hide();
        return this;
    },
    show: function() {
        this.element.show();
        return this;
    },
    positionUnder: function(element) {
        var element = $(element);
        var offset = element.cumulativeOffset();
        var dimensions = element.getDimensions();
        this.element.setStyle({
            left: offset[0] + 'px',
            top: offset[1] + 'px',
            width: dimensions.width + 'px',
            height: dimensions.height + 'px',
            zIndex: element.getStyle('zIndex') - 1
        }).show();
        return this;
    },
    setBounds: function(bounds) {
        for(prop in bounds)
            bounds[prop] += 'px';
        this.element.setStyle(bounds);
        return this;
    },
    destroy: function() {
        if(this.element)
            this.element.remove();
        return this;
    }
});<|endoftext|>


<commit_before>var mpq = [];
mpq.push(["init", _bushido_metrics_token]);
(function() {
var mp = document.createElement("script"); mp.type = "text/javascript"; mp.async = true;
mp.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + "//api.mixpanel.com/site_media/js/api/mixpanel.js";
var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(mp, s);
})();

$(function(){
  var section = $('body')[0].className;

  var props = {
    app: window._bushido_app
    ,claimed: window._bushido_claimed
  };

  mpq.push(["track_links", $('div#header h1 a.single'), 'big site name header click', props]);
  mpq.push(["track_links", $('li.contents a'), "Contents", props]);
  mpq.push(["track_links", $('li.assets a'), "Assets", props]);
  mpq.push(["track_links", $('li.settings a'), "Settings", props]);

  $('body.contents div#submenu li:first').each(function(){
    var $this = $(this);
    $this.bind('mouseover', function(){
      //mpmetrics.track("pages hover");
      mpq.push(["track", "pages hover", props]);
    });

    // mpmetrics.track_links($this.find('div.header a'), "pages popup new item");
    // mpmetrics.track_links($this.find('div.inner a'), "pages popup inner links");
  });

  $('body.contents div#submenu li:not(:first)').each(function(){
    var $this = $(this);
    $this.bind('mouseover', function(){
      //mpmetrics.track("model hover");
      mpq.push(["track", "model hover", props]);
    });

    // mpmetrics.track_links($this.find('div.header a'), "model popup new item");
    // mpmetrics.track_links($this.find('div.inner a'), "model popup inner links");
  });

  $('img.toggler').each(function(){
    var $this = $(this);
    $this.bind('click', function(){
      mpq.push(["track", "hiearchy toggler click", props]);
    });
  })

  $('body.contents a.remove').each(function(){
    var $this = $(this);
    $this.bind('click', function(){
      mpq.push(["track", "page trash click", props]);
    });
  });

  $('body.assets button span:contains(Create)').bind('click', function(){
    mpq.push(["track", "asset create", props]);
  });

  $('body.contents button span:contains(Create)').bind('click', function(){
    mpq.push(["track", "content create", props]);
  });

  $('fieldset span').each(function(){
    var $this = $(this);

    $this.bind('click', function(){
      var $content = $this.parent().next('ol')
          ,state = ($content.is(':visible') === true) ? 'close' : 'open';
      mpq.push(["track", section+ " - "+$this.text()+" click to "+state, props]);
    });
  });

  $('input[type="text"]').each(function(){
    var $this = $(this);
    $this.bind('change', function(){
      mpq.push(["track", section+ ' input '+$this.attr('name')+ " change" ,props]);
    });
  });

  $('h2 a.editable').bind('click', function(){
    mpq.push(["track", "editable title click" ,props]);
  });

});<commit_msg>expanded the hooks<commit_after>var mpq = [];
mpq.push(["init", _bushido_metrics_token]);
(function() {
var mp = document.createElement("script"); mp.type = "text/javascript"; mp.async = true;
mp.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + "//api.mixpanel.com/site_media/js/api/mixpanel.js";
var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(mp, s);
})();

$(function(){
  var section = $('body')[0].className;

  var props = {
    app: window._bushido_app
    ,claimed: window._bushido_claimed
  };

  mpq.push(["track_links", $('div#header h1 a.single'), 'big site name header click', props ]);
  mpq.push(["track_links", $('div#global-actions-bar a:first'), 'account settings click', props ]);
  mpq.push(["track_links", $('div#global-actions-bar a:eq(1)'), "see website", props ]);
  mpq.push(["track_links", $('div#global-actions-bar a:eq(2)'), "log out", props ]);
  mpq.push(["track_links", $('li.contents a'), "Contents",  props]);
  mpq.push(["track_links", $('li.assets a'), "Assets", props ]);
  mpq.push(["track_links", $('li.settings a'), "Settings", props ]);
  mpq.push(["track_links", $('#local-actions-bar a.new'), "generic new page", props ]);
  mpq.push(["track_links", $('div.action a'), $('div.action a span').text(), props ]);
  mpq.push(["track_links", $('div.action a'), $('div.action a span'), props ]);
  mpq.push(["track_links", $('body div.span-12 p a'), 'contents back without saving', props ]);
  mpq.push(["track_links", $('div#content div.inner a'), "Page hiearchy title click", props ]);
  mpq.push(["track_links", $('p.no-items a'), "no assets, click here", props ]);

  mpq.push(["track_links", $('#bushi_banner_claim'), "BUSHI CLAIM CLICK!!!!!", props ]);

  $('body.contents div#submenu li:first').each(function(){
    var $this = $(this);
    $this.bind('mouseover', function(){
      //mpmetrics.track("pages hover");
      mpq.push(["track", "pages hover", props]);
    });

    // mpmetrics.track_links($this.find('div.header a'), "pages popup new item");
    // mpmetrics.track_links($this.find('div.inner a'), "pages popup inner links");
  });

  $('body.contents div#submenu li:not(:first)').each(function(){
    var $this = $(this);
    $this.bind('mouseover', function(){
      //mpmetrics.track("model hover");
      mpq.push(["track", "model hover", props]);
    });

    // mpmetrics.track_links($this.find('div.header a'), "model popup new item");
    // mpmetrics.track_links($this.find('div.inner a'), "model popup inner links");
  });

  $('img.toggler').each(function(){
    var $this = $(this);
    $this.bind('click', function(){
      mpq.push(["track", "hiearchy toggler click", props]);
    });
  })

  $('body.contents a.remove').each(function(){
    var $this = $(this);
    $this.bind('click', function(){
      mpq.push(["track", "page trash click", props]);
    });
  });

  $('body.assets button span:contains(Create)').bind('click', function(){
    mpq.push(["track", "asset create", props]);
  });

  $('body.contents button span:contains(Create)').bind('click', function(){
    mpq.push(["track", "content create", props]);
  });

  $('fieldset span').each(function(){
    var $this = $(this);

    $this.bind('click', function(){
      var $content = $this.parent().next('ol')
          ,state = ($content.is(':visible') === true) ? 'close' : 'open';
      mpq.push(["track", section+ " - "+$this.text()+" click to "+state, props]);
    });
  });

  $('input[type="text"]').each(function(){
    var $this = $(this);
    $this.bind('change', function(){
      mpq.push(["track", section+ ' input '+$this.attr('name')+ " change" ,props]);
    });
  });

  $('h2 a.editable').bind('click', function(){
    mpq.push(["track", "editable title click" ,props]);
  });

});<|endoftext|>


<commit_before>"use strict";

// this is a basic wrapper for making Request() requests
//  we wrap this so we can have the same debug information for all requests

var needle = require("needle");

// get our project Log function for writing log output
var Log = require("./debugPrint");

// include our Promise library
var Promise = require("./promise");

/**
 * Make a network request
 * @private
 * @param parameters to pass to request library
 */
function MakeRequest(networkRequest) {
    if (arguments.length != 1) {
        return Promise.reject("HTTP requires 1 argument. The network object configuration");
    }

    // debug log if we're in debug mode
    Log(`Making request to ${networkRequest.url}`);

    // grab method from the request (we'll call .[method] directly using the needle library)
    var requestMethod = networkRequest.method || "get";
    delete networkRequest.method;

    // extract the required URL
    var requestURL = networkRequest.url;
    if (!requestURL) return Promise.reject(`No URL defined for ${requestMethod} request`);
    delete networkRequest.url;

    var requestData = networkRequest.data || networkRequest.body || {};
    delete networkRequest.data;
    delete networkRequest.body;

    // build-in retires into this wrapper (default 3)
    var retries = networkRequest.retries || 3;
    // un-set retries in-case request suddenly supports this or something!
    delete networkRequest.retries;

    // default delay of 2 seconds for each retry attempt
    var retryDelay = networkRequest.retryDelay || 2000;
    delete networkRequest.retryDelay;

    // we will default to returning the body, but can return the full response object if we want
    var returnFullResponse = networkRequest.returnFullResponse || false;
    delete networkRequest.returnFullResponse;

    // add ability to force responses into JSON objects, even if they don't return application/json content header
    var forceJSON = networkRequest.forceJSON || false;
    delete networkRequest.forceJSON;

    // return result as a Promise!
    return new Promise(function(resolve, reject) {
        var attempt = 0;

        // make request in an anonymouse function so we can make multiple requests to it easily
        var attemptRequest = function() {
            Log(`Calling ${requestMethod}:${requestURL}`);

            // build Needle request
            needle.request(requestMethod, requestURL, requestData, networkRequest, function(err, resp) {
                if (err || resp.statusCode >= 400 || (resp.statusCode == 200 && !resp.body)) {
                    Log(`Network request failed attempt ${attempt}/${retries} for URL ${requestURL}`);
                    Log(err || (resp.statusCode + ": " + JSON.stringify(resp.body, null, 2)));

                    // if we have retires left, try again!
                    attempt++;
                    if (attempt < retries) {
                        // try again after retryDelay milliseconds
                        setTimeout(attemptRequest, retryDelay);
                        return;
                    } else {
                        return reject(err || (resp.statusCode + ": " + JSON.stringify(resp.body, null, 2)));
                    }
                }

                // no error! return the result
                if (returnFullResponse) {
                    Log(`Successfully fetched response for URL ${requestURL}`);
                    return resolve(resp);
                } else {
                    // enable "forceJSON" if the return header type is "application/json"
                    if (resp.headers && resp.headers["content-type"] && resp.headers["content-type"].indexOf("application/json") >= 0) {
                        Log("Found 'application/json' header from in HTTP request, parsing JSON data");
                        forceJSON = true;
                    }

                    // if we want to force JSON (and we're not already a JSON object!)
                    if (forceJSON && resp.body.constructor !== {}.constructor && resp.body.constructor !== [].constructor) {
                        var JSONData;
                        try {
                            JSONData = JSON.parse(resp.body);
                        } catch (e) {
                            return reject(`Unable to parse ${resp.body} into a JSON object: ${e}`);
                        }
                        Log(`Successfully fetched and parsed JSON from response at ${requestURL}`);
                        return resolve(JSONData);
                    } else {
                        Log(`Successfully fetched body for URL ${requestURL}`);
                        return resolve(resp.body);
                    }
                }
            });
        };

        // make first request attempt
        process.nextTick(attemptRequest);
    }.bind(this));
}

module.exports = MakeRequest;<commit_msg>[!] Re-attempt HTTP request if JSON parse fails<commit_after>"use strict";

// this is a basic wrapper for making Request() requests
//  we wrap this so we can have the same debug information for all requests

var needle = require("needle");

// get our project Log function for writing log output
var Log = require("./debugPrint");

// include our Promise library
var Promise = require("./promise");

/**
 * Make a network request
 * @private
 * @param parameters to pass to request library
 */
function MakeRequest(networkRequest) {
    if (arguments.length != 1) {
        return Promise.reject("HTTP requires 1 argument. The network object configuration");
    }

    // debug log if we're in debug mode
    Log(`Making request to ${networkRequest.url}`);

    // grab method from the request (we'll call .[method] directly using the needle library)
    var requestMethod = networkRequest.method || "get";
    delete networkRequest.method;

    // extract the required URL
    var requestURL = networkRequest.url;
    if (!requestURL) return Promise.reject(`No URL defined for ${requestMethod} request`);
    delete networkRequest.url;

    var requestData = networkRequest.data || networkRequest.body || {};
    delete networkRequest.data;
    delete networkRequest.body;

    // build-in retires into this wrapper (default 3)
    var retries = networkRequest.retries || 3;
    // un-set retries in-case request suddenly supports this or something!
    delete networkRequest.retries;

    // default delay of 2 seconds for each retry attempt
    var retryDelay = networkRequest.retryDelay || 2000;
    delete networkRequest.retryDelay;

    // we will default to returning the body, but can return the full response object if we want
    var returnFullResponse = networkRequest.returnFullResponse || false;
    delete networkRequest.returnFullResponse;

    // add ability to force responses into JSON objects, even if they don't return application/json content header
    var forceJSON = networkRequest.forceJSON || false;
    delete networkRequest.forceJSON;

    // return result as a Promise!
    return new Promise(function(resolve, reject) {
        var attempt = 0;

        // make request in an anonymouse function so we can make multiple requests to it easily
        var attemptRequest = function() {
            Log(`Calling ${requestMethod}:${requestURL}`);

            // build Needle request
            needle.request(requestMethod, requestURL, requestData, networkRequest, function(err, resp) {
                if (err || resp.statusCode >= 400 || (resp.statusCode == 200 && !resp.body)) {
                    Log(`Network request failed attempt ${attempt}/${retries} for URL ${requestURL}`);
                    Log(err || (resp.statusCode + ": " + JSON.stringify(resp.body, null, 2)));

                    // if we have retires left, try again!
                    attempt++;
                    if (attempt < retries) {
                        // try again after retryDelay milliseconds
                        setTimeout(attemptRequest, retryDelay);
                        return;
                    } else {
                        return reject(err || (resp.statusCode + ": " + JSON.stringify(resp.body, null, 2)));
                    }
                }

                // no error! return the result
                if (returnFullResponse) {
                    Log(`Successfully fetched response for URL ${requestURL}`);
                    return resolve(resp);
                } else {
                    // enable "forceJSON" if the return header type is "application/json"
                    if (resp.headers && resp.headers["content-type"] && resp.headers["content-type"].indexOf("application/json") >= 0) {
                        Log("Found 'application/json' header from in HTTP request, parsing JSON data");
                        forceJSON = true;
                    }

                    // if we want to force JSON (and we're not already a JSON object!)
                    if (forceJSON && resp.body.constructor !== {}.constructor && resp.body.constructor !== [].constructor) {
                        var JSONData;
                        try {
                            JSONData = JSON.parse(resp.body);
                        } catch (e) {
                            // if we have retires left, try again!
                            attempt++;
                            if (attempt < retries) {
                                // try again after retryDelay milliseconds
                                setTimeout(attemptRequest, retryDelay);
                                return;
                            } else {
                                return reject(`Unable to parse ${resp.body} into a JSON object: ${e}`);
                            }
                        }
                        Log(`Successfully fetched and parsed JSON from response at ${requestURL}`);
                        return resolve(JSONData);
                    } else {
                        Log(`Successfully fetched body for URL ${requestURL}`);
                        return resolve(resp.body);
                    }
                }
            });
        };

        // make first request attempt
        process.nextTick(attemptRequest);
    }.bind(this));
}

module.exports = MakeRequest;<|endoftext|>


<commit_before>$(document).ready(function() {

	if (chatroom_theme == 'dark') {
		$('body').css('color', 'white');
		$('#message').css('background-color', 'black');
		$('#message').css('color', 'white');
		$('#chatbox').css('background-color', 'black');
		$('#users').css('background-color', 'black');
		$('#room').css('background-color', 'black');
		$('.user_typing').css('color', 'white');
	}

	if (show_connected_users == 'false') {
		$('#users').hide();
	}

	$('#container, #join_room').css('width', room_width);
	$('#room').css('width', room_width - 162);
	$('#body').css('font-size', font_size + 'px');
});<commit_msg>added to chatroom.js<commit_after><|endoftext|>


<commit_before>/**
 * Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var AWS = require('./core');
var inherit = AWS.util.inherit;

/**
 * @constructor
 */
AWS.Endpoint = inherit({

  constructor: function Endpoint(config, serviceName) {
    this.region = config.region;
    this.scheme = config.useSSL ? 'https' : 'http';
    this.host = serviceName + '.' + config.region + '.amazonaws.com';
    this.port = config.useSSL ? 443 : 80;
  }

});

AWS.HttpRequest = inherit({

  constructor: function HttpRequest() {
    this.method = 'POST';
    this.uri = '/';
    this.headers = {};
    this.headers['User-Agent'] = 'aws-sdk-js/0.1';
    this.body = undefined;
    this.endpoint = undefined;
  },

  pathname: function pathname() {
    return this.uri.split('?', 1)[0];
  },

  search: function search() {
    return this.uri.split('?', 2)[1] || '';
  }

});

/**
 * @constructor
 */
AWS.HttpResponse = inherit({
  constructor: function HttpResponse() {
    this.statusCode = null;
    this.headers = {};
    this.body = null;
  }
});

/**
 * @constructor
 */
AWS.RequestHandler = inherit({

  constructor: function RequestHandler(awsRequest) {
    this.awsRequest = awsRequest;
    this.awsResponse = awsRequest.awsResponse;
    this.service = this.awsResponse.service;
    this.method = this.awsResponse.method;
    this.params = this.awsResponse.params;
  },

  makeRequest: function makeRequest() {

    var requestHandler = this;
    var httpResponse = new AWS.HttpResponse();
    var httpRequest = this.service.buildRequest(this.method, this.params);
    httpRequest.sign();

    this.awsResponse.httpResponse = httpResponse;
    this.awsResponse.httpRequest = httpRequest;

    AWS.HttpClient.getInstance().handleRequest(httpRequest, {

      onHeaders: function onHeaders(statusCode, headers) {
        httpResponse.statusCode = statusCode;
        httpResponse.headers = headers;
      },

      onData: function onData(data) {
        if (httpResponse.body === null) {
          httpResponse.body = data;
        } else {
          httpResponse.body += data;
        }
      },

      onEnd: function onEnd() {
        if (httpResponse.body) {
          httpResponse.body = httpResponse.body.toString();
        }
        requestHandler.handleHttpResponse(httpResponse);
      },

      onError: function onError(error) {
        requestHandler.retryRequest(error);
      }

    });

  },

  // Called when the http client returns a response.  Successfull http requests
  // may still contain an error (e.g. 400, 500, etc)
  handleHttpResponse: function handleHttpResponse(httpResponse) {
    try {
      var self = this;
      this.service.parseResponse(httpResponse, this.method, function (error, data) {
        if (error)
          self.handleError(error);
        else
          self.awsRequest.notifyDone(data);
      });
    } catch (error) {
      // unrecoverable error trying to parse the response
      this.awsRequest.notifyFail(error);
    }
  },

  handleError: function handleError(error) {
    if (error.retryable) {
      this.retryRequest(error);
    } else {
      this.awsRequest.notifyFail(error);
    }
  },

  retryRequest: function retryRequest(error) {

    var delays = this.service.retryDelays();
    var delay = delays[this.awsResponse.retryCount];

    this.awsResponse.retryCount += 1;

    if (delay !== undefined) {

      var requestHandler = this;
      setTimeout(function delayRetry() {
        requestHandler.makeRequest();
      }, delay);

    } else {

      this.awsRequest.notifyFail(error); // retried too many times

    }
  }
});

/**
 * @constructor
 */
AWS.NodeHttpClient = inherit({
  constructor: function NodeHttpClient() {},

  handleRequest: function handleRequest(request, callbacks) {

    var options = {
      host: request.endpoint.host,
      port: request.endpoint.port,
      method: request.method,
      headers: request.headers,
      path: request.uri
    };

    var client = request.endpoint.scheme === 'https' ?
      require('https') : require('http');

    var req = client.request(options, function onResponse(resp) {
      callbacks.onHeaders(resp.statusCode, resp.headers);
      resp.on('data', callbacks.onData);
      resp.on('end', callbacks.onEnd);
    });

    if (request.body) req.write(request.body);

    req.end();
    req.on('error', function (e) {
      callbacks.onError({ code: 'NetworkingError', message: e.toString() });
    });
  }
});

AWS.HttpClient = AWS.NodeHttpClient;

AWS.HttpClient.getInstance = function getInstance() {
  /*jshint newcap:false */
  if (this.singleton === undefined) {
    this.singleton = new this();
  }
  return this.singleton;
};
<commit_msg>Don't hardcode version in User-Agent string<commit_after>/**
 * Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var AWS = require('./core');
var inherit = AWS.util.inherit;

/**
 * @constructor
 */
AWS.Endpoint = inherit({

  constructor: function Endpoint(config, serviceName) {
    this.region = config.region;
    this.scheme = config.useSSL ? 'https' : 'http';
    this.host = serviceName + '.' + config.region + '.amazonaws.com';
    this.port = config.useSSL ? 443 : 80;
  }

});

AWS.HttpRequest = inherit({

  constructor: function HttpRequest() {
    this.method = 'POST';
    this.uri = '/';
    this.headers = {};
    this.headers['User-Agent'] = 'aws-sdk-js/' + AWS.VERSION;
    this.body = undefined;
    this.endpoint = undefined;
  },

  pathname: function pathname() {
    return this.uri.split('?', 1)[0];
  },

  search: function search() {
    return this.uri.split('?', 2)[1] || '';
  }

});

/**
 * @constructor
 */
AWS.HttpResponse = inherit({
  constructor: function HttpResponse() {
    this.statusCode = null;
    this.headers = {};
    this.body = null;
  }
});

/**
 * @constructor
 */
AWS.RequestHandler = inherit({

  constructor: function RequestHandler(awsRequest) {
    this.awsRequest = awsRequest;
    this.awsResponse = awsRequest.awsResponse;
    this.service = this.awsResponse.service;
    this.method = this.awsResponse.method;
    this.params = this.awsResponse.params;
  },

  makeRequest: function makeRequest() {

    var requestHandler = this;
    var httpResponse = new AWS.HttpResponse();
    var httpRequest = this.service.buildRequest(this.method, this.params);
    httpRequest.sign();

    this.awsResponse.httpResponse = httpResponse;
    this.awsResponse.httpRequest = httpRequest;

    AWS.HttpClient.getInstance().handleRequest(httpRequest, {

      onHeaders: function onHeaders(statusCode, headers) {
        httpResponse.statusCode = statusCode;
        httpResponse.headers = headers;
      },

      onData: function onData(data) {
        if (httpResponse.body === null) {
          httpResponse.body = data;
        } else {
          httpResponse.body += data;
        }
      },

      onEnd: function onEnd() {
        if (httpResponse.body) {
          httpResponse.body = httpResponse.body.toString();
        }
        requestHandler.handleHttpResponse(httpResponse);
      },

      onError: function onError(error) {
        requestHandler.retryRequest(error);
      }

    });

  },

  // Called when the http client returns a response.  Successfull http requests
  // may still contain an error (e.g. 400, 500, etc)
  handleHttpResponse: function handleHttpResponse(httpResponse) {
    try {
      var self = this;
      this.service.parseResponse(httpResponse, this.method, function (error, data) {
        if (error)
          self.handleError(error);
        else
          self.awsRequest.notifyDone(data);
      });
    } catch (error) {
      // unrecoverable error trying to parse the response
      this.awsRequest.notifyFail(error);
    }
  },

  handleError: function handleError(error) {
    if (error.retryable) {
      this.retryRequest(error);
    } else {
      this.awsRequest.notifyFail(error);
    }
  },

  retryRequest: function retryRequest(error) {

    var delays = this.service.retryDelays();
    var delay = delays[this.awsResponse.retryCount];

    this.awsResponse.retryCount += 1;

    if (delay !== undefined) {

      var requestHandler = this;
      setTimeout(function delayRetry() {
        requestHandler.makeRequest();
      }, delay);

    } else {

      this.awsRequest.notifyFail(error); // retried too many times

    }
  }
});

/**
 * @constructor
 */
AWS.NodeHttpClient = inherit({
  constructor: function NodeHttpClient() {},

  handleRequest: function handleRequest(request, callbacks) {

    var options = {
      host: request.endpoint.host,
      port: request.endpoint.port,
      method: request.method,
      headers: request.headers,
      path: request.uri
    };

    var client = request.endpoint.scheme === 'https' ?
      require('https') : require('http');

    var req = client.request(options, function onResponse(resp) {
      callbacks.onHeaders(resp.statusCode, resp.headers);
      resp.on('data', callbacks.onData);
      resp.on('end', callbacks.onEnd);
    });

    if (request.body) req.write(request.body);

    req.end();
    req.on('error', function (e) {
      callbacks.onError({ code: 'NetworkingError', message: e.toString() });
    });
  }
});

AWS.HttpClient = AWS.NodeHttpClient;

AWS.HttpClient.getInstance = function getInstance() {
  /*jshint newcap:false */
  if (this.singleton === undefined) {
    this.singleton = new this();
  }
  return this.singleton;
};
<|endoftext|>


<commit_before>(function($) {
    $(function() {
        /**
         * Change trigger for checkboxes in a checkbox list.
         *
         * Handles "select all" functionality as well as the value of
         * the "select all" checkbox when other checkboxes are changed.
         */
        $(".checkbox-list :checkbox").change(function() {
            var cb = $(this);
            var l = cb.parents(".checkbox-list");

            if (cb.hasClass("all-toggler")) {
                // "Select all"
                if (cb.is(":checked")) {
                    l.find(":checkbox:not(:checked)").attr("checked", true);
                } else {
                    l.find(":checkbox:checked").attr("checked", false);
                }
            } else {
                if (cb.is(":checked")) {
                    if (l.find(":checkbox:not(:checked):not(.all-toggler)").length <= 0) {
                        l.find(".all-toggler").attr("checked", true);
                    }
                } else {
                    l.find(".all-toggler").attr("checked", false);
                }
            }
        });
    });

    $(function () {
        if ($("#kp-group-selection-form").length > 0) {
            /**
             * Fetches schools by Ajax when choosing a district in the group selection fragment
             */
            $("#kp-group_selection-district_id").change(function() {
                var districtId = $("#kp-group_selection-district_id option:selected").val();
                var values = $(this).parents("form").serialize();

                $("#kp-group_selection-district_id").parent().append('

');

                $("#kp-group_selection-school_id").attr("disabled", "disabled");
                $("#kp-group_selection-group_id").html("<option>Välj skola först</option>").attr("disabled", "disabled");

                var request = $.ajax({
                    url: kpConfig.schools.list.url,
                    data: values,
                    success: function(data) {
                        $("#kp-group_selection-school_id").html(data).removeAttr("disabled");
                    },
                    error: function() {
                        $("#kp-group_selection-school_id").html("<option>Välj stadsdel först</option>");
                    },
                    complete: function() {
                        $("#kp-group-selection-form").trigger("districtSelected", [ districtId ]);
                        $("#kp-group_selection-district_id").parent().find('.load-indicator').remove();
                    }
                });

            });
            /**
             * Fetches groups by Ajax when choosing a school in the group selection fragment
             */
            $("#kp-group_selection-school_id").change(function() {
                var schoolId = $("#kp-group_selection-school_id option:selected").val();
                var values = $(this).parents("form").serialize();

                $("#kp-group_selection-school_id").parent().append('

');
                $("#kp-group_selection-group_id").attr("disabled", "disabled");

                var request = $.ajax({
                    url: kpConfig.groups.list.url,
                    data: values,
                    success: function(data, textStatus) {
                        $("#kp-group_selection-group_id").html(data).removeAttr("disabled");
                    },
                    error: function() {
                        $("#kp-group_selection-group_id").html("<option>Välj skola först</option>");
                    },
                    complete: function() {
                        $("#kp-group_selection-school_id").parent().find('.load-indicator').remove();
                        $("#kp-group-selection-form").trigger("schoolSelected", [ schoolId ]);
                    }
                });
            });
            /**
             * Triggers the event groupSelected on the group selection fragment when selecting
             * a group.
             */
            $("#kp-group_selection-group_id").change(function() {
                var groupId = parseInt($("#kp-group_selection-group_id option:selected").val());
                $("#kp-group-selection-form").trigger("groupSelected", [ groupId ])
                $.get(kpConfig.groups.select.url, { group_id: groupId });
            });
        }
    });

    $(function() {
        /**
         * Listeners for group selection fragment events for the notification request form
         */
        $("#kp .notification-request-group-selection #kp-group-selection-form"
        ).bind("groupSelected", function(e, groupId) {
            if (!isNaN(groupId)) {
                // Set the groupId in the form
                $("#kp-notification_request-group_id").val(groupId);
                $("#kp .notification-request-form input").removeAttr("disabled");
            } else {
                // Disable the form
                $("#kp .notification-request-form input").attr("disabled", "disabled");
            }
        }).bind("districtSelected schoolSelected", function(e, id){
            // Disable the form
            $("#kp .notification-request-form input").attr("disabled", "disabled");
        });

        /**
         * Listeners for group selection fragment events for the group bookings listing
         */
        $("#kp .group-bookings-group-selection #kp-group-selection-form"
        ).bind("groupSelected", function(e, groupId) {
            if (!isNaN(groupId)) {
                // Load the group booking list
                var request = $.get(kpConfig.booking.groupList.url,
                { group_id: groupId },
                function(data) {
                    $("#kp-group-bookings-container").html(data);
                });
            } else {
                $("#kp-group-bookings-container").html("");
            }
        }).bind("districtSelected schoolSelected", function(e, id){
            $("#kp-group-bookings-container").html("");
        });
    });

    $(function() {
        /**
         * Shows the multiple choice input field when choosing the question type
         * "multiple choice".
         */
        $("#kp .question-form .types-field-row :radio").click(function() {
            if ($(this).val() == "QuestionMchoice") {
                $("#kp .question-form .choice_csv-field-row").show("slow");
            } else {
                $("#kp .question-form .choice_csv-field-row").hide("slow")
            }
        });
    });

    $(function() {
        /**
         * Sums the number of booked tickets in the booking view.
         * TODO: handle non-number input
         */
        var changeHandler = function() {
            var inputs = $("#kp #kp-booking-form-container .num-seats");
            var i;
            var sum = 0;

            for ( i = 0 ; i < inputs.length ; i++) {
                if (!isNaN(Number(inputs[i].value))) {
                    sum += Number(inputs[i].value);
                }
            };

            $("#kp-booking-count").html("Du har angett totalt " + String(sum) + " platser.");
        };

        $("#kp-booking-form-container").change(changeHandler);
        $("#kp-booking-form-container").keyup(changeHandler);

        $("

").appendTo(
        "#kp-booking-form-container .seats-container");
        changeHandler();

        /**
         * Listeners for group selection fragment events for the booking form
         */
        $("#kp .booking-group-selection #kp-group-selection-form"
        ).bind("groupSelected", function(e, groupId) {
            if (!isNaN(groupId)) {
                var occasionId = $("#kp-occasion_id").val();

                $("#kp-group_selection-group_id").parent().append('

');

                var request = $.get(
                kpConfig.booking.form.url,
                { group_id: groupId, occasion_id: occasionId },
                function(data) {
                    $("#kp-booking-form-container").html(data);
                    $("#kp-group_selection-group_id").parent().find('.load-indicator').remove();

                    // Hack the incoming URL for use in Sitevision
                    var base = $("#kp-sitevision-base-url").attr("href");
                    var form = $("#kp-booking-form-container form.booking-form");
                    var path = form.attr("action");
                    // Strip the trailing slash from the base
                    form.attr("action", base.substr(0, base.length - 1) + path);

                    $("

").appendTo(
                    "#kp-booking-form-container .seats-container");
                    changeHandler();
                });

            } else {
                // Disable the form
                $("#kp-booking-form-container").html("");
            }
        }).bind("districtSelected schoolSelected", function(e, id){
            // Disable the form
            $("#kp-booking-form-container").html("");
        });

    });

    $(function() {
        /**
         * Default settings for the date picker.
         */
        $.datepicker.setDefaults({
            dateFormat: "yy-mm-dd",
            firstDay: 1,
            showOn: "both",
            buttonText: "Visa kalender",
            dayNames: ['söndag', 'måndag', 'tisdag', 'onsdag', 'torsdag', 'fredag', 'lördag'],
            dayNamesMin: ['sö', 'må', 'ti', 'on', 'to', 'fr', 'lö'],
            dayNamesShort: ['sön', 'mån', 'tis', 'ons', 'tor', 'fre', 'lör'],
            monthNames: ['januari', 'februari', 'mars', 'april', 'maj', 'juni', 'juli', 'augusti', 'september', 'oktober', 'november', 'december'],
            monthNamesShort: ['jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec']
        });

        // The minimum date is today on an auto date field
        var today = new Date();
        $("#kp .date-field.auto").datepicker({
            minDate: new Date()
        });

        // The minimum date is tomorrow on the ticket release date field
        var tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);

        $("#kp #kp-allotment-release_date").datepicker({
            minDate: tomorrow
        });

        // Default settings on the date fields in the filter form
        $("#kp #kp-calendar-filter-from-date, #kp #kp-calendar-filter-to-date").datepicker();
    });

    $(function() {
        // Tabs
        $("#kp .tabs").tabs();

        /**
         * Preselection of tabs.
         */
        $("#kp .tabs .preselect").each(function () {
            var tab = $(this);
            var tabIdx = tab.parent().children("li").index(tab);
            tab.parents(".ui-tabs").tabs("select", tabIdx);
        });
    });

    $(function() {
        /**
         * Image cycling
         */
        $("#kp .model-cnt .images-cnt").each(function() {
            var c = $(this);
            var imgs = c.find("img");

            if (imgs.length > 1) {

                c.find(".images").cycle("fade");

                // Trigger for playing/pausing the cycling.
                $("Spela/Pausa").appendTo(c).toggle(
                function() {
                    $(this).removeClass("playing").addClass("paused").siblings(".images").cycle("pause");
                },
                function() {
                    $(this).removeClass("paused").addClass("playing").siblings(".images").cycle("resume", true);
                });
            }
        });
    });

    $(function() {
        /**
         * Collapsible fieldsets
         */
        $("#kp fieldset.collapsible legend").click(function() {
            $(this).parent().toggleClass("collapsed");
        });
    });

    $(function() {
        /**
         * Disable age filters when choosing further education
         */
        $("#kp #kp-calendar-filter-further-education-true").change(function() {
            if ($(this).is(":checked")) {
                $("#kp #kp-calendar-filter-from-age, #kp #kp-calendar-filter-to-age").attr("disabled", "disabled");
            }
        });
        /**
         * Enable age filters when discarding further education
         */
        $("#kp #kp-calendar-filter-further-education-false").change(function() {
            if ($(this).is(":checked")) {
                $("#kp #kp-calendar-filter-from-age, #kp #kp-calendar-filter-to-age").removeAttr("disabled");
            }
        });
    });

    $(function() {
        /**
         * Hijacks the link going to the list with ticket availability
         * and displays the list using Ajax in a UI dialog.
         */
        $("#kp .calendar-list .ticket-availability-link").click(function() {
            var link = $(this);
            var url = link.attr("href");
            var linkContainer = link.parent();

            link.hide();
            linkContainer.append('

');

            $.get(url, function(data) {

                linkContainer.find(".load-indicator").remove();
                link.show();

                dialogContainer = $("#kp-ticket-availability-dialog");

                if (dialogContainer.length > 0) {
                    dialogContainer.children().remove();
                    dialogContainer.dialog("destroy");
                } else {
                    dialogContainer = $("

").appendTo("body");
                }

                var d = $(data);
                dialogContainer.append(d);

                // Fix for incoming URL:s in Sitevision
                var urlBase = $("#kp-sitevision-base-url").attr("href");
                dialogContainer.find("a").each(function(i, elem) {
                    var link = $(elem);
                    var href = link.attr("href");

                    // Remove the domain name (IE fix)
                    if (href.indexOf("http://") == 0) {
                        href = href.slice(href.indexOf("/", 7));
                    }

                    link.attr("href", urlBase.substr(0, urlBase.length - 1) + href);
                });

                dialogContainer.dialog({
                    width: 640,
                    height: 480,
                    modal: true,
                    resizable: false,
                    draggable: true,
                    title: link.attr("title"),
                    close: function() { dialogContainer.dialog("destroy").remove(); }
                });
            });

            return false;
        });
    });

    $(function() {
        /**
         * Hides the age inputs when selecting further education in the event
         * form.
         */
        $("#kp #kp-event-further_education").click(function() {
            if ($(this).is(":checked")) {
                $("#kp .from_age-field-row, #kp .to_age-field-row").hide();
            } else {
                $("#kp .from_age-field-row, #kp .to_age-field-row").show();
            }
        });
    });

    $(function() {
        /**
         * Ajax functionality for selecting an event when adding links
         * between events.
         */
        $("#kp #kp-event_link-culture_provider_id").change(function() {
            var cpId = parseInt($(this).val());

            if (!isNaN(cpId) && cpId > 0) {
                $.get(
                kpConfig.events.list.url,
                { "culture_provider_id": cpId },
                function(data) {
                    $("#kp-event_link-event_id").html(data).removeAttr("disabled", "disabled");
                    $("#kp-event_link-submit").removeAttr("disabled", "disabled");
                });
            } else {
                $("#kp-event_link-event_id, #kp-event_link-submit").attr("disabled", "disabled");
            }
        });
    });

})(jQuery);
<commit_msg>Buggfix för Sitevision-Ajax-problem i bokningslistningen.<commit_after>(function($) {
    $(function() {
        /**
         * Change trigger for checkboxes in a checkbox list.
         *
         * Handles "select all" functionality as well as the value of
         * the "select all" checkbox when other checkboxes are changed.
         */
        $(".checkbox-list :checkbox").change(function() {
            var cb = $(this);
            var l = cb.parents(".checkbox-list");

            if (cb.hasClass("all-toggler")) {
                // "Select all"
                if (cb.is(":checked")) {
                    l.find(":checkbox:not(:checked)").attr("checked", true);
                } else {
                    l.find(":checkbox:checked").attr("checked", false);
                }
            } else {
                if (cb.is(":checked")) {
                    if (l.find(":checkbox:not(:checked):not(.all-toggler)").length <= 0) {
                        l.find(".all-toggler").attr("checked", true);
                    }
                } else {
                    l.find(".all-toggler").attr("checked", false);
                }
            }
        });
    });

    $(function () {
        if ($("#kp-group-selection-form").length > 0) {
            /**
             * Fetches schools by Ajax when choosing a district in the group selection fragment
             */
            $("#kp-group_selection-district_id").change(function() {
                var districtId = $("#kp-group_selection-district_id option:selected").val();
                var values = $(this).parents("form").serialize();

                $("#kp-group_selection-district_id").parent().append('

');

                $("#kp-group_selection-school_id").attr("disabled", "disabled");
                $("#kp-group_selection-group_id").html("<option>Välj skola först</option>").attr("disabled", "disabled");

                var request = $.ajax({
                    url: kpConfig.schools.list.url,
                    data: values,
                    success: function(data) {
                        $("#kp-group_selection-school_id").html(data).removeAttr("disabled");
                    },
                    error: function() {
                        $("#kp-group_selection-school_id").html("<option>Välj stadsdel först</option>");
                    },
                    complete: function() {
                        $("#kp-group-selection-form").trigger("districtSelected", [ districtId ]);
                        $("#kp-group_selection-district_id").parent().find('.load-indicator').remove();
                    }
                });

            });
            /**
             * Fetches groups by Ajax when choosing a school in the group selection fragment
             */
            $("#kp-group_selection-school_id").change(function() {
                var schoolId = $("#kp-group_selection-school_id option:selected").val();
                var values = $(this).parents("form").serialize();

                $("#kp-group_selection-school_id").parent().append('

');
                $("#kp-group_selection-group_id").attr("disabled", "disabled");

                var request = $.ajax({
                    url: kpConfig.groups.list.url,
                    data: values,
                    success: function(data, textStatus) {
                        $("#kp-group_selection-group_id").html(data).removeAttr("disabled");
                    },
                    error: function() {
                        $("#kp-group_selection-group_id").html("<option>Välj skola först</option>");
                    },
                    complete: function() {
                        $("#kp-group_selection-school_id").parent().find('.load-indicator').remove();
                        $("#kp-group-selection-form").trigger("schoolSelected", [ schoolId ]);
                    }
                });
            });
            /**
             * Triggers the event groupSelected on the group selection fragment when selecting
             * a group.
             */
            $("#kp-group_selection-group_id").change(function() {
                var groupId = parseInt($("#kp-group_selection-group_id option:selected").val());
                $("#kp-group-selection-form").trigger("groupSelected", [ groupId ])
                $.get(kpConfig.groups.select.url, { group_id: groupId });
            });
        }
    });

    $(function() {
        /**
         * Listeners for group selection fragment events for the notification request form
         */
        $("#kp .notification-request-group-selection #kp-group-selection-form"
        ).bind("groupSelected", function(e, groupId) {
            if (!isNaN(groupId)) {
                // Set the groupId in the form
                $("#kp-notification_request-group_id").val(groupId);
                $("#kp .notification-request-form input").removeAttr("disabled");
            } else {
                // Disable the form
                $("#kp .notification-request-form input").attr("disabled", "disabled");
            }
        }).bind("districtSelected schoolSelected", function(e, id){
            // Disable the form
            $("#kp .notification-request-form input").attr("disabled", "disabled");
        });

        /**
         * Listeners for group selection fragment events for the group bookings listing
         */
        $("#kp .group-bookings-group-selection #kp-group-selection-form"
        ).bind("groupSelected", function(e, groupId) {
            if (!isNaN(groupId)) {
                // Load the group booking list
                var request = $.get(kpConfig.booking.groupList.url,
                { group_id: groupId },
                function(data) {
                    var cnt = $("#kp-group-bookings-container");
                    cnt.html(data);

                    // Fix for incoming URL:s in Sitevision
                    var urlBase = $("#kp-sitevision-base-url").attr("href");
                    cnt.find("a").each(function(i, elem) {
                        var link = $(elem);
                        var href = link.attr("href");

                        // Remove the domain name (IE fix)
                        if (href.indexOf("http://") == 0) {
                            href = href.slice(href.indexOf("/", 7));
                        }

                        link.attr("href", urlBase.substr(0, urlBase.length - 1) + href);
                    });
                });
            } else {
                $("#kp-group-bookings-container").html("");
            }
        }).bind("districtSelected schoolSelected", function(e, id){
            $("#kp-group-bookings-container").html("");
        });
    });

    $(function() {
        /**
         * Shows the multiple choice input field when choosing the question type
         * "multiple choice".
         */
        $("#kp .question-form .types-field-row :radio").click(function() {
            if ($(this).val() == "QuestionMchoice") {
                $("#kp .question-form .choice_csv-field-row").show("slow");
            } else {
                $("#kp .question-form .choice_csv-field-row").hide("slow")
            }
        });
    });

    $(function() {
        /**
         * Sums the number of booked tickets in the booking view.
         * TODO: handle non-number input
         */
        var changeHandler = function() {
            var inputs = $("#kp #kp-booking-form-container .num-seats");
            var i;
            var sum = 0;

            for ( i = 0 ; i < inputs.length ; i++) {
                if (!isNaN(Number(inputs[i].value))) {
                    sum += Number(inputs[i].value);
                }
            };

            $("#kp-booking-count").html("Du har angett totalt " + String(sum) + " platser.");
        };

        $("#kp-booking-form-container").change(changeHandler);
        $("#kp-booking-form-container").keyup(changeHandler);

        $("

").appendTo(
        "#kp-booking-form-container .seats-container");
        changeHandler();

        /**
         * Listeners for group selection fragment events for the booking form
         */
        $("#kp .booking-group-selection #kp-group-selection-form"
        ).bind("groupSelected", function(e, groupId) {
            if (!isNaN(groupId)) {
                var occasionId = $("#kp-occasion_id").val();

                $("#kp-group_selection-group_id").parent().append('

');

                var request = $.get(
                kpConfig.booking.form.url,
                { group_id: groupId, occasion_id: occasionId },
                function(data) {
                    $("#kp-booking-form-container").html(data);
                    $("#kp-group_selection-group_id").parent().find('.load-indicator').remove();

                    // Hack the incoming URL for use in Sitevision
                    var base = $("#kp-sitevision-base-url").attr("href");
                    var form = $("#kp-booking-form-container form.booking-form");
                    var path = form.attr("action");
                    // Strip the trailing slash from the base
                    form.attr("action", base.substr(0, base.length - 1) + path);

                    $("

").appendTo(
                    "#kp-booking-form-container .seats-container");
                    changeHandler();
                });

            } else {
                // Disable the form
                $("#kp-booking-form-container").html("");
            }
        }).bind("districtSelected schoolSelected", function(e, id){
            // Disable the form
            $("#kp-booking-form-container").html("");
        });

    });

    $(function() {
        /**
         * Default settings for the date picker.
         */
        $.datepicker.setDefaults({
            dateFormat: "yy-mm-dd",
            firstDay: 1,
            showOn: "both",
            buttonText: "Visa kalender",
            dayNames: ['söndag', 'måndag', 'tisdag', 'onsdag', 'torsdag', 'fredag', 'lördag'],
            dayNamesMin: ['sö', 'må', 'ti', 'on', 'to', 'fr', 'lö'],
            dayNamesShort: ['sön', 'mån', 'tis', 'ons', 'tor', 'fre', 'lör'],
            monthNames: ['januari', 'februari', 'mars', 'april', 'maj', 'juni', 'juli', 'augusti', 'september', 'oktober', 'november', 'december'],
            monthNamesShort: ['jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec']
        });

        // The minimum date is today on an auto date field
        var today = new Date();
        $("#kp .date-field.auto").datepicker({
            minDate: new Date()
        });

        // The minimum date is tomorrow on the ticket release date field
        var tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);

        $("#kp #kp-allotment-release_date").datepicker({
            minDate: tomorrow
        });

        // Default settings on the date fields in the filter form
        $("#kp #kp-calendar-filter-from-date, #kp #kp-calendar-filter-to-date").datepicker();
    });

    $(function() {
        // Tabs
        $("#kp .tabs").tabs();

        /**
         * Preselection of tabs.
         */
        $("#kp .tabs .preselect").each(function () {
            var tab = $(this);
            var tabIdx = tab.parent().children("li").index(tab);
            tab.parents(".ui-tabs").tabs("select", tabIdx);
        });
    });

    $(function() {
        /**
         * Image cycling
         */
        $("#kp .model-cnt .images-cnt").each(function() {
            var c = $(this);
            var imgs = c.find("img");

            if (imgs.length > 1) {

                c.find(".images").cycle("fade");

                // Trigger for playing/pausing the cycling.
                $("Spela/Pausa").appendTo(c).toggle(
                function() {
                    $(this).removeClass("playing").addClass("paused").siblings(".images").cycle("pause");
                },
                function() {
                    $(this).removeClass("paused").addClass("playing").siblings(".images").cycle("resume", true);
                });
            }
        });
    });

    $(function() {
        /**
         * Collapsible fieldsets
         */
        $("#kp fieldset.collapsible legend").click(function() {
            $(this).parent().toggleClass("collapsed");
        });
    });

    $(function() {
        /**
         * Disable age filters when choosing further education
         */
        $("#kp #kp-calendar-filter-further-education-true").change(function() {
            if ($(this).is(":checked")) {
                $("#kp #kp-calendar-filter-from-age, #kp #kp-calendar-filter-to-age").attr("disabled", "disabled");
            }
        });
        /**
         * Enable age filters when discarding further education
         */
        $("#kp #kp-calendar-filter-further-education-false").change(function() {
            if ($(this).is(":checked")) {
                $("#kp #kp-calendar-filter-from-age, #kp #kp-calendar-filter-to-age").removeAttr("disabled");
            }
        });
    });

    $(function() {
        /**
         * Hijacks the link going to the list with ticket availability
         * and displays the list using Ajax in a UI dialog.
         */
        $("#kp .calendar-list .ticket-availability-link").click(function() {
            var link = $(this);
            var url = link.attr("href");
            var linkContainer = link.parent();

            link.hide();
            linkContainer.append('

');

            $.get(url, function(data) {

                linkContainer.find(".load-indicator").remove();
                link.show();

                dialogContainer = $("#kp-ticket-availability-dialog");

                if (dialogContainer.length > 0) {
                    dialogContainer.children().remove();
                    dialogContainer.dialog("destroy");
                } else {
                    dialogContainer = $("

").appendTo("body");
                }

                var d = $(data);
                dialogContainer.append(d);

                // Fix for incoming URL:s in Sitevision
                var urlBase = $("#kp-sitevision-base-url").attr("href");
                dialogContainer.find("a").each(function(i, elem) {
                    var link = $(elem);
                    var href = link.attr("href");

                    // Remove the domain name (IE fix)
                    if (href.indexOf("http://") == 0) {
                        href = href.slice(href.indexOf("/", 7));
                    }

                    link.attr("href", urlBase.substr(0, urlBase.length - 1) + href);
                });

                dialogContainer.dialog({
                    width: 640,
                    height: 480,
                    modal: true,
                    resizable: false,
                    draggable: true,
                    title: link.attr("title"),
                    close: function() { dialogContainer.dialog("destroy").remove(); }
                });
            });

            return false;
        });
    });

    $(function() {
        /**
         * Hides the age inputs when selecting further education in the event
         * form.
         */
        $("#kp #kp-event-further_education").click(function() {
            if ($(this).is(":checked")) {
                $("#kp .from_age-field-row, #kp .to_age-field-row").hide();
            } else {
                $("#kp .from_age-field-row, #kp .to_age-field-row").show();
            }
        });
    });

    $(function() {
        /**
         * Ajax functionality for selecting an event when adding links
         * between events.
         */
        $("#kp #kp-event_link-culture_provider_id").change(function() {
            var cpId = parseInt($(this).val());

            if (!isNaN(cpId) && cpId > 0) {
                $.get(
                kpConfig.events.list.url,
                { "culture_provider_id": cpId },
                function(data) {
                    $("#kp-event_link-event_id").html(data).removeAttr("disabled", "disabled");
                    $("#kp-event_link-submit").removeAttr("disabled", "disabled");
                });
            } else {
                $("#kp-event_link-event_id, #kp-event_link-submit").attr("disabled", "disabled");
            }
        });
    });

})(jQuery);
<|endoftext|>


<commit_before>'use strict';

const database = require('./init/database');
const config = require('./init/config');
const sessions = require('./init/sessions');
const schedule = require('./init/schedule');
const passport = require('./init/passport');
const acl = require('./init/acl');
const views = require('./init/views');
const logger = require('./init/logger');
const parser = require('./init/parser');
const locals = require('./init/locals');
const staticFiles = require('./init/static');
const authenticated = require('./init/authenticated');
const settings = require('./init/settings');
const workflows = require('./init/workflows');
const routes = require('./init/routes');

module.exports = (application) => {
  return database(application).then(app => {
    return config(app);
  }).then(app => {
    return sessions(app);
  }).then(app => {
    return schedule(app);
  }).then(app => {
    return passport(app);
  }).then(app => {
    return acl(app);
  }).then(app => {
    return settings(app);
  }).then(app => {
    return workflows(app);
  }).then(app => {
    return routes(app);
  }).then(app => {
    return views(app);
  }).then(app => {
    return logger(app);
  }).then(app => {
    return parser(app);
  }).then(app => {
    return locals(app);
  }).then(app => {
    return authenticated(app);
  }).then(app => {
    return staticFiles(app);
  });
};
<commit_msg>:bug: config first to get init<commit_after>'use strict';

const database = require('./init/database');
const config = require('./init/config');
const sessions = require('./init/sessions');
const schedule = require('./init/schedule');
const passport = require('./init/passport');
const acl = require('./init/acl');
const views = require('./init/views');
const logger = require('./init/logger');
const parser = require('./init/parser');
const locals = require('./init/locals');
const staticFiles = require('./init/static');
const authenticated = require('./init/authenticated');
const settings = require('./init/settings');
const workflows = require('./init/workflows');
const routes = require('./init/routes');

module.exports = (application) => {
  return config(application).then(app => {
    return database(app);
  }).then(app => {
    return sessions(app);
  }).then(app => {
    return schedule(app);
  }).then(app => {
    return passport(app);
  }).then(app => {
    return acl(app);
  }).then(app => {
    return settings(app);
  }).then(app => {
    return workflows(app);
  }).then(app => {
    return routes(app);
  }).then(app => {
    return views(app);
  }).then(app => {
    return logger(app);
  }).then(app => {
    return parser(app);
  }).then(app => {
    return locals(app);
  }).then(app => {
    return authenticated(app);
  }).then(app => {
    return staticFiles(app);
  });
};
<|endoftext|>