').addClass(settings.timer_progress_class));
+ timer_container.addClass(settings.timer_paused_class);
+ container.append(timer_container);
+ }
+
+ if (settings.slide_number) {
+ number_container = $('
').addClass(settings.slide_number_class);
+ number_container.append('
' + settings.slide_number_text + '
');
+ container.append(number_container);
+ }
+
+ if (settings.bullets) {
+ bullets_container = $('
').addClass(settings.bullets_container_class);
+ container.append(bullets_container);
+ bullets_container.wrap('
');
+ self.slides().each(function (idx, el) {
+ var bullet = $('').attr('data-orbit-slide', idx).on('click', self.link_bullet);;
+ bullets_container.append(bullet);
+ });
+ }
+
+ };
+
+ self._goto = function (next_idx, start_timer) {
+ // if (locked) {return false;}
+ if (next_idx === idx) {return false;}
+ if (typeof timer === 'object') {timer.restart();}
+ var slides = self.slides();
+
+ var dir = 'next';
+ locked = true;
+ if (next_idx < idx) {dir = 'prev';}
+ if (next_idx >= slides.length) {
+ if (!settings.circular) {
+ return false;
+ }
+ next_idx = 0;
+ } else if (next_idx < 0) {
+ if (!settings.circular) {
+ return false;
+ }
+ next_idx = slides.length - 1;
+ }
+
+ var current = $(slides.get(idx));
+ var next = $(slides.get(next_idx));
+
+ current.css('zIndex', 2);
+ current.removeClass(settings.active_slide_class);
+ next.css('zIndex', 4).addClass(settings.active_slide_class);
+
+ slides_container.trigger('before-slide-change.fndtn.orbit');
+ settings.before_slide_change();
+ self.update_active_link(next_idx);
+
+ var callback = function () {
+ var unlock = function () {
+ idx = next_idx;
+ locked = false;
+ if (start_timer === true) {timer = self.create_timer(); timer.start();}
+ self.update_slide_number(idx);
+ slides_container.trigger('after-slide-change.fndtn.orbit', [{slide_number : idx, total_slides : slides.length}]);
+ settings.after_slide_change(idx, slides.length);
+ };
+ if (slides_container.outerHeight() != next.outerHeight() && settings.variable_height) {
+ slides_container.animate({'height': next.outerHeight()}, 250, 'linear', unlock);
+ } else {
+ unlock();
+ }
+ };
+
+ if (slides.length === 1) {callback(); return false;}
+
+ var start_animation = function () {
+ if (dir === 'next') {animate.next(current, next, callback);}
+ if (dir === 'prev') {animate.prev(current, next, callback);}
+ };
+
+ if (next.outerHeight() > slides_container.outerHeight() && settings.variable_height) {
+ slides_container.animate({'height': next.outerHeight()}, 250, 'linear', start_animation);
+ } else {
+ start_animation();
+ }
+ };
+
+ self.next = function (e) {
+ e.stopImmediatePropagation();
+ e.preventDefault();
+ self._goto(idx + 1);
+ };
+
+ self.prev = function (e) {
+ e.stopImmediatePropagation();
+ e.preventDefault();
+ self._goto(idx - 1);
+ };
+
+ self.link_custom = function (e) {
+ e.preventDefault();
+ var link = $(this).attr('data-orbit-link');
+ if ((typeof link === 'string') && (link = $.trim(link)) != '') {
+ var slide = container.find('[data-orbit-slide=' + link + ']');
+ if (slide.index() != -1) {self._goto(slide.index());}
+ }
+ };
+
+ self.link_bullet = function (e) {
+ var index = $(this).attr('data-orbit-slide');
+ if ((typeof index === 'string') && (index = $.trim(index)) != '') {
+ if (isNaN(parseInt(index))) {
+ var slide = container.find('[data-orbit-slide=' + index + ']');
+ if (slide.index() != -1) {self._goto(slide.index() + 1);}
+ } else {
+ self._goto(parseInt(index));
+ }
+ }
+
+ }
+
+ self.timer_callback = function () {
+ self._goto(idx + 1, true);
+ }
+
+ self.compute_dimensions = function () {
+ var current = $(self.slides().get(idx));
+ var h = current.outerHeight();
+ if (!settings.variable_height) {
+ self.slides().each(function(){
+ if ($(this).outerHeight() > h) { h = $(this).outerHeight(); }
+ });
+ }
+ slides_container.height(h);
+ };
+
+ self.create_timer = function () {
+ var t = new Timer(
+ container.find('.' + settings.timer_container_class),
+ settings,
+ self.timer_callback
+ );
+ return t;
+ };
+
+ self.stop_timer = function () {
+ if (typeof timer === 'object') {
+ timer.stop();
+ }
+ };
+
+ self.toggle_timer = function () {
+ var t = container.find('.' + settings.timer_container_class);
+ if (t.hasClass(settings.timer_paused_class)) {
+ if (typeof timer === 'undefined') {timer = self.create_timer();}
+ timer.start();
+ } else {
+ if (typeof timer === 'object') {timer.stop();}
+ }
+ };
+
+ self.init = function () {
+ self.build_markup();
+ if (settings.timer) {
+ timer = self.create_timer();
+ Foundation.utils.image_loaded(this.slides().children('img'), timer.start);
+ }
+ animate = new FadeAnimation(settings, slides_container);
+ if (settings.animation === 'slide') {
+ animate = new SlideAnimation(settings, slides_container);
+ }
+
+ container.on('click', '.' + settings.next_class, self.next);
+ container.on('click', '.' + settings.prev_class, self.prev);
+
+ if (settings.next_on_click) {
+ container.on('click', '.' + settings.slides_container_class + ' [data-orbit-slide]', self.link_bullet);
+ }
+
+ container.on('click', self.toggle_timer);
+ if (settings.swipe) {
+ container.on('touchstart.fndtn.orbit', function (e) {
+ if (!e.touches) {e = e.originalEvent;}
+ var data = {
+ start_page_x : e.touches[0].pageX,
+ start_page_y : e.touches[0].pageY,
+ start_time : (new Date()).getTime(),
+ delta_x : 0,
+ is_scrolling : undefined
+ };
+ container.data('swipe-transition', data);
+ e.stopPropagation();
+ })
+ .on('touchmove.fndtn.orbit', function (e) {
+ if (!e.touches) {
+ e = e.originalEvent;
+ }
+ // Ignore pinch/zoom events
+ if (e.touches.length > 1 || e.scale && e.scale !== 1) {
+ return;
+ }
+
+ var data = container.data('swipe-transition');
+ if (typeof data === 'undefined') {data = {};}
+
+ data.delta_x = e.touches[0].pageX - data.start_page_x;
+
+ if ( typeof data.is_scrolling === 'undefined') {
+ data.is_scrolling = !!( data.is_scrolling || Math.abs(data.delta_x) < Math.abs(e.touches[0].pageY - data.start_page_y) );
+ }
+
+ if (!data.is_scrolling && !data.active) {
+ e.preventDefault();
+ var direction = (data.delta_x < 0) ? (idx + 1) : (idx - 1);
+ data.active = true;
+ self._goto(direction);
+ }
+ })
+ .on('touchend.fndtn.orbit', function (e) {
+ container.data('swipe-transition', {});
+ e.stopPropagation();
+ })
+ }
+ container.on('mouseenter.fndtn.orbit', function (e) {
+ if (settings.timer && settings.pause_on_hover) {
+ self.stop_timer();
+ }
+ })
+ .on('mouseleave.fndtn.orbit', function (e) {
+ if (settings.timer && settings.resume_on_mouseout) {
+ timer.start();
+ }
+ });
+
+ $(document).on('click', '[data-orbit-link]', self.link_custom);
+ $(window).on('load resize', self.compute_dimensions);
+ Foundation.utils.image_loaded(this.slides().children('img'), self.compute_dimensions);
+ Foundation.utils.image_loaded(this.slides().children('img'), function () {
+ container.prev('.' + settings.preloader_class).css('display', 'none');
+ self.update_slide_number(0);
+ self.update_active_link(0);
+ slides_container.trigger('ready.fndtn.orbit');
+ });
+ };
+
+ self.init();
+ };
+
+ var Timer = function (el, settings, callback) {
+ var self = this,
+ duration = settings.timer_speed,
+ progress = el.find('.' + settings.timer_progress_class),
+ start,
+ timeout,
+ left = -1;
+
+ this.update_progress = function (w) {
+ var new_progress = progress.clone();
+ new_progress.attr('style', '');
+ new_progress.css('width', w + '%');
+ progress.replaceWith(new_progress);
+ progress = new_progress;
+ };
+
+ this.restart = function () {
+ clearTimeout(timeout);
+ el.addClass(settings.timer_paused_class);
+ left = -1;
+ self.update_progress(0);
+ };
+
+ this.start = function () {
+ if (!el.hasClass(settings.timer_paused_class)) {return true;}
+ left = (left === -1) ? duration : left;
+ el.removeClass(settings.timer_paused_class);
+ start = new Date().getTime();
+ progress.animate({'width' : '100%'}, left, 'linear');
+ timeout = setTimeout(function () {
+ self.restart();
+ callback();
+ }, left);
+ el.trigger('timer-started.fndtn.orbit')
+ };
+
+ this.stop = function () {
+ if (el.hasClass(settings.timer_paused_class)) {return true;}
+ clearTimeout(timeout);
+ el.addClass(settings.timer_paused_class);
+ var end = new Date().getTime();
+ left = left - (end - start);
+ var w = 100 - ((left / duration) * 100);
+ self.update_progress(w);
+ el.trigger('timer-stopped.fndtn.orbit');
+ };
+ };
+
+ var SlideAnimation = function (settings, container) {
+ var duration = settings.animation_speed;
+ var is_rtl = ($('html[dir=rtl]').length === 1);
+ var margin = is_rtl ? 'marginRight' : 'marginLeft';
+ var animMargin = {};
+ animMargin[margin] = '0%';
+
+ this.next = function (current, next, callback) {
+ current.animate({marginLeft : '-100%'}, duration);
+ next.animate(animMargin, duration, function () {
+ current.css(margin, '100%');
+ callback();
+ });
+ };
+
+ this.prev = function (current, prev, callback) {
+ current.animate({marginLeft : '100%'}, duration);
+ prev.css(margin, '-100%');
+ prev.animate(animMargin, duration, function () {
+ current.css(margin, '100%');
+ callback();
+ });
+ };
+ };
+
+ var FadeAnimation = function (settings, container) {
+ var duration = settings.animation_speed;
+ var is_rtl = ($('html[dir=rtl]').length === 1);
+ var margin = is_rtl ? 'marginRight' : 'marginLeft';
+
+ this.next = function (current, next, callback) {
+ next.css({'margin' : '0%', 'opacity' : '0.01'});
+ next.animate({'opacity' :'1'}, duration, 'linear', function () {
+ current.css('margin', '100%');
+ callback();
+ });
+ };
+
+ this.prev = function (current, prev, callback) {
+ prev.css({'margin' : '0%', 'opacity' : '0.01'});
+ prev.animate({'opacity' : '1'}, duration, 'linear', function () {
+ current.css('margin', '100%');
+ callback();
+ });
+ };
+ };
+
+ Foundation.libs = Foundation.libs || {};
+
+ Foundation.libs.orbit = {
+ name : 'orbit',
+
+ version : '5.5.1',
+
+ settings : {
+ animation : 'slide',
+ timer_speed : 10000,
+ pause_on_hover : true,
+ resume_on_mouseout : false,
+ next_on_click : true,
+ animation_speed : 500,
+ stack_on_small : false,
+ navigation_arrows : true,
+ slide_number : true,
+ slide_number_text : 'of',
+ container_class : 'orbit-container',
+ stack_on_small_class : 'orbit-stack-on-small',
+ next_class : 'orbit-next',
+ prev_class : 'orbit-prev',
+ timer_container_class : 'orbit-timer',
+ timer_paused_class : 'paused',
+ timer_progress_class : 'orbit-progress',
+ slides_container_class : 'orbit-slides-container',
+ preloader_class : 'preloader',
+ slide_selector : '*',
+ bullets_container_class : 'orbit-bullets',
+ bullets_active_class : 'active',
+ slide_number_class : 'orbit-slide-number',
+ caption_class : 'orbit-caption',
+ active_slide_class : 'active',
+ orbit_transition_class : 'orbit-transitioning',
+ bullets : true,
+ circular : true,
+ timer : true,
+ variable_height : false,
+ swipe : true,
+ before_slide_change : noop,
+ after_slide_change : noop
+ },
+
+ init : function (scope, method, options) {
+ var self = this;
+ this.bindings(method, options);
+ },
+
+ events : function (instance) {
+ var orbit_instance = new Orbit(this.S(instance), this.S(instance).data('orbit-init'));
+ this.S(instance).data(this.name + '-instance', orbit_instance);
+ },
+
+ reflow : function () {
+ var self = this;
+
+ if (self.S(self.scope).is('[data-orbit]')) {
+ var $el = self.S(self.scope);
+ var instance = $el.data(self.name + '-instance');
+ instance.compute_dimensions();
+ } else {
+ self.S('[data-orbit]', self.scope).each(function (idx, el) {
+ var $el = self.S(el);
+ var opts = self.data_options($el);
+ var instance = $el.data(self.name + '-instance');
+ instance.compute_dimensions();
+ });
+ }
+ }
+ };
+
+}(jQuery, window, window.document));
+
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.reveal = {
+ name : 'reveal',
+
+ version : '5.5.1',
+
+ locked : false,
+
+ settings : {
+ animation : 'fadeAndPop',
+ animation_speed : 250,
+ close_on_background_click : true,
+ close_on_esc : true,
+ dismiss_modal_class : 'close-reveal-modal',
+ multiple_opened : false,
+ bg_class : 'reveal-modal-bg',
+ root_element : 'body',
+ open : function(){},
+ opened : function(){},
+ close : function(){},
+ closed : function(){},
+ bg : $('.reveal-modal-bg'),
+ css : {
+ open : {
+ 'opacity' : 0,
+ 'visibility' : 'visible',
+ 'display' : 'block'
+ },
+ close : {
+ 'opacity' : 1,
+ 'visibility' : 'hidden',
+ 'display' : 'none'
+ }
+ }
+ },
+
+ init : function (scope, method, options) {
+ $.extend(true, this.settings, method, options);
+ this.bindings(method, options);
+ },
+
+ events : function (scope) {
+ var self = this,
+ S = self.S;
+
+ S(this.scope)
+ .off('.reveal')
+ .on('click.fndtn.reveal', '[' + this.add_namespace('data-reveal-id') + ']:not([disabled])', function (e) {
+ e.preventDefault();
+
+ if (!self.locked) {
+ var element = S(this),
+ ajax = element.data(self.data_attr('reveal-ajax'));
+
+ self.locked = true;
+
+ if (typeof ajax === 'undefined') {
+ self.open.call(self, element);
+ } else {
+ var url = ajax === true ? element.attr('href') : ajax;
+
+ self.open.call(self, element, {url : url});
+ }
+ }
+ });
+
+ S(document)
+ .on('click.fndtn.reveal', this.close_targets(), function (e) {
+ e.preventDefault();
+ if (!self.locked) {
+ var settings = S('[' + self.attr_name() + '].open').data(self.attr_name(true) + '-init') || self.settings,
+ bg_clicked = S(e.target)[0] === S('.' + settings.bg_class)[0];
+
+ if (bg_clicked) {
+ if (settings.close_on_background_click) {
+ e.stopPropagation();
+ } else {
+ return;
+ }
+ }
+
+ self.locked = true;
+ self.close.call(self, bg_clicked ? S('[' + self.attr_name() + '].open') : S(this).closest('[' + self.attr_name() + ']'));
+ }
+ });
+
+ if (S('[' + self.attr_name() + ']', this.scope).length > 0) {
+ S(this.scope)
+ // .off('.reveal')
+ .on('open.fndtn.reveal', this.settings.open)
+ .on('opened.fndtn.reveal', this.settings.opened)
+ .on('opened.fndtn.reveal', this.open_video)
+ .on('close.fndtn.reveal', this.settings.close)
+ .on('closed.fndtn.reveal', this.settings.closed)
+ .on('closed.fndtn.reveal', this.close_video);
+ } else {
+ S(this.scope)
+ // .off('.reveal')
+ .on('open.fndtn.reveal', '[' + self.attr_name() + ']', this.settings.open)
+ .on('opened.fndtn.reveal', '[' + self.attr_name() + ']', this.settings.opened)
+ .on('opened.fndtn.reveal', '[' + self.attr_name() + ']', this.open_video)
+ .on('close.fndtn.reveal', '[' + self.attr_name() + ']', this.settings.close)
+ .on('closed.fndtn.reveal', '[' + self.attr_name() + ']', this.settings.closed)
+ .on('closed.fndtn.reveal', '[' + self.attr_name() + ']', this.close_video);
+ }
+
+ return true;
+ },
+
+ // PATCH #3: turning on key up capture only when a reveal window is open
+ key_up_on : function (scope) {
+ var self = this;
+
+ // PATCH #1: fixing multiple keyup event trigger from single key press
+ self.S('body').off('keyup.fndtn.reveal').on('keyup.fndtn.reveal', function ( event ) {
+ var open_modal = self.S('[' + self.attr_name() + '].open'),
+ settings = open_modal.data(self.attr_name(true) + '-init') || self.settings ;
+ // PATCH #2: making sure that the close event can be called only while unlocked,
+ // so that multiple keyup.fndtn.reveal events don't prevent clean closing of the reveal window.
+ if ( settings && event.which === 27 && settings.close_on_esc && !self.locked) { // 27 is the keycode for the Escape key
+ self.close.call(self, open_modal);
+ }
+ });
+
+ return true;
+ },
+
+ // PATCH #3: turning on key up capture only when a reveal window is open
+ key_up_off : function (scope) {
+ this.S('body').off('keyup.fndtn.reveal');
+ return true;
+ },
+
+ open : function (target, ajax_settings) {
+ var self = this,
+ modal;
+
+ if (target) {
+ if (typeof target.selector !== 'undefined') {
+ // Find the named node; only use the first one found, since the rest of the code assumes there's only one node
+ modal = self.S('#' + target.data(self.data_attr('reveal-id'))).first();
+ } else {
+ modal = self.S(this.scope);
+
+ ajax_settings = target;
+ }
+ } else {
+ modal = self.S(this.scope);
+ }
+
+ var settings = modal.data(self.attr_name(true) + '-init');
+ settings = settings || this.settings;
+
+ if (modal.hasClass('open') && target.attr('data-reveal-id') == modal.attr('id')) {
+ return self.close(modal);
+ }
+
+ if (!modal.hasClass('open')) {
+ var open_modal = self.S('[' + self.attr_name() + '].open');
+
+ if (typeof modal.data('css-top') === 'undefined') {
+ modal.data('css-top', parseInt(modal.css('top'), 10))
+ .data('offset', this.cache_offset(modal));
+ }
+
+ this.key_up_on(modal); // PATCH #3: turning on key up capture only when a reveal window is open
+
+ modal.on('open.fndtn.reveal').trigger('open.fndtn.reveal');
+
+ if (open_modal.length < 1) {
+ this.toggle_bg(modal, true);
+ }
+
+ if (typeof ajax_settings === 'string') {
+ ajax_settings = {
+ url : ajax_settings
+ };
+ }
+
+ if (typeof ajax_settings === 'undefined' || !ajax_settings.url) {
+ if (open_modal.length > 0) {
+ if (settings.multiple_opened) {
+ this.to_back(open_modal);
+ } else {
+ this.hide(open_modal, settings.css.close);
+ }
+ }
+
+ this.show(modal, settings.css.open);
+ } else {
+ var old_success = typeof ajax_settings.success !== 'undefined' ? ajax_settings.success : null;
+
+ $.extend(ajax_settings, {
+ success : function (data, textStatus, jqXHR) {
+ if ( $.isFunction(old_success) ) {
+ var result = old_success(data, textStatus, jqXHR);
+ if (typeof result == 'string') {
+ data = result;
+ }
+ }
+
+ modal.html(data);
+ self.S(modal).foundation('section', 'reflow');
+ self.S(modal).children().foundation();
+
+ if (open_modal.length > 0) {
+ if (settings.multiple_opened) {
+ this.to_back(open_modal);
+ } else {
+ this.hide(open_modal, settings.css.close);
+ }
+ }
+ self.show(modal, settings.css.open);
+ }
+ });
+
+ $.ajax(ajax_settings);
+ }
+ }
+ self.S(window).trigger('resize');
+ },
+
+ close : function (modal) {
+ var modal = modal && modal.length ? modal : this.S(this.scope),
+ open_modals = this.S('[' + this.attr_name() + '].open'),
+ settings = modal.data(this.attr_name(true) + '-init') || this.settings;
+
+ if (open_modals.length > 0) {
+ this.locked = true;
+ this.key_up_off(modal); // PATCH #3: turning on key up capture only when a reveal window is open
+ modal.trigger('close').trigger('close.fndtn.reveal');
+
+ if ((settings.multiple_opened && open_modals.length === 1) || !settings.multiple_opened || modal.length > 1) {
+ this.toggle_bg(modal, false);
+ this.to_front(modal);
+ }
+
+ if (settings.multiple_opened) {
+ this.hide(modal, settings.css.close, settings);
+ this.to_front($($.makeArray(open_modals).reverse()[1]));
+ } else {
+ this.hide(open_modals, settings.css.close, settings);
+ }
+ }
+ },
+
+ close_targets : function () {
+ var base = '.' + this.settings.dismiss_modal_class;
+
+ if (this.settings.close_on_background_click) {
+ return base + ', .' + this.settings.bg_class;
+ }
+
+ return base;
+ },
+
+ toggle_bg : function (modal, state) {
+ if (this.S('.' + this.settings.bg_class).length === 0) {
+ this.settings.bg = $('
', {'class': this.settings.bg_class})
+ .appendTo('body').hide();
+ }
+
+ var visible = this.settings.bg.filter(':visible').length > 0;
+ if ( state != visible ) {
+ if ( state == undefined ? visible : !state ) {
+ this.hide(this.settings.bg);
+ } else {
+ this.show(this.settings.bg);
+ }
+ }
+ },
+
+ show : function (el, css) {
+ // is modal
+ if (css) {
+ var settings = el.data(this.attr_name(true) + '-init') || this.settings,
+ root_element = settings.root_element;
+
+ if (el.parent(root_element).length === 0) {
+ var placeholder = el.wrap('
').parent();
+
+ el.on('closed.fndtn.reveal.wrapped', function () {
+ el.detach().appendTo(placeholder);
+ el.unwrap().unbind('closed.fndtn.reveal.wrapped');
+ });
+
+ el.detach().appendTo(root_element);
+ }
+
+ var animData = getAnimationData(settings.animation);
+ if (!animData.animate) {
+ this.locked = false;
+ }
+ if (animData.pop) {
+ css.top = $(window).scrollTop() - el.data('offset') + 'px';
+ var end_css = {
+ top: $(window).scrollTop() + el.data('css-top') + 'px',
+ opacity: 1
+ };
+
+ return setTimeout(function () {
+ return el
+ .css(css)
+ .animate(end_css, settings.animation_speed, 'linear', function () {
+ this.locked = false;
+ el.trigger('opened').trigger('opened.fndtn.reveal');
+ }.bind(this))
+ .addClass('open');
+ }.bind(this), settings.animation_speed / 2);
+ }
+
+ if (animData.fade) {
+ css.top = $(window).scrollTop() + el.data('css-top') + 'px';
+ var end_css = {opacity: 1};
+
+ return setTimeout(function () {
+ return el
+ .css(css)
+ .animate(end_css, settings.animation_speed, 'linear', function () {
+ this.locked = false;
+ el.trigger('opened').trigger('opened.fndtn.reveal');
+ }.bind(this))
+ .addClass('open');
+ }.bind(this), settings.animation_speed / 2);
+ }
+
+ return el.css(css).show().css({opacity : 1}).addClass('open').trigger('opened').trigger('opened.fndtn.reveal');
+ }
+
+ var settings = this.settings;
+
+ // should we animate the background?
+ if (getAnimationData(settings.animation).fade) {
+ return el.fadeIn(settings.animation_speed / 2);
+ }
+
+ this.locked = false;
+
+ return el.show();
+ },
+
+ to_back : function(el) {
+ el.addClass('toback');
+ },
+
+ to_front : function(el) {
+ el.removeClass('toback');
+ },
+
+ hide : function (el, css) {
+ // is modal
+ if (css) {
+ var settings = el.data(this.attr_name(true) + '-init');
+ settings = settings || this.settings;
+
+ var animData = getAnimationData(settings.animation);
+ if (!animData.animate) {
+ this.locked = false;
+ }
+ if (animData.pop) {
+ var end_css = {
+ top: - $(window).scrollTop() - el.data('offset') + 'px',
+ opacity: 0
+ };
+
+ return setTimeout(function () {
+ return el
+ .animate(end_css, settings.animation_speed, 'linear', function () {
+ this.locked = false;
+ el.css(css).trigger('closed').trigger('closed.fndtn.reveal');
+ }.bind(this))
+ .removeClass('open');
+ }.bind(this), settings.animation_speed / 2);
+ }
+
+ if (animData.fade) {
+ var end_css = {opacity : 0};
+
+ return setTimeout(function () {
+ return el
+ .animate(end_css, settings.animation_speed, 'linear', function () {
+ this.locked = false;
+ el.css(css).trigger('closed').trigger('closed.fndtn.reveal');
+ }.bind(this))
+ .removeClass('open');
+ }.bind(this), settings.animation_speed / 2);
+ }
+
+ return el.hide().css(css).removeClass('open').trigger('closed').trigger('closed.fndtn.reveal');
+ }
+
+ var settings = this.settings;
+
+ // should we animate the background?
+ if (getAnimationData(settings.animation).fade) {
+ return el.fadeOut(settings.animation_speed / 2);
+ }
+
+ return el.hide();
+ },
+
+ close_video : function (e) {
+ var video = $('.flex-video', e.target),
+ iframe = $('iframe', video);
+
+ if (iframe.length > 0) {
+ iframe.attr('data-src', iframe[0].src);
+ iframe.attr('src', iframe.attr('src'));
+ video.hide();
+ }
+ },
+
+ open_video : function (e) {
+ var video = $('.flex-video', e.target),
+ iframe = video.find('iframe');
+
+ if (iframe.length > 0) {
+ var data_src = iframe.attr('data-src');
+ if (typeof data_src === 'string') {
+ iframe[0].src = iframe.attr('data-src');
+ } else {
+ var src = iframe[0].src;
+ iframe[0].src = undefined;
+ iframe[0].src = src;
+ }
+ video.show();
+ }
+ },
+
+ data_attr : function (str) {
+ if (this.namespace.length > 0) {
+ return this.namespace + '-' + str;
+ }
+
+ return str;
+ },
+
+ cache_offset : function (modal) {
+ var offset = modal.show().height() + parseInt(modal.css('top'), 10);
+
+ modal.hide();
+
+ return offset;
+ },
+
+ off : function () {
+ $(this.scope).off('.fndtn.reveal');
+ },
+
+ reflow : function () {}
+ };
+
+ /*
+ * getAnimationData('popAndFade') // {animate: true, pop: true, fade: true}
+ * getAnimationData('fade') // {animate: true, pop: false, fade: true}
+ * getAnimationData('pop') // {animate: true, pop: true, fade: false}
+ * getAnimationData('foo') // {animate: false, pop: false, fade: false}
+ * getAnimationData(null) // {animate: false, pop: false, fade: false}
+ */
+ function getAnimationData(str) {
+ var fade = /fade/i.test(str);
+ var pop = /pop/i.test(str);
+ return {
+ animate : fade || pop,
+ pop : pop,
+ fade : fade
+ };
+ }
+}(jQuery, window, window.document));
+
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.slider = {
+ name : 'slider',
+
+ version : '5.5.1',
+
+ settings : {
+ start : 0,
+ end : 100,
+ step : 1,
+ precision : null,
+ initial : null,
+ display_selector : '',
+ vertical : false,
+ trigger_input_change : false,
+ on_change : function () {}
+ },
+
+ cache : {},
+
+ init : function (scope, method, options) {
+ Foundation.inherit(this, 'throttle');
+ this.bindings(method, options);
+ this.reflow();
+ },
+
+ events : function () {
+ var self = this;
+
+ $(this.scope)
+ .off('.slider')
+ .on('mousedown.fndtn.slider touchstart.fndtn.slider pointerdown.fndtn.slider',
+ '[' + self.attr_name() + ']:not(.disabled, [disabled]) .range-slider-handle', function (e) {
+ if (!self.cache.active) {
+ e.preventDefault();
+ self.set_active_slider($(e.target));
+ }
+ })
+ .on('mousemove.fndtn.slider touchmove.fndtn.slider pointermove.fndtn.slider', function (e) {
+ if (!!self.cache.active) {
+ e.preventDefault();
+ if ($.data(self.cache.active[0], 'settings').vertical) {
+ var scroll_offset = 0;
+ if (!e.pageY) {
+ scroll_offset = window.scrollY;
+ }
+ self.calculate_position(self.cache.active, self.get_cursor_position(e, 'y') + scroll_offset);
+ } else {
+ self.calculate_position(self.cache.active, self.get_cursor_position(e, 'x'));
+ }
+ }
+ })
+ .on('mouseup.fndtn.slider touchend.fndtn.slider pointerup.fndtn.slider', function (e) {
+ self.remove_active_slider();
+ })
+ .on('change.fndtn.slider', function (e) {
+ self.settings.on_change();
+ });
+
+ self.S(window)
+ .on('resize.fndtn.slider', self.throttle(function (e) {
+ self.reflow();
+ }, 300));
+ },
+
+ get_cursor_position : function (e, xy) {
+ var pageXY = 'page' + xy.toUpperCase(),
+ clientXY = 'client' + xy.toUpperCase(),
+ position;
+
+ if (typeof e[pageXY] !== 'undefined') {
+ position = e[pageXY];
+ } else if (typeof e.originalEvent[clientXY] !== 'undefined') {
+ position = e.originalEvent[clientXY];
+ } else if (e.originalEvent.touches && e.originalEvent.touches[0] && typeof e.originalEvent.touches[0][clientXY] !== 'undefined') {
+ position = e.originalEvent.touches[0][clientXY];
+ } else if (e.currentPoint && typeof e.currentPoint[xy] !== 'undefined') {
+ position = e.currentPoint[xy];
+ }
+
+ return position;
+ },
+
+ set_active_slider : function ($handle) {
+ this.cache.active = $handle;
+ },
+
+ remove_active_slider : function () {
+ this.cache.active = null;
+ },
+
+ calculate_position : function ($handle, cursor_x) {
+ var self = this,
+ settings = $.data($handle[0], 'settings'),
+ handle_l = $.data($handle[0], 'handle_l'),
+ handle_o = $.data($handle[0], 'handle_o'),
+ bar_l = $.data($handle[0], 'bar_l'),
+ bar_o = $.data($handle[0], 'bar_o');
+
+ requestAnimationFrame(function () {
+ var pct;
+
+ if (Foundation.rtl && !settings.vertical) {
+ pct = self.limit_to(((bar_o + bar_l - cursor_x) / bar_l), 0, 1);
+ } else {
+ pct = self.limit_to(((cursor_x - bar_o) / bar_l), 0, 1);
+ }
+
+ pct = settings.vertical ? 1 - pct : pct;
+
+ var norm = self.normalized_value(pct, settings.start, settings.end, settings.step, settings.precision);
+
+ self.set_ui($handle, norm);
+ });
+ },
+
+ set_ui : function ($handle, value) {
+ var settings = $.data($handle[0], 'settings'),
+ handle_l = $.data($handle[0], 'handle_l'),
+ bar_l = $.data($handle[0], 'bar_l'),
+ norm_pct = this.normalized_percentage(value, settings.start, settings.end),
+ handle_offset = norm_pct * (bar_l - handle_l) - 1,
+ progress_bar_length = norm_pct * 100,
+ $handle_parent = $handle.parent(),
+ $hidden_inputs = $handle.parent().children('input[type=hidden]');
+
+ if (Foundation.rtl && !settings.vertical) {
+ handle_offset = -handle_offset;
+ }
+
+ handle_offset = settings.vertical ? -handle_offset + bar_l - handle_l + 1 : handle_offset;
+ this.set_translate($handle, handle_offset, settings.vertical);
+
+ if (settings.vertical) {
+ $handle.siblings('.range-slider-active-segment').css('height', progress_bar_length + '%');
+ } else {
+ $handle.siblings('.range-slider-active-segment').css('width', progress_bar_length + '%');
+ }
+
+ $handle_parent.attr(this.attr_name(), value).trigger('change').trigger('change.fndtn.slider');
+
+ $hidden_inputs.val(value);
+ if (settings.trigger_input_change) {
+ $hidden_inputs.trigger('change');
+ }
+
+ if (!$handle[0].hasAttribute('aria-valuemin')) {
+ $handle.attr({
+ 'aria-valuemin' : settings.start,
+ 'aria-valuemax' : settings.end
+ });
+ }
+ $handle.attr('aria-valuenow', value);
+
+ if (settings.display_selector != '') {
+ $(settings.display_selector).each(function () {
+ if (this.hasOwnProperty('value')) {
+ $(this).val(value);
+ } else {
+ $(this).text(value);
+ }
+ });
+ }
+
+ },
+
+ normalized_percentage : function (val, start, end) {
+ return Math.min(1, (val - start) / (end - start));
+ },
+
+ normalized_value : function (val, start, end, step, precision) {
+ var range = end - start,
+ point = val * range,
+ mod = (point - (point % step)) / step,
+ rem = point % step,
+ round = ( rem >= step * 0.5 ? step : 0);
+ return ((mod * step + round) + start).toFixed(precision);
+ },
+
+ set_translate : function (ele, offset, vertical) {
+ if (vertical) {
+ $(ele)
+ .css('-webkit-transform', 'translateY(' + offset + 'px)')
+ .css('-moz-transform', 'translateY(' + offset + 'px)')
+ .css('-ms-transform', 'translateY(' + offset + 'px)')
+ .css('-o-transform', 'translateY(' + offset + 'px)')
+ .css('transform', 'translateY(' + offset + 'px)');
+ } else {
+ $(ele)
+ .css('-webkit-transform', 'translateX(' + offset + 'px)')
+ .css('-moz-transform', 'translateX(' + offset + 'px)')
+ .css('-ms-transform', 'translateX(' + offset + 'px)')
+ .css('-o-transform', 'translateX(' + offset + 'px)')
+ .css('transform', 'translateX(' + offset + 'px)');
+ }
+ },
+
+ limit_to : function (val, min, max) {
+ return Math.min(Math.max(val, min), max);
+ },
+
+ initialize_settings : function (handle) {
+ var settings = $.extend({}, this.settings, this.data_options($(handle).parent())),
+ decimal_places_match_result;
+
+ if (settings.precision === null) {
+ decimal_places_match_result = ('' + settings.step).match(/\.([\d]*)/);
+ settings.precision = decimal_places_match_result && decimal_places_match_result[1] ? decimal_places_match_result[1].length : 0;
+ }
+
+ if (settings.vertical) {
+ $.data(handle, 'bar_o', $(handle).parent().offset().top);
+ $.data(handle, 'bar_l', $(handle).parent().outerHeight());
+ $.data(handle, 'handle_o', $(handle).offset().top);
+ $.data(handle, 'handle_l', $(handle).outerHeight());
+ } else {
+ $.data(handle, 'bar_o', $(handle).parent().offset().left);
+ $.data(handle, 'bar_l', $(handle).parent().outerWidth());
+ $.data(handle, 'handle_o', $(handle).offset().left);
+ $.data(handle, 'handle_l', $(handle).outerWidth());
+ }
+
+ $.data(handle, 'bar', $(handle).parent());
+ $.data(handle, 'settings', settings);
+ },
+
+ set_initial_position : function ($ele) {
+ var settings = $.data($ele.children('.range-slider-handle')[0], 'settings'),
+ initial = ((typeof settings.initial == 'number' && !isNaN(settings.initial)) ? settings.initial : Math.floor((settings.end - settings.start) * 0.5 / settings.step) * settings.step + settings.start),
+ $handle = $ele.children('.range-slider-handle');
+ this.set_ui($handle, initial);
+ },
+
+ set_value : function (value) {
+ var self = this;
+ $('[' + self.attr_name() + ']', this.scope).each(function () {
+ $(this).attr(self.attr_name(), value);
+ });
+ if (!!$(this.scope).attr(self.attr_name())) {
+ $(this.scope).attr(self.attr_name(), value);
+ }
+ self.reflow();
+ },
+
+ reflow : function () {
+ var self = this;
+ self.S('[' + this.attr_name() + ']').each(function () {
+ var handle = $(this).children('.range-slider-handle')[0],
+ val = $(this).attr(self.attr_name());
+ self.initialize_settings(handle);
+
+ if (val) {
+ self.set_ui($(handle), parseFloat(val));
+ } else {
+ self.set_initial_position($(this));
+ }
+ });
+ }
+ };
+
+}(jQuery, window, window.document));
+
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.tab = {
+ name : 'tab',
+
+ version : '5.5.1',
+
+ settings : {
+ active_class : 'active',
+ callback : function () {},
+ deep_linking : false,
+ scroll_to_content : true,
+ is_hover : false
+ },
+
+ default_tab_hashes : [],
+
+ init : function (scope, method, options) {
+ var self = this,
+ S = this.S;
+
+ this.bindings(method, options);
+
+ // store the initial href, which is used to allow correct behaviour of the
+ // browser back button when deep linking is turned on.
+ self.entry_location = window.location.href;
+
+ this.handle_location_hash_change();
+
+ // Store the default active tabs which will be referenced when the
+ // location hash is absent, as in the case of navigating the tabs and
+ // returning to the first viewing via the browser Back button.
+ S('[' + this.attr_name() + '] > .active > a', this.scope).each(function () {
+ self.default_tab_hashes.push(this.hash);
+ });
+ },
+
+ events : function () {
+ var self = this,
+ S = this.S;
+
+ var usual_tab_behavior = function (e) {
+ var settings = S(this).closest('[' + self.attr_name() + ']').data(self.attr_name(true) + '-init');
+ if (!settings.is_hover || Modernizr.touch) {
+ e.preventDefault();
+ e.stopPropagation();
+ self.toggle_active_tab(S(this).parent());
+ }
+ };
+
+ S(this.scope)
+ .off('.tab')
+ // Click event: tab title
+ .on('focus.fndtn.tab', '[' + this.attr_name() + '] > * > a', usual_tab_behavior )
+ .on('click.fndtn.tab', '[' + this.attr_name() + '] > * > a', usual_tab_behavior )
+ // Hover event: tab title
+ .on('mouseenter.fndtn.tab', '[' + this.attr_name() + '] > * > a', function (e) {
+ var settings = S(this).closest('[' + self.attr_name() + ']').data(self.attr_name(true) + '-init');
+ if (settings.is_hover) {
+ self.toggle_active_tab(S(this).parent());
+ }
+ });
+
+ // Location hash change event
+ S(window).on('hashchange.fndtn.tab', function (e) {
+ e.preventDefault();
+ self.handle_location_hash_change();
+ });
+ },
+
+ handle_location_hash_change : function () {
+
+ var self = this,
+ S = this.S;
+
+ S('[' + this.attr_name() + ']', this.scope).each(function () {
+ var settings = S(this).data(self.attr_name(true) + '-init');
+ if (settings.deep_linking) {
+ // Match the location hash to a label
+ var hash;
+ if (settings.scroll_to_content) {
+ hash = self.scope.location.hash;
+ } else {
+ // prefix the hash to prevent anchor scrolling
+ hash = self.scope.location.hash.replace('fndtn-', '');
+ }
+ if (hash != '') {
+ // Check whether the location hash references a tab content div or
+ // another element on the page (inside or outside the tab content div)
+ var hash_element = S(hash);
+ if (hash_element.hasClass('content') && hash_element.parent().hasClass('tabs-content')) {
+ // Tab content div
+ self.toggle_active_tab($('[' + self.attr_name() + '] > * > a[href=' + hash + ']').parent());
+ } else {
+ // Not the tab content div. If inside the tab content, find the
+ // containing tab and toggle it as active.
+ var hash_tab_container_id = hash_element.closest('.content').attr('id');
+ if (hash_tab_container_id != undefined) {
+ self.toggle_active_tab($('[' + self.attr_name() + '] > * > a[href=#' + hash_tab_container_id + ']').parent(), hash);
+ }
+ }
+ } else {
+ // Reference the default tab hashes which were initialized in the init function
+ for (var ind = 0; ind < self.default_tab_hashes.length; ind++) {
+ self.toggle_active_tab($('[' + self.attr_name() + '] > * > a[href=' + self.default_tab_hashes[ind] + ']').parent());
+ }
+ }
+ }
+ });
+ },
+
+ toggle_active_tab : function (tab, location_hash) {
+ var self = this,
+ S = self.S,
+ tabs = tab.closest('[' + this.attr_name() + ']'),
+ tab_link = tab.find('a'),
+ anchor = tab.children('a').first(),
+ target_hash = '#' + anchor.attr('href').split('#')[1],
+ target = S(target_hash),
+ siblings = tab.siblings(),
+ settings = tabs.data(this.attr_name(true) + '-init'),
+ interpret_keyup_action = function (e) {
+ // Light modification of Heydon Pickering's Practical ARIA Examples: http://heydonworks.com/practical_aria_examples/js/a11y.js
+
+ // define current, previous and next (possible) tabs
+
+ var $original = $(this);
+ var $prev = $(this).parents('li').prev().children('[role="tab"]');
+ var $next = $(this).parents('li').next().children('[role="tab"]');
+ var $target;
+
+ // find the direction (prev or next)
+
+ switch (e.keyCode) {
+ case 37:
+ $target = $prev;
+ break;
+ case 39:
+ $target = $next;
+ break;
+ default:
+ $target = false
+ break;
+ }
+
+ if ($target.length) {
+ $original.attr({
+ 'tabindex' : '-1',
+ 'aria-selected' : null
+ });
+ $target.attr({
+ 'tabindex' : '0',
+ 'aria-selected' : true
+ }).focus();
+ }
+
+ // Hide panels
+
+ $('[role="tabpanel"]')
+ .attr('aria-hidden', 'true');
+
+ // Show panel which corresponds to target
+
+ $('#' + $(document.activeElement).attr('href').substring(1))
+ .attr('aria-hidden', null);
+
+ },
+ go_to_hash = function(hash) {
+ // This function allows correct behaviour of the browser's back button when deep linking is enabled. Without it
+ // the user would get continually redirected to the default hash.
+ var is_entry_location = window.location.href === self.entry_location,
+ default_hash = settings.scroll_to_content ? self.default_tab_hashes[0] : is_entry_location ? window.location.hash :'fndtn-' + self.default_tab_hashes[0].replace('#', '')
+
+ if (!(is_entry_location && hash === default_hash)) {
+ window.location.hash = hash;
+ }
+ };
+
+ // allow usage of data-tab-content attribute instead of href
+ if (S(this).data(this.data_attr('tab-content'))) {
+ target_hash = '#' + S(this).data(this.data_attr('tab-content')).split('#')[1];
+ target = S(target_hash);
+ }
+
+ if (settings.deep_linking) {
+
+ if (settings.scroll_to_content) {
+
+ // retain current hash to scroll to content
+ go_to_hash(location_hash || target_hash);
+
+ if (location_hash == undefined || location_hash == target_hash) {
+ tab.parent()[0].scrollIntoView();
+ } else {
+ S(target_hash)[0].scrollIntoView();
+ }
+ } else {
+ // prefix the hashes so that the browser doesn't scroll down
+ if (location_hash != undefined) {
+ go_to_hash('fndtn-' + location_hash.replace('#', ''));
+ } else {
+ go_to_hash('fndtn-' + target_hash.replace('#', ''));
+ }
+ }
+ }
+
+ // WARNING: The activation and deactivation of the tab content must
+ // occur after the deep linking in order to properly refresh the browser
+ // window (notably in Chrome).
+ // Clean up multiple attr instances to done once
+ tab.addClass(settings.active_class).triggerHandler('opened');
+ tab_link.attr({'aria-selected' : 'true', tabindex : 0});
+ siblings.removeClass(settings.active_class)
+ siblings.find('a').attr({'aria-selected' : 'false', tabindex : -1});
+ target.siblings().removeClass(settings.active_class).attr({'aria-hidden' : 'true', tabindex : -1});
+ target.addClass(settings.active_class).attr('aria-hidden', 'false').removeAttr('tabindex');
+ settings.callback(tab);
+ target.triggerHandler('toggled', [tab]);
+ tabs.triggerHandler('toggled', [target]);
+
+ tab_link.off('keydown').on('keydown', interpret_keyup_action );
+ },
+
+ data_attr : function (str) {
+ if (this.namespace.length > 0) {
+ return this.namespace + '-' + str;
+ }
+
+ return str;
+ },
+
+ off : function () {},
+
+ reflow : function () {}
+ };
+}(jQuery, window, window.document));
+
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.tooltip = {
+ name : 'tooltip',
+
+ version : '5.5.1',
+
+ settings : {
+ additional_inheritable_classes : [],
+ tooltip_class : '.tooltip',
+ append_to : 'body',
+ touch_close_text : 'Tap To Close',
+ disable_for_touch : false,
+ hover_delay : 200,
+ show_on : 'all',
+ tip_template : function (selector, content) {
+ return '' + content + ' ';
+ }
+ },
+
+ cache : {},
+
+ init : function (scope, method, options) {
+ Foundation.inherit(this, 'random_str');
+ this.bindings(method, options);
+ },
+
+ should_show : function (target, tip) {
+ var settings = $.extend({}, this.settings, this.data_options(target));
+
+ if (settings.show_on === 'all') {
+ return true;
+ } else if (this.small() && settings.show_on === 'small') {
+ return true;
+ } else if (this.medium() && settings.show_on === 'medium') {
+ return true;
+ } else if (this.large() && settings.show_on === 'large') {
+ return true;
+ }
+ return false;
+ },
+
+ medium : function () {
+ return matchMedia(Foundation.media_queries['medium']).matches;
+ },
+
+ large : function () {
+ return matchMedia(Foundation.media_queries['large']).matches;
+ },
+
+ events : function (instance) {
+ var self = this,
+ S = self.S;
+
+ self.create(this.S(instance));
+
+ $(this.scope)
+ .off('.tooltip')
+ .on('mouseenter.fndtn.tooltip mouseleave.fndtn.tooltip touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip',
+ '[' + this.attr_name() + ']', function (e) {
+ var $this = S(this),
+ settings = $.extend({}, self.settings, self.data_options($this)),
+ is_touch = false;
+
+ if (Modernizr.touch && /touchstart|MSPointerDown/i.test(e.type) && S(e.target).is('a')) {
+ return false;
+ }
+
+ if (/mouse/i.test(e.type) && self.ie_touch(e)) {
+ return false;
+ }
+
+ if ($this.hasClass('open')) {
+ if (Modernizr.touch && /touchstart|MSPointerDown/i.test(e.type)) {
+ e.preventDefault();
+ }
+ self.hide($this);
+ } else {
+ if (settings.disable_for_touch && Modernizr.touch && /touchstart|MSPointerDown/i.test(e.type)) {
+ return;
+ } else if (!settings.disable_for_touch && Modernizr.touch && /touchstart|MSPointerDown/i.test(e.type)) {
+ e.preventDefault();
+ S(settings.tooltip_class + '.open').hide();
+ is_touch = true;
+ }
+
+ if (/enter|over/i.test(e.type)) {
+ this.timer = setTimeout(function () {
+ var tip = self.showTip($this);
+ }.bind(this), self.settings.hover_delay);
+ } else if (e.type === 'mouseout' || e.type === 'mouseleave') {
+ clearTimeout(this.timer);
+ self.hide($this);
+ } else {
+ self.showTip($this);
+ }
+ }
+ })
+ .on('mouseleave.fndtn.tooltip touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip', '[' + this.attr_name() + '].open', function (e) {
+ if (/mouse/i.test(e.type) && self.ie_touch(e)) {
+ return false;
+ }
+
+ if ($(this).data('tooltip-open-event-type') == 'touch' && e.type == 'mouseleave') {
+ return;
+ } else if ($(this).data('tooltip-open-event-type') == 'mouse' && /MSPointerDown|touchstart/i.test(e.type)) {
+ self.convert_to_touch($(this));
+ } else {
+ self.hide($(this));
+ }
+ })
+ .on('DOMNodeRemoved DOMAttrModified', '[' + this.attr_name() + ']:not(a)', function (e) {
+ self.hide(S(this));
+ });
+ },
+
+ ie_touch : function (e) {
+ // How do I distinguish between IE11 and Windows Phone 8?????
+ return false;
+ },
+
+ showTip : function ($target) {
+ var $tip = this.getTip($target);
+ if (this.should_show($target, $tip)) {
+ return this.show($target);
+ }
+ return;
+ },
+
+ getTip : function ($target) {
+ var selector = this.selector($target),
+ settings = $.extend({}, this.settings, this.data_options($target)),
+ tip = null;
+
+ if (selector) {
+ tip = this.S('span[data-selector="' + selector + '"]' + settings.tooltip_class);
+ }
+
+ return (typeof tip === 'object') ? tip : false;
+ },
+
+ selector : function ($target) {
+ var id = $target.attr('id'),
+ dataSelector = $target.attr(this.attr_name()) || $target.attr('data-selector');
+
+ if ((id && id.length < 1 || !id) && typeof dataSelector != 'string') {
+ dataSelector = this.random_str(6);
+ $target
+ .attr('data-selector', dataSelector)
+ .attr('aria-describedby', dataSelector);
+ }
+
+ return (id && id.length > 0) ? id : dataSelector;
+ },
+
+ create : function ($target) {
+ var self = this,
+ settings = $.extend({}, this.settings, this.data_options($target)),
+ tip_template = this.settings.tip_template;
+
+ if (typeof settings.tip_template === 'string' && window.hasOwnProperty(settings.tip_template)) {
+ tip_template = window[settings.tip_template];
+ }
+
+ var $tip = $(tip_template(this.selector($target), $('
').html($target.attr('title')).html())),
+ classes = this.inheritable_classes($target);
+
+ $tip.addClass(classes).appendTo(settings.append_to);
+
+ if (Modernizr.touch) {
+ $tip.append('' + settings.touch_close_text + ' ');
+ $tip.on('touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip', function (e) {
+ self.hide($target);
+ });
+ }
+
+ $target.removeAttr('title').attr('title', '');
+ },
+
+ reposition : function (target, tip, classes) {
+ var width, nub, nubHeight, nubWidth, column, objPos;
+
+ tip.css('visibility', 'hidden').show();
+
+ width = target.data('width');
+ nub = tip.children('.nub');
+ nubHeight = nub.outerHeight();
+ nubWidth = nub.outerHeight();
+
+ if (this.small()) {
+ tip.css({'width' : '100%'});
+ } else {
+ tip.css({'width' : (width) ? width : 'auto'});
+ }
+
+ objPos = function (obj, top, right, bottom, left, width) {
+ return obj.css({
+ 'top' : (top) ? top : 'auto',
+ 'bottom' : (bottom) ? bottom : 'auto',
+ 'left' : (left) ? left : 'auto',
+ 'right' : (right) ? right : 'auto'
+ }).end();
+ };
+
+ objPos(tip, (target.offset().top + target.outerHeight() + 10), 'auto', 'auto', target.offset().left);
+
+ if (this.small()) {
+ objPos(tip, (target.offset().top + target.outerHeight() + 10), 'auto', 'auto', 12.5, $(this.scope).width());
+ tip.addClass('tip-override');
+ objPos(nub, -nubHeight, 'auto', 'auto', target.offset().left);
+ } else {
+ var left = target.offset().left;
+ if (Foundation.rtl) {
+ nub.addClass('rtl');
+ left = target.offset().left + target.outerWidth() - tip.outerWidth();
+ }
+ objPos(tip, (target.offset().top + target.outerHeight() + 10), 'auto', 'auto', left);
+ tip.removeClass('tip-override');
+ if (classes && classes.indexOf('tip-top') > -1) {
+ if (Foundation.rtl) {
+ nub.addClass('rtl');
+ }
+ objPos(tip, (target.offset().top - tip.outerHeight()), 'auto', 'auto', left)
+ .removeClass('tip-override');
+ } else if (classes && classes.indexOf('tip-left') > -1) {
+ objPos(tip, (target.offset().top + (target.outerHeight() / 2) - (tip.outerHeight() / 2)), 'auto', 'auto', (target.offset().left - tip.outerWidth() - nubHeight))
+ .removeClass('tip-override');
+ nub.removeClass('rtl');
+ } else if (classes && classes.indexOf('tip-right') > -1) {
+ objPos(tip, (target.offset().top + (target.outerHeight() / 2) - (tip.outerHeight() / 2)), 'auto', 'auto', (target.offset().left + target.outerWidth() + nubHeight))
+ .removeClass('tip-override');
+ nub.removeClass('rtl');
+ }
+ }
+
+ tip.css('visibility', 'visible').hide();
+ },
+
+ small : function () {
+ return matchMedia(Foundation.media_queries.small).matches &&
+ !matchMedia(Foundation.media_queries.medium).matches;
+ },
+
+ inheritable_classes : function ($target) {
+ var settings = $.extend({}, this.settings, this.data_options($target)),
+ inheritables = ['tip-top', 'tip-left', 'tip-bottom', 'tip-right', 'radius', 'round'].concat(settings.additional_inheritable_classes),
+ classes = $target.attr('class'),
+ filtered = classes ? $.map(classes.split(' '), function (el, i) {
+ if ($.inArray(el, inheritables) !== -1) {
+ return el;
+ }
+ }).join(' ') : '';
+
+ return $.trim(filtered);
+ },
+
+ convert_to_touch : function ($target) {
+ var self = this,
+ $tip = self.getTip($target),
+ settings = $.extend({}, self.settings, self.data_options($target));
+
+ if ($tip.find('.tap-to-close').length === 0) {
+ $tip.append('' + settings.touch_close_text + ' ');
+ $tip.on('click.fndtn.tooltip.tapclose touchstart.fndtn.tooltip.tapclose MSPointerDown.fndtn.tooltip.tapclose', function (e) {
+ self.hide($target);
+ });
+ }
+
+ $target.data('tooltip-open-event-type', 'touch');
+ },
+
+ show : function ($target) {
+ var $tip = this.getTip($target);
+
+ if ($target.data('tooltip-open-event-type') == 'touch') {
+ this.convert_to_touch($target);
+ }
+
+ this.reposition($target, $tip, $target.attr('class'));
+ $target.addClass('open');
+ $tip.fadeIn(150);
+ },
+
+ hide : function ($target) {
+ var $tip = this.getTip($target);
+
+ $tip.fadeOut(150, function () {
+ $tip.find('.tap-to-close').remove();
+ $tip.off('click.fndtn.tooltip.tapclose MSPointerDown.fndtn.tapclose');
+ $target.removeClass('open');
+ });
+ },
+
+ off : function () {
+ var self = this;
+ this.S(this.scope).off('.fndtn.tooltip');
+ this.S(this.settings.tooltip_class).each(function (i) {
+ $('[' + self.attr_name() + ']').eq(i).attr('title', $(this).text());
+ }).remove();
+ },
+
+ reflow : function () {}
+ };
+}(jQuery, window, window.document));
+
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.topbar = {
+ name : 'topbar',
+
+ version : '5.5.1',
+
+ settings : {
+ index : 0,
+ sticky_class : 'sticky',
+ custom_back_text : true,
+ back_text : 'Back',
+ mobile_show_parent_link : true,
+ is_hover : true,
+ scrolltop : true, // jump to top when sticky nav menu toggle is clicked
+ sticky_on : 'all'
+ },
+
+ init : function (section, method, options) {
+ Foundation.inherit(this, 'add_custom_rule register_media throttle');
+ var self = this;
+
+ self.register_media('topbar', 'foundation-mq-topbar');
+
+ this.bindings(method, options);
+
+ self.S('[' + this.attr_name() + ']', this.scope).each(function () {
+ var topbar = $(this),
+ settings = topbar.data(self.attr_name(true) + '-init'),
+ section = self.S('section, .top-bar-section', this);
+ topbar.data('index', 0);
+ var topbarContainer = topbar.parent();
+ if (topbarContainer.hasClass('fixed') || self.is_sticky(topbar, topbarContainer, settings) ) {
+ self.settings.sticky_class = settings.sticky_class;
+ self.settings.sticky_topbar = topbar;
+ topbar.data('height', topbarContainer.outerHeight());
+ topbar.data('stickyoffset', topbarContainer.offset().top);
+ } else {
+ topbar.data('height', topbar.outerHeight());
+ }
+
+ if (!settings.assembled) {
+ self.assemble(topbar);
+ }
+
+ if (settings.is_hover) {
+ self.S('.has-dropdown', topbar).addClass('not-click');
+ } else {
+ self.S('.has-dropdown', topbar).removeClass('not-click');
+ }
+
+ // Pad body when sticky (scrolled) or fixed.
+ self.add_custom_rule('.f-topbar-fixed { padding-top: ' + topbar.data('height') + 'px }');
+
+ if (topbarContainer.hasClass('fixed')) {
+ self.S('body').addClass('f-topbar-fixed');
+ }
+ });
+
+ },
+
+ is_sticky : function (topbar, topbarContainer, settings) {
+ var sticky = topbarContainer.hasClass(settings.sticky_class);
+ var smallMatch = matchMedia(Foundation.media_queries.small).matches;
+ var medMatch = matchMedia(Foundation.media_queries.medium).matches;
+ var lrgMatch = matchMedia(Foundation.media_queries.large).matches;
+
+ if (sticky && settings.sticky_on === 'all') {
+ return true;
+ }
+ if (sticky && this.small() && settings.sticky_on.indexOf('small') !== -1) {
+ if (smallMatch && !medMatch && !lrgMatch) { return true; }
+ }
+ if (sticky && this.medium() && settings.sticky_on.indexOf('medium') !== -1) {
+ if (smallMatch && medMatch && !lrgMatch) { return true; }
+ }
+ if (sticky && this.large() && settings.sticky_on.indexOf('large') !== -1) {
+ if (smallMatch && medMatch && lrgMatch) { return true; }
+ }
+
+ // fix for iOS browsers
+ if (sticky && navigator.userAgent.match(/(iPad|iPhone|iPod)/g)) {
+ return true;
+ }
+ return false;
+ },
+
+ toggle : function (toggleEl) {
+ var self = this,
+ topbar;
+
+ if (toggleEl) {
+ topbar = self.S(toggleEl).closest('[' + this.attr_name() + ']');
+ } else {
+ topbar = self.S('[' + this.attr_name() + ']');
+ }
+
+ var settings = topbar.data(this.attr_name(true) + '-init');
+
+ var section = self.S('section, .top-bar-section', topbar);
+
+ if (self.breakpoint()) {
+ if (!self.rtl) {
+ section.css({left : '0%'});
+ $('>.name', section).css({left : '100%'});
+ } else {
+ section.css({right : '0%'});
+ $('>.name', section).css({right : '100%'});
+ }
+
+ self.S('li.moved', section).removeClass('moved');
+ topbar.data('index', 0);
+
+ topbar
+ .toggleClass('expanded')
+ .css('height', '');
+ }
+
+ if (settings.scrolltop) {
+ if (!topbar.hasClass('expanded')) {
+ if (topbar.hasClass('fixed')) {
+ topbar.parent().addClass('fixed');
+ topbar.removeClass('fixed');
+ self.S('body').addClass('f-topbar-fixed');
+ }
+ } else if (topbar.parent().hasClass('fixed')) {
+ if (settings.scrolltop) {
+ topbar.parent().removeClass('fixed');
+ topbar.addClass('fixed');
+ self.S('body').removeClass('f-topbar-fixed');
+
+ window.scrollTo(0, 0);
+ } else {
+ topbar.parent().removeClass('expanded');
+ }
+ }
+ } else {
+ if (self.is_sticky(topbar, topbar.parent(), settings)) {
+ topbar.parent().addClass('fixed');
+ }
+
+ if (topbar.parent().hasClass('fixed')) {
+ if (!topbar.hasClass('expanded')) {
+ topbar.removeClass('fixed');
+ topbar.parent().removeClass('expanded');
+ self.update_sticky_positioning();
+ } else {
+ topbar.addClass('fixed');
+ topbar.parent().addClass('expanded');
+ self.S('body').addClass('f-topbar-fixed');
+ }
+ }
+ }
+ },
+
+ timer : null,
+
+ events : function (bar) {
+ var self = this,
+ S = this.S;
+
+ S(this.scope)
+ .off('.topbar')
+ .on('click.fndtn.topbar', '[' + this.attr_name() + '] .toggle-topbar', function (e) {
+ e.preventDefault();
+ self.toggle(this);
+ })
+ .on('click.fndtn.topbar', '.top-bar .top-bar-section li a[href^="#"],[' + this.attr_name() + '] .top-bar-section li a[href^="#"]', function (e) {
+ var li = $(this).closest('li');
+ if (self.breakpoint() && !li.hasClass('back') && !li.hasClass('has-dropdown')) {
+ self.toggle();
+ }
+ })
+ .on('click.fndtn.topbar', '[' + this.attr_name() + '] li.has-dropdown', function (e) {
+ var li = S(this),
+ target = S(e.target),
+ topbar = li.closest('[' + self.attr_name() + ']'),
+ settings = topbar.data(self.attr_name(true) + '-init');
+
+ if (target.data('revealId')) {
+ self.toggle();
+ return;
+ }
+
+ if (self.breakpoint()) {
+ return;
+ }
+
+ if (settings.is_hover && !Modernizr.touch) {
+ return;
+ }
+
+ e.stopImmediatePropagation();
+
+ if (li.hasClass('hover')) {
+ li
+ .removeClass('hover')
+ .find('li')
+ .removeClass('hover');
+
+ li.parents('li.hover')
+ .removeClass('hover');
+ } else {
+ li.addClass('hover');
+
+ $(li).siblings().removeClass('hover');
+
+ if (target[0].nodeName === 'A' && target.parent().hasClass('has-dropdown')) {
+ e.preventDefault();
+ }
+ }
+ })
+ .on('click.fndtn.topbar', '[' + this.attr_name() + '] .has-dropdown>a', function (e) {
+ if (self.breakpoint()) {
+
+ e.preventDefault();
+
+ var $this = S(this),
+ topbar = $this.closest('[' + self.attr_name() + ']'),
+ section = topbar.find('section, .top-bar-section'),
+ dropdownHeight = $this.next('.dropdown').outerHeight(),
+ $selectedLi = $this.closest('li');
+
+ topbar.data('index', topbar.data('index') + 1);
+ $selectedLi.addClass('moved');
+
+ if (!self.rtl) {
+ section.css({left : -(100 * topbar.data('index')) + '%'});
+ section.find('>.name').css({left : 100 * topbar.data('index') + '%'});
+ } else {
+ section.css({right : -(100 * topbar.data('index')) + '%'});
+ section.find('>.name').css({right : 100 * topbar.data('index') + '%'});
+ }
+
+ topbar.css('height', $this.siblings('ul').outerHeight(true) + topbar.data('height'));
+ }
+ });
+
+ S(window).off('.topbar').on('resize.fndtn.topbar', self.throttle(function () {
+ self.resize.call(self);
+ }, 50)).trigger('resize').trigger('resize.fndtn.topbar').load(function () {
+ // Ensure that the offset is calculated after all of the pages resources have loaded
+ S(this).trigger('resize.fndtn.topbar');
+ });
+
+ S('body').off('.topbar').on('click.fndtn.topbar', function (e) {
+ var parent = S(e.target).closest('li').closest('li.hover');
+
+ if (parent.length > 0) {
+ return;
+ }
+
+ S('[' + self.attr_name() + '] li.hover').removeClass('hover');
+ });
+
+ // Go up a level on Click
+ S(this.scope).on('click.fndtn.topbar', '[' + this.attr_name() + '] .has-dropdown .back', function (e) {
+ e.preventDefault();
+
+ var $this = S(this),
+ topbar = $this.closest('[' + self.attr_name() + ']'),
+ section = topbar.find('section, .top-bar-section'),
+ settings = topbar.data(self.attr_name(true) + '-init'),
+ $movedLi = $this.closest('li.moved'),
+ $previousLevelUl = $movedLi.parent();
+
+ topbar.data('index', topbar.data('index') - 1);
+
+ if (!self.rtl) {
+ section.css({left : -(100 * topbar.data('index')) + '%'});
+ section.find('>.name').css({left : 100 * topbar.data('index') + '%'});
+ } else {
+ section.css({right : -(100 * topbar.data('index')) + '%'});
+ section.find('>.name').css({right : 100 * topbar.data('index') + '%'});
+ }
+
+ if (topbar.data('index') === 0) {
+ topbar.css('height', '');
+ } else {
+ topbar.css('height', $previousLevelUl.outerHeight(true) + topbar.data('height'));
+ }
+
+ setTimeout(function () {
+ $movedLi.removeClass('moved');
+ }, 300);
+ });
+
+ // Show dropdown menus when their items are focused
+ S(this.scope).find('.dropdown a')
+ .focus(function () {
+ $(this).parents('.has-dropdown').addClass('hover');
+ })
+ .blur(function () {
+ $(this).parents('.has-dropdown').removeClass('hover');
+ });
+ },
+
+ resize : function () {
+ var self = this;
+ self.S('[' + this.attr_name() + ']').each(function () {
+ var topbar = self.S(this),
+ settings = topbar.data(self.attr_name(true) + '-init');
+
+ var stickyContainer = topbar.parent('.' + self.settings.sticky_class);
+ var stickyOffset;
+
+ if (!self.breakpoint()) {
+ var doToggle = topbar.hasClass('expanded');
+ topbar
+ .css('height', '')
+ .removeClass('expanded')
+ .find('li')
+ .removeClass('hover');
+
+ if (doToggle) {
+ self.toggle(topbar);
+ }
+ }
+
+ if (self.is_sticky(topbar, stickyContainer, settings)) {
+ if (stickyContainer.hasClass('fixed')) {
+ // Remove the fixed to allow for correct calculation of the offset.
+ stickyContainer.removeClass('fixed');
+
+ stickyOffset = stickyContainer.offset().top;
+ if (self.S(document.body).hasClass('f-topbar-fixed')) {
+ stickyOffset -= topbar.data('height');
+ }
+
+ topbar.data('stickyoffset', stickyOffset);
+ stickyContainer.addClass('fixed');
+ } else {
+ stickyOffset = stickyContainer.offset().top;
+ topbar.data('stickyoffset', stickyOffset);
+ }
+ }
+
+ });
+ },
+
+ breakpoint : function () {
+ return !matchMedia(Foundation.media_queries['topbar']).matches;
+ },
+
+ small : function () {
+ return matchMedia(Foundation.media_queries['small']).matches;
+ },
+
+ medium : function () {
+ return matchMedia(Foundation.media_queries['medium']).matches;
+ },
+
+ large : function () {
+ return matchMedia(Foundation.media_queries['large']).matches;
+ },
+
+ assemble : function (topbar) {
+ var self = this,
+ settings = topbar.data(this.attr_name(true) + '-init'),
+ section = self.S('section, .top-bar-section', topbar);
+
+ // Pull element out of the DOM for manipulation
+ section.detach();
+
+ self.S('.has-dropdown>a', section).each(function () {
+ var $link = self.S(this),
+ $dropdown = $link.siblings('.dropdown'),
+ url = $link.attr('href'),
+ $titleLi;
+
+ if (!$dropdown.find('.title.back').length) {
+
+ if (settings.mobile_show_parent_link == true && url) {
+ $titleLi = $(' ' + $link.html() +' ');
+ } else {
+ $titleLi = $(' ');
+ }
+
+ // Copy link to subnav
+ if (settings.custom_back_text == true) {
+ $('h5>a', $titleLi).html(settings.back_text);
+ } else {
+ $('h5>a', $titleLi).html('« ' + $link.html());
+ }
+ $dropdown.prepend($titleLi);
+ }
+ });
+
+ // Put element back in the DOM
+ section.appendTo(topbar);
+
+ // check for sticky
+ this.sticky();
+
+ this.assembled(topbar);
+ },
+
+ assembled : function (topbar) {
+ topbar.data(this.attr_name(true), $.extend({}, topbar.data(this.attr_name(true)), {assembled : true}));
+ },
+
+ height : function (ul) {
+ var total = 0,
+ self = this;
+
+ $('> li', ul).each(function () {
+ total += self.S(this).outerHeight(true);
+ });
+
+ return total;
+ },
+
+ sticky : function () {
+ var self = this;
+
+ this.S(window).on('scroll', function () {
+ self.update_sticky_positioning();
+ });
+ },
+
+ update_sticky_positioning : function () {
+ var klass = '.' + this.settings.sticky_class,
+ $window = this.S(window),
+ self = this;
+
+ if (self.settings.sticky_topbar && self.is_sticky(this.settings.sticky_topbar, this.settings.sticky_topbar.parent(), this.settings)) {
+ var distance = this.settings.sticky_topbar.data('stickyoffset');
+ if (!self.S(klass).hasClass('expanded')) {
+ if ($window.scrollTop() > (distance)) {
+ if (!self.S(klass).hasClass('fixed')) {
+ self.S(klass).addClass('fixed');
+ self.S('body').addClass('f-topbar-fixed');
+ }
+ } else if ($window.scrollTop() <= distance) {
+ if (self.S(klass).hasClass('fixed')) {
+ self.S(klass).removeClass('fixed');
+ self.S('body').removeClass('f-topbar-fixed');
+ }
+ }
+ }
+ }
+ },
+
+ off : function () {
+ this.S(this.scope).off('.fndtn.topbar');
+ this.S(window).off('.fndtn.topbar');
+ },
+
+ reflow : function () {}
+ };
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation.min.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation.min.js
new file mode 100644
index 00000000..6e032f47
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation.min.js
@@ -0,0 +1,4 @@
+!function(a,b,c,d){"use strict";function e(a){return("string"==typeof a||a instanceof String)&&(a=a.replace(/^['\\/"]+|(;\s?})+|['\\/"]+$/g,"")),a}var f=function(b){for(var c=b.length,d=a("head");c--;)0===d.has("."+b[c]).length&&d.append(' ')};f(["foundation-mq-small","foundation-mq-small-only","foundation-mq-medium","foundation-mq-medium-only","foundation-mq-large","foundation-mq-large-only","foundation-mq-xlarge","foundation-mq-xlarge-only","foundation-mq-xxlarge","foundation-data-attribute-namespace"]),a(function(){"undefined"!=typeof FastClick&&"undefined"!=typeof c.body&&FastClick.attach(c.body)});var g=function(b,d){if("string"==typeof b){if(d){var e;if(d.jquery){if(e=d[0],!e)return d}else e=d;return a(e.querySelectorAll(b))}return a(c.querySelectorAll(b))}return a(b,d)},h=function(a){var b=[];return a||b.push("data"),this.namespace.length>0&&b.push(this.namespace),b.push(this.name),b.join("-")},i=function(a){for(var b=a.split("-"),c=b.length,d=[];c--;)0!==c?d.push(b[c]):this.namespace.length>0?d.push(this.namespace,b[c]):d.push(b[c]);return d.reverse().join("-")},j=function(b,c){var d=this,e=function(){var e=g(this),f=!e.data(d.attr_name(!0)+"-init");e.data(d.attr_name(!0)+"-init",a.extend({},d.settings,c||b,d.data_options(e))),f&&d.events(this)};return g(this.scope).is("["+this.attr_name()+"]")?e.call(this.scope):g("["+this.attr_name()+"]",this.scope).each(e),"string"==typeof b?this[b].call(this,c):void 0},k=function(a,b){function c(){b(a[0])}function d(){if(this.one("load",c),/MSIE (\d+\.\d+);/.test(navigator.userAgent)){var a=this.attr("src"),b=a.match(/\?/)?"&":"?";b+="random="+(new Date).getTime(),this.attr("src",a+b)}}return a.attr("src")?void(a[0].complete||4===a[0].readyState?c():d.call(a)):void c()};b.matchMedia=b.matchMedia||function(a){var b,c=a.documentElement,d=c.firstElementChild||c.firstChild,e=a.createElement("body"),f=a.createElement("div");return f.id="mq-test-1",f.style.cssText="position:absolute;top:-100em",e.style.background="none",e.appendChild(f),function(a){return f.innerHTML='',c.insertBefore(e,d),b=42===f.offsetWidth,c.removeChild(e),{matches:b,media:a}}}(c),function(a){function c(){d&&(g(c),i&&a.fx.tick())}for(var d,e=0,f=["webkit","moz"],g=b.requestAnimationFrame,h=b.cancelAnimationFrame,i="undefined"!=typeof a.fx;e").appendTo("head")[0].sheet,global:{namespace:d},init:function(a,c,d,e,f){var h=[a,d,e,f],i=[];if(this.rtl=/rtl/i.test(g("html").attr("dir")),this.scope=a||this.scope,this.set_namespace(),c&&"string"==typeof c&&!/reflow/i.test(c))this.libs.hasOwnProperty(c)&&i.push(this.init_lib(c,h));else for(var j in this.libs)i.push(this.init_lib(j,c));return g(b).load(function(){g(b).trigger("resize.fndtn.clearing").trigger("resize.fndtn.dropdown").trigger("resize.fndtn.equalizer").trigger("resize.fndtn.interchange").trigger("resize.fndtn.joyride").trigger("resize.fndtn.magellan").trigger("resize.fndtn.topbar").trigger("resize.fndtn.slider")}),a},init_lib:function(b,c){return this.libs.hasOwnProperty(b)?(this.patch(this.libs[b]),c&&c.hasOwnProperty(b)?("undefined"!=typeof this.libs[b].settings?a.extend(!0,this.libs[b].settings,c[b]):"undefined"!=typeof this.libs[b].defaults&&a.extend(!0,this.libs[b].defaults,c[b]),this.libs[b].init.apply(this.libs[b],[this.scope,c[b]])):(c=c instanceof Array?c:new Array(c),this.libs[b].init.apply(this.libs[b],c))):function(){}},patch:function(a){a.scope=this.scope,a.namespace=this.global.namespace,a.rtl=this.rtl,a.data_options=this.utils.data_options,a.attr_name=h,a.add_namespace=i,a.bindings=j,a.S=this.utils.S},inherit:function(a,b){for(var c=b.split(" "),d=c.length;d--;)this.utils.hasOwnProperty(c[d])&&(a[c[d]]=this.utils[c[d]])},set_namespace:function(){var b=this.global.namespace===d?a(".foundation-data-attribute-namespace").css("font-family"):this.global.namespace;this.global.namespace=b===d||/false/i.test(b)?"":b},libs:{},utils:{S:g,throttle:function(a,b){var c=null;return function(){var d=this,e=arguments;null==c&&(c=setTimeout(function(){a.apply(d,e),c=null},b))}},debounce:function(a,b,c){var d,e;return function(){var f=this,g=arguments,h=function(){d=null,c||(e=a.apply(f,g))},i=c&&!d;return clearTimeout(d),d=setTimeout(h,b),i&&(e=a.apply(f,g)),e}},data_options:function(b,c){function d(a){return!isNaN(a-0)&&null!==a&&""!==a&&a!==!1&&a!==!0}function e(b){return"string"==typeof b?a.trim(b):b}c=c||"options";var f,g,h,i={},j=function(a){var b=Foundation.global.namespace;return a.data(b.length>0?b+"-"+c:c)},k=j(b);if("object"==typeof k)return k;for(h=(k||":").split(";"),f=h.length;f--;)g=h[f].split(":"),g=[g[0],g.slice(1).join(":")],/true/i.test(g[1])&&(g[1]=!0),/false/i.test(g[1])&&(g[1]=!1),d(g[1])&&(g[1]=-1===g[1].indexOf(".")?parseInt(g[1],10):parseFloat(g[1])),2===g.length&&g[0].length>0&&(i[e(g[0])]=e(g[1]));return i},register_media:function(b,c){Foundation.media_queries[b]===d&&(a("head").append(' '),Foundation.media_queries[b]=e(a("."+c).css("font-family")))},add_custom_rule:function(a,b){if(b===d&&Foundation.stylesheet)Foundation.stylesheet.insertRule(a,Foundation.stylesheet.cssRules.length);else{var c=Foundation.media_queries[b];c!==d&&Foundation.stylesheet.insertRule("@media "+Foundation.media_queries[b]+"{ "+a+" }")}},image_loaded:function(a,b){var c=this,d=a.length;0===d&&b(a),a.each(function(){k(c.S(this),function(){d-=1,0===d&&b(a)})})},random_str:function(){return this.fidx||(this.fidx=0),this.prefix=this.prefix||[this.name||"F",(+new Date).toString(36)].join("-"),this.prefix+(this.fidx++).toString(36)},match:function(a){return b.matchMedia(a).matches},is_small_up:function(){return this.match(Foundation.media_queries.small)},is_medium_up:function(){return this.match(Foundation.media_queries.medium)},is_large_up:function(){return this.match(Foundation.media_queries.large)},is_xlarge_up:function(){return this.match(Foundation.media_queries.xlarge)},is_xxlarge_up:function(){return this.match(Foundation.media_queries.xxlarge)},is_small_only:function(){return!(this.is_medium_up()||this.is_large_up()||this.is_xlarge_up()||this.is_xxlarge_up())},is_medium_only:function(){return this.is_medium_up()&&!this.is_large_up()&&!this.is_xlarge_up()&&!this.is_xxlarge_up()},is_large_only:function(){return this.is_medium_up()&&this.is_large_up()&&!this.is_xlarge_up()&&!this.is_xxlarge_up()},is_xlarge_only:function(){return this.is_medium_up()&&this.is_large_up()&&this.is_xlarge_up()&&!this.is_xxlarge_up()},is_xxlarge_only:function(){return this.is_medium_up()&&this.is_large_up()&&this.is_xlarge_up()&&this.is_xxlarge_up()}}},a.fn.foundation=function(){var a=Array.prototype.slice.call(arguments,0);return this.each(function(){return Foundation.init.apply(Foundation,[this].concat(a)),this})}}(jQuery,window,window.document),function(a,b,c){"use strict";Foundation.libs.abide={name:"abide",version:"5.5.1",settings:{live_validate:!0,validate_on_blur:!0,focus_on_invalid:!0,error_labels:!0,error_class:"error",timeout:1e3,patterns:{alpha:/^[a-zA-Z]+$/,alpha_numeric:/^[a-zA-Z0-9]+$/,integer:/^[-+]?\d+$/,number:/^[-+]?\d*(?:[\.\,]\d+)?$/,card:/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/,cvv:/^([0-9]){3,4}$/,email:/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/,url:/^(https?|ftp|file|ssh):\/\/(((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/,domain:/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,8}$/,datetime:/^([0-2][0-9]{3})\-([0-1][0-9])\-([0-3][0-9])T([0-5][0-9])\:([0-5][0-9])\:([0-5][0-9])(Z|([\-\+]([0-1][0-9])\:00))$/,date:/(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))$/,time:/^(0[0-9]|1[0-9]|2[0-3])(:[0-5][0-9]){2}$/,dateISO:/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/,month_day_year:/^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.]\d{4}$/,day_month_year:/^(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.]\d{4}$/,color:/^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/},validators:{equalTo:function(a){var b=c.getElementById(a.getAttribute(this.add_namespace("data-equalto"))).value,d=a.value,e=b===d;return e}}},timer:null,init:function(a,b,c){this.bindings(b,c)},events:function(b){var c=this,d=c.S(b).attr("novalidate","novalidate"),e=d.data(this.attr_name(!0)+"-init")||{};this.invalid_attr=this.add_namespace("data-invalid"),d.off(".abide").on("submit.fndtn.abide validate.fndtn.abide",function(a){var b=/ajax/i.test(c.S(this).attr(c.attr_name()));return c.validate(c.S(this).find("input, textarea, select").get(),a,b)}).on("reset",function(){return c.reset(a(this))}).find("input, textarea, select").off(".abide").on("blur.fndtn.abide change.fndtn.abide",function(a){e.validate_on_blur===!0&&c.validate([this],a)}).on("keydown.fndtn.abide",function(a){e.live_validate===!0&&9!=a.which&&(clearTimeout(c.timer),c.timer=setTimeout(function(){c.validate([this],a)}.bind(this),e.timeout))})},reset:function(b){b.removeAttr(this.invalid_attr),a(this.invalid_attr,b).removeAttr(this.invalid_attr),a("."+this.settings.error_class,b).not("small").removeClass(this.settings.error_class)},validate:function(a,b,c){for(var d=this.parse_patterns(a),e=d.length,f=this.S(a[0]).closest("form"),g=/submit/.test(b.type),h=0;e>h;h++)if(!d[h]&&(g||c))return this.settings.focus_on_invalid&&a[h].focus(),f.trigger("invalid").trigger("invalid.fndtn.abide"),this.S(a[h]).closest("form").attr(this.invalid_attr,""),!1;return(g||c)&&f.trigger("valid").trigger("valid.fndtn.abide"),f.removeAttr(this.invalid_attr),c?!1:!0},parse_patterns:function(a){for(var b=a.length,c=[];b--;)c.push(this.pattern(a[b]));return this.check_validation_and_apply_styles(c)},pattern:function(a){var b=a.getAttribute("type"),c="string"==typeof a.getAttribute("required"),d=a.getAttribute("pattern")||"";return this.settings.patterns.hasOwnProperty(d)&&d.length>0?[a,this.settings.patterns[d],c]:d.length>0?[a,new RegExp(d),c]:this.settings.patterns.hasOwnProperty(b)?[a,this.settings.patterns[b],c]:(d=/.*/,[a,d,c])},check_validation_and_apply_styles:function(b){var c=b.length,d=[],e=this.S(b[0][0]).closest("[data-"+this.attr_name(!0)+"]");for(e.data(this.attr_name(!0)+"-init")||{};c--;){var f,g,h=b[c][0],i=b[c][2],j=h.value.trim(),k=this.S(h).parent(),l=h.getAttribute(this.add_namespace("data-abide-validator")),m="radio"===h.type,n="checkbox"===h.type,o=this.S('label[for="'+h.getAttribute("id")+'"]'),p=i?h.value.length>0:!0,q=[];if(h.getAttribute(this.add_namespace("data-equalto"))&&(l="equalTo"),f=k.is("label")?k.parent():k,l&&(g=this.settings.validators[l].apply(this,[h,i,f]),q.push(g)),m&&i)q.push(this.valid_radio(h,i));else if(n&&i)q.push(this.valid_checkbox(h,i));else if(q.push(b[c][1].test(j)&&p||!i&&h.value.length<1||a(h).attr("disabled")?!0:!1),q=[q.every(function(a){return a})],q[0])this.S(h).removeAttr(this.invalid_attr),h.setAttribute("aria-invalid","false"),h.removeAttribute("aria-describedby"),f.removeClass(this.settings.error_class),o.length>0&&this.settings.error_labels&&o.removeClass(this.settings.error_class).removeAttr("role"),a(h).triggerHandler("valid");else{this.S(h).attr(this.invalid_attr,""),h.setAttribute("aria-invalid","true");var r=f.find("small."+this.settings.error_class,"span."+this.settings.error_class),s=r.length>0?r[0].id:"";s.length>0&&h.setAttribute("aria-describedby",s),f.addClass(this.settings.error_class),o.length>0&&this.settings.error_labels&&o.addClass(this.settings.error_class).attr("role","alert"),a(h).triggerHandler("invalid")}d.push(q[0])}return d=[d.every(function(a){return a})]},valid_checkbox:function(a,b){var a=this.S(a),c=a.is(":checked")||!b||a.get(0).getAttribute("disabled");return c?a.removeAttr(this.invalid_attr).parent().removeClass(this.settings.error_class):a.attr(this.invalid_attr,"").parent().addClass(this.settings.error_class),c},valid_radio:function(a){for(var b=a.getAttribute("name"),c=this.S(a).closest("[data-"+this.attr_name(!0)+"]").find("[name='"+b+"']"),d=c.length,e=!1,f=!1,g=0;d>g;g++)c[g].getAttribute("disabled")?(f=!0,e=!0):c[g].checked?e=!0:f&&(e=!1);for(var g=0;d>g;g++)e?this.S(c[g]).removeAttr(this.invalid_attr).parent().removeClass(this.settings.error_class):this.S(c[g]).attr(this.invalid_attr,"").parent().addClass(this.settings.error_class);return e},valid_equal:function(a,b,d){var e=c.getElementById(a.getAttribute(this.add_namespace("data-equalto"))).value,f=a.value,g=e===f;return g?(this.S(a).removeAttr(this.invalid_attr),d.removeClass(this.settings.error_class),label.length>0&&settings.error_labels&&label.removeClass(this.settings.error_class)):(this.S(a).attr(this.invalid_attr,""),d.addClass(this.settings.error_class),label.length>0&&settings.error_labels&&label.addClass(this.settings.error_class)),g},valid_oneof:function(a,b,c,d){var a=this.S(a),e=this.S("["+this.add_namespace("data-oneof")+"]"),f=e.filter(":checked").length>0;if(f?a.removeAttr(this.invalid_attr).parent().removeClass(this.settings.error_class):a.attr(this.invalid_attr,"").parent().addClass(this.settings.error_class),!d){var g=this;e.each(function(){g.valid_oneof.call(g,this,null,null,!0)})}return f}}}(jQuery,window,window.document),function(a){"use strict";Foundation.libs.accordion={name:"accordion",version:"5.5.1",settings:{content_class:"content",active_class:"active",multi_expand:!1,toggleable:!0,callback:function(){}},init:function(a,b,c){this.bindings(b,c)},events:function(){var b=this,c=this.S;c(this.scope).off(".fndtn.accordion").on("click.fndtn.accordion","["+this.attr_name()+"] > .accordion-navigation > a",function(d){var e=c(this).closest("["+b.attr_name()+"]"),f=b.attr_name()+"="+e.attr(b.attr_name()),g=e.data(b.attr_name(!0)+"-init")||b.settings,h=c("#"+this.href.split("#")[1]),i=a("> .accordion-navigation",e),j=i.children("."+g.content_class),k=j.filter("."+g.active_class);return d.preventDefault(),e.attr(b.attr_name())&&(j=j.add("["+f+"] dd > ."+g.content_class),i=i.add("["+f+"] .accordion-navigation")),g.toggleable&&h.is(k)?(h.parent(".accordion-navigation").toggleClass(g.active_class,!1),h.toggleClass(g.active_class,!1),g.callback(h),h.triggerHandler("toggled",[e]),void e.triggerHandler("toggled",[h])):(g.multi_expand||(j.removeClass(g.active_class),i.removeClass(g.active_class)),h.addClass(g.active_class).parent().addClass(g.active_class),g.callback(h),h.triggerHandler("toggled",[e]),void e.triggerHandler("toggled",[h]))})},off:function(){},reflow:function(){}}}(jQuery,window,window.document),function(a){"use strict";Foundation.libs.alert={name:"alert",version:"5.5.1",settings:{callback:function(){}},init:function(a,b,c){this.bindings(b,c)},events:function(){var b=this,c=this.S;a(this.scope).off(".alert").on("click.fndtn.alert","["+this.attr_name()+"] .close",function(a){var d=c(this).closest("["+b.attr_name()+"]"),e=d.data(b.attr_name(!0)+"-init")||b.settings;a.preventDefault(),Modernizr.csstransitions?(d.addClass("alert-close"),d.on("transitionend webkitTransitionEnd oTransitionEnd",function(){c(this).trigger("close").trigger("close.fndtn.alert").remove(),e.callback()})):d.fadeOut(300,function(){c(this).trigger("close").trigger("close.fndtn.alert").remove(),e.callback()})})},reflow:function(){}}}(jQuery,window,window.document),function(a,b,c,d){"use strict";Foundation.libs.clearing={name:"clearing",version:"5.5.1",settings:{templates:{viewing:'× '},close_selectors:".clearing-close, div.clearing-blackout",open_selectors:"",skip_selector:"",touch_label:"",init:!1,locked:!1},init:function(a,b,c){var d=this;Foundation.inherit(this,"throttle image_loaded"),this.bindings(b,c),d.S(this.scope).is("["+this.attr_name()+"]")?this.assemble(d.S("li",this.scope)):d.S("["+this.attr_name()+"]",this.scope).each(function(){d.assemble(d.S("li",this))})},events:function(d){var e=this,f=e.S,g=a(".scroll-container");g.length>0&&(this.scope=g),f(this.scope).off(".clearing").on("click.fndtn.clearing","ul["+this.attr_name()+"] li "+this.settings.open_selectors,function(a,b,c){var b=b||f(this),c=c||b,d=b.next("li"),g=b.closest("["+e.attr_name()+"]").data(e.attr_name(!0)+"-init"),h=f(a.target);a.preventDefault(),g||(e.init(),g=b.closest("["+e.attr_name()+"]").data(e.attr_name(!0)+"-init")),c.hasClass("visible")&&b[0]===c[0]&&d.length>0&&e.is_open(b)&&(c=d,h=f("img",c)),e.open(h,b,c),e.update_paddles(c)}).on("click.fndtn.clearing",".clearing-main-next",function(a){e.nav(a,"next")}).on("click.fndtn.clearing",".clearing-main-prev",function(a){e.nav(a,"prev")}).on("click.fndtn.clearing",this.settings.close_selectors,function(a){Foundation.libs.clearing.close(a,this)}),a(c).on("keydown.fndtn.clearing",function(a){e.keydown(a)}),f(b).off(".clearing").on("resize.fndtn.clearing",function(){e.resize()}),this.swipe_events(d)},swipe_events:function(){var a=this,b=a.S;b(this.scope).on("touchstart.fndtn.clearing",".visible-img",function(a){a.touches||(a=a.originalEvent);var c={start_page_x:a.touches[0].pageX,start_page_y:a.touches[0].pageY,start_time:(new Date).getTime(),delta_x:0,is_scrolling:d};b(this).data("swipe-transition",c),a.stopPropagation()}).on("touchmove.fndtn.clearing",".visible-img",function(c){if(c.touches||(c=c.originalEvent),!(c.touches.length>1||c.scale&&1!==c.scale)){var d=b(this).data("swipe-transition");if("undefined"==typeof d&&(d={}),d.delta_x=c.touches[0].pageX-d.start_page_x,Foundation.rtl&&(d.delta_x=-d.delta_x),"undefined"==typeof d.is_scrolling&&(d.is_scrolling=!!(d.is_scrolling||Math.abs(d.delta_x) ');var d=c.detach(),e="";if(null!=d[0]){e=d[0].outerHTML;var f=this.S("#foundationClearingHolder"),g=c.data(this.attr_name(!0)+"-init"),h={grid:'
'+e+"
",viewing:g.templates.viewing},i='
",j=this.settings.touch_label;Modernizr.touch&&(i=a(i).find(".clearing-touch-label").html(j).end()),f.after(i).remove()}}},open:function(b,d,e){function f(){setTimeout(function(){this.image_loaded(m,function(){1!==m.outerWidth()||o?g.call(this,m):f.call(this)}.bind(this))}.bind(this),100)}function g(b){var c=a(b);c.css("visibility","visible"),i.css("overflow","hidden"),j.addClass("clearing-blackout"),k.addClass("clearing-container"),l.show(),this.fix_height(e).caption(h.S(".clearing-caption",l),h.S("img",e)).center_and_label(b,n).shift(d,e,function(){e.closest("li").siblings().removeClass("visible"),e.closest("li").addClass("visible")}),l.trigger("opened.fndtn.clearing")}var h=this,i=a(c.body),j=e.closest(".clearing-assembled"),k=h.S("div",j).first(),l=h.S(".visible-img",k),m=h.S("img",l).not(b),n=h.S(".clearing-touch-label",k),o=!1;a("body").on("touchmove",function(a){a.preventDefault()}),m.error(function(){o=!0}),this.locked()||(l.trigger("open.fndtn.clearing"),m.attr("src",this.load(b)).css("visibility","hidden"),f.call(this))},close:function(b,d){b.preventDefault();var e,f,g=function(a){return/blackout/.test(a.selector)?a:a.closest(".clearing-blackout")}(a(d)),h=a(c.body);return d===b.target&&g&&(h.css("overflow",""),e=a("div",g).first(),f=a(".visible-img",e),f.trigger("close.fndtn.clearing"),this.settings.prev_index=0,a("ul["+this.attr_name()+"]",g).attr("style","").closest(".clearing-blackout").removeClass("clearing-blackout"),e.removeClass("clearing-container"),f.hide(),f.trigger("closed.fndtn.clearing")),a("body").off("touchmove"),!1},is_open:function(a){return a.parent().prop("style").length>0},keydown:function(b){var c=a(".clearing-blackout ul["+this.attr_name()+"]"),d=this.rtl?37:39,e=this.rtl?39:37,f=27;b.which===d&&this.go(c,"next"),b.which===e&&this.go(c,"prev"),b.which===f&&this.S("a.clearing-close").trigger("click").trigger("click.fndtn.clearing")},nav:function(b,c){var d=a("ul["+this.attr_name()+"]",".clearing-blackout");b.preventDefault(),this.go(d,c)},resize:function(){var b=a("img",".clearing-blackout .visible-img"),c=a(".clearing-touch-label",".clearing-blackout");b.length&&(this.center_and_label(b,c),b.trigger("resized.fndtn.clearing"))},fix_height:function(a){var b=a.parent().children(),c=this;return b.each(function(){var a=c.S(this),b=a.find("img");a.height()>b.outerHeight()&&a.addClass("fix-height")}).closest("ul").width(100*b.length+"%"),this},update_paddles:function(a){a=a.closest("li");var b=a.closest(".carousel").siblings(".visible-img");a.next().length>0?this.S(".clearing-main-next",b).removeClass("disabled"):this.S(".clearing-main-next",b).addClass("disabled"),a.prev().length>0?this.S(".clearing-main-prev",b).removeClass("disabled"):this.S(".clearing-main-prev",b).addClass("disabled")},center_and_label:function(a,b){return b.css(!this.rtl&&b.length>0?{marginLeft:-(b.outerWidth()/2),marginTop:-(a.outerHeight()/2)-b.outerHeight()-10}:{marginRight:-(b.outerWidth()/2),marginTop:-(a.outerHeight()/2)-b.outerHeight()-10,left:"auto",right:"50%"}),this},load:function(a){var b;return b="A"===a[0].nodeName?a.attr("href"):a.closest("a").attr("href"),this.preload(a),b?b:a.attr("src")},preload:function(a){this.img(a.closest("li").next()).img(a.closest("li").prev())},img:function(a){if(a.length){var b=new Image,c=this.S("a",a);b.src=c.length?c.attr("href"):this.S("img",a).attr("src")}return this},caption:function(a,b){var c=b.attr("data-caption");return c?a.html(c).show():a.text("").hide(),this},go:function(a,b){var c=this.S(".visible",a),d=c[b]();this.settings.skip_selector&&0!=d.find(this.settings.skip_selector).length&&(d=d[b]()),d.length&&this.S("img",d).trigger("click",[c,d]).trigger("click.fndtn.clearing",[c,d]).trigger("change.fndtn.clearing")},shift:function(a,b,c){var d,e=b.parent(),f=this.settings.prev_index||b.index(),g=this.direction(e,a,b),h=this.rtl?"right":"left",i=parseInt(e.css("left"),10),j=b.outerWidth(),k={};b.index()===f||/skip/.test(g)?/skip/.test(g)&&(d=b.index()-this.settings.up_count,this.lock(),d>0?(k[h]=-(d*j),e.animate(k,300,this.unlock())):(k[h]=0,e.animate(k,300,this.unlock()))):/left/.test(g)?(this.lock(),k[h]=i+j,e.animate(k,300,this.unlock())):/right/.test(g)&&(this.lock(),k[h]=i-j,e.animate(k,300,this.unlock())),c()},direction:function(a,b,c){var d,e=this.S("li",a),f=e.outerWidth()+e.outerWidth()/4,g=Math.floor(this.S(".clearing-container").outerWidth()/f)-1,h=e.index(c);return this.settings.up_count=g,d=this.adjacent(this.settings.prev_index,h)?h>g&&h>this.settings.prev_index?"right":h>g-1&&h<=this.settings.prev_index?"left":!1:"skip",this.settings.prev_index=h,d},adjacent:function(a,b){for(var c=b+1;c>=b-1;c--)if(c===a)return!0;return!1},lock:function(){this.settings.locked=!0},unlock:function(){this.settings.locked=!1},locked:function(){return this.settings.locked},off:function(){this.S(this.scope).off(".fndtn.clearing"),this.S(b).off(".fndtn.clearing")},reflow:function(){this.init()}}}(jQuery,window,window.document),function(a,b,c){"use strict";Foundation.libs.dropdown={name:"dropdown",version:"5.5.1",settings:{active_class:"open",disabled_class:"disabled",mega_class:"mega",align:"bottom",is_hover:!1,hover_timeout:150,opened:function(){},closed:function(){}},init:function(b,c,d){Foundation.inherit(this,"throttle"),a.extend(!0,this.settings,c,d),this.bindings(c,d)},events:function(){var d=this,e=d.S;e(this.scope).off(".dropdown").on("click.fndtn.dropdown","["+this.attr_name()+"]",function(b){var c=e(this).data(d.attr_name(!0)+"-init")||d.settings;(!c.is_hover||Modernizr.touch)&&(b.preventDefault(),e(this).parent("[data-reveal-id]")&&b.stopPropagation(),d.toggle(a(this)))}).on("mouseenter.fndtn.dropdown","["+this.attr_name()+"], ["+this.attr_name()+"-content]",function(a){var b,c,f=e(this);clearTimeout(d.timeout),f.data(d.data_attr())?(b=e("#"+f.data(d.data_attr())),c=f):(b=f,c=e("["+d.attr_name()+'="'+b.attr("id")+'"]'));var g=c.data(d.attr_name(!0)+"-init")||d.settings;e(a.currentTarget).data(d.data_attr())&&g.is_hover&&d.closeall.call(d),g.is_hover&&d.open.apply(d,[b,c])}).on("mouseleave.fndtn.dropdown","["+this.attr_name()+"], ["+this.attr_name()+"-content]",function(){var a,b=e(this);if(b.data(d.data_attr()))a=b.data(d.data_attr(!0)+"-init")||d.settings;else var c=e("["+d.attr_name()+'="'+e(this).attr("id")+'"]'),a=c.data(d.attr_name(!0)+"-init")||d.settings;d.timeout=setTimeout(function(){b.data(d.data_attr())?a.is_hover&&d.close.call(d,e("#"+b.data(d.data_attr()))):a.is_hover&&d.close.call(d,b)}.bind(this),a.hover_timeout)}).on("click.fndtn.dropdown",function(b){var f=e(b.target).closest("["+d.attr_name()+"-content]"),g=f.find("a");return g.length>0&&"false"!==f.attr("aria-autoclose")&&d.close.call(d,e("["+d.attr_name()+"-content]")),b.target!==c&&!a.contains(c.documentElement,b.target)||e(b.target).closest("["+d.attr_name()+"]").length>0?void 0:!e(b.target).data("revealId")&&f.length>0&&(e(b.target).is("["+d.attr_name()+"-content]")||a.contains(f.first()[0],b.target))?void b.stopPropagation():void d.close.call(d,e("["+d.attr_name()+"-content]"))}).on("opened.fndtn.dropdown","["+d.attr_name()+"-content]",function(){d.settings.opened.call(this)}).on("closed.fndtn.dropdown","["+d.attr_name()+"-content]",function(){d.settings.closed.call(this)}),e(b).off(".dropdown").on("resize.fndtn.dropdown",d.throttle(function(){d.resize.call(d)},50)),this.resize()},close:function(b){var c=this;b.each(function(){var d=a("["+c.attr_name()+"="+b[0].id+"]")||a("aria-controls="+b[0].id+"]");d.attr("aria-expanded","false"),c.S(this).hasClass(c.settings.active_class)&&(c.S(this).css(Foundation.rtl?"right":"left","-99999px").attr("aria-hidden","true").removeClass(c.settings.active_class).prev("["+c.attr_name()+"]").removeClass(c.settings.active_class).removeData("target"),c.S(this).trigger("closed").trigger("closed.fndtn.dropdown",[b]))}),b.removeClass("f-open-"+this.attr_name(!0))},closeall:function(){var b=this;a.each(b.S(".f-open-"+this.attr_name(!0)),function(){b.close.call(b,b.S(this))})},open:function(a,b){this.css(a.addClass(this.settings.active_class),b),a.prev("["+this.attr_name()+"]").addClass(this.settings.active_class),a.data("target",b.get(0)).trigger("opened").trigger("opened.fndtn.dropdown",[a,b]),a.attr("aria-hidden","false"),b.attr("aria-expanded","true"),a.focus(),a.addClass("f-open-"+this.attr_name(!0))},data_attr:function(){return this.namespace.length>0?this.namespace+"-"+this.name:this.name},toggle:function(a){if(!a.hasClass(this.settings.disabled_class)){var b=this.S("#"+a.data(this.data_attr()));0!==b.length&&(this.close.call(this,this.S("["+this.attr_name()+"-content]").not(b)),b.hasClass(this.settings.active_class)?(this.close.call(this,b),b.data("target")!==a.get(0)&&this.open.call(this,b,a)):this.open.call(this,b,a))}},resize:function(){var b=this.S("["+this.attr_name()+"-content].open"),c=a(b.data("target"));b.length&&c.length&&this.css(b,c)},css:function(a,b){var c=Math.max((b.width()-a.width())/2,8),d=b.data(this.attr_name(!0)+"-init")||this.settings;if(this.clear_idx(),this.small()){var e=this.dirs.bottom.call(a,b,d);a.attr("style","").removeClass("drop-left drop-right drop-top").css({position:"absolute",width:"95%","max-width":"none",top:e.top}),a.css(Foundation.rtl?"right":"left",c)}else this.style(a,b,d);return a},style:function(b,c,d){var e=a.extend({position:"absolute"},this.dirs[d.align].call(b,c,d));b.attr("style","").css(e)},dirs:{_base:function(a){var d=this.offsetParent(),e=d.offset(),f=a.offset();f.top-=e.top,f.left-=e.left,f.missRight=!1,f.missTop=!1,f.missLeft=!1,f.leftRightFlag=!1;var g;g=c.getElementsByClassName("row")[0]?c.getElementsByClassName("row")[0].clientWidth:b.outerWidth;var h=(b.outerWidth-g)/2,i=g;return this.hasClass("mega")||(a.offset().top<=this.outerHeight()&&(f.missTop=!0,i=b.outerWidth-h,f.leftRightFlag=!0),a.offset().left+this.outerWidth()>a.offset().left+h&&a.offset().left-h>this.outerWidth()&&(f.missRight=!0,f.missLeft=!1),a.offset().left-this.outerWidth()<=0&&(f.missLeft=!0,f.missRight=!1)),f},top:function(a,b){var c=Foundation.libs.dropdown,d=c.dirs._base.call(this,a);return this.addClass("drop-top"),1==d.missTop&&(d.top=d.top+a.outerHeight()+this.outerHeight(),this.removeClass("drop-top")),1==d.missRight&&(d.left=d.left-this.outerWidth()+a.outerWidth()),(a.outerWidth()
0)for(var d=this.S("["+this.add_namespace("data-uuid")+'="'+a+'"]');c--;){var e,f=b[c][2];if(e=matchMedia(this.settings.named_queries.hasOwnProperty(f)?this.settings.named_queries[f]:f),e.matches)return{el:d,scenario:b[c]}}return!1},load:function(a,b){return("undefined"==typeof this["cached_"+a]||b)&&this["update_"+a](),this["cached_"+a]},update_images:function(){var a=this.S("img["+this.data_attr+"]"),b=a.length,c=b,d=0,e=this.data_attr;for(this.cache={},this.cached_images=[],this.images_loaded=0===b;c--;){if(d++,a[c]){var f=a[c].getAttribute(e)||"";f.length>0&&this.cached_images.push(a[c])}d===b&&(this.images_loaded=!0,this.enhance("images"))}return this},update_nodes:function(){var a=this.S("["+this.data_attr+"]").not("img"),b=a.length,c=b,d=0,e=this.data_attr;for(this.cached_nodes=[],this.nodes_loaded=0===b;c--;){d++;var f=a[c].getAttribute(e)||"";f.length>0&&this.cached_nodes.push(a[c]),d===b&&(this.nodes_loaded=!0,this.enhance("nodes"))}return this},enhance:function(c){for(var d=this["cached_"+c].length;d--;)this.object(a(this["cached_"+c][d]));return a(b).trigger("resize").trigger("resize.fndtn.interchange")},convert_directive:function(a){var b=this.trim(a);return b.length>0?b:"replace"},parse_scenario:function(a){var b=a[0].match(/(.+),\s*(\w+)\s*$/),c=a[1];if(b)var d=b[1],e=b[2];else var f=a[0].split(/,\s*$/),d=f[0],e="";return[this.trim(d),this.convert_directive(e),this.trim(c)]},object:function(a){var b=this.parse_data_attr(a),c=[],d=b.length;if(d>0)for(;d--;){var e=b[d].split(/\(([^\)]*?)(\))$/);if(e.length>1){var f=this.parse_scenario(e);c.push(f)}}return this.store(a,c)},store:function(a,b){var c=this.random_str(),d=a.data(this.add_namespace("uuid",!0));return this.cache[d]?this.cache[d]:(a.attr(this.add_namespace("data-uuid"),c),this.cache[c]=b)},trim:function(b){return"string"==typeof b?a.trim(b):b},set_data_attr:function(a){return a?this.namespace.length>0?this.namespace+"-"+this.settings.load_attr:this.settings.load_attr:this.namespace.length>0?"data-"+this.namespace+"-"+this.settings.load_attr:"data-"+this.settings.load_attr},parse_data_attr:function(a){for(var b=a.attr(this.attr_name()).split(/\[(.*?)\]/),c=b.length,d=[];c--;)b[c].replace(/[\W\d]+/,"").length>4&&d.push(b[c]);return d},reflow:function(){this.load("images",!0),this.load("nodes",!0)}}}(jQuery,window,window.document),function(a,b,c,d){"use strict";Foundation.libs.joyride={name:"joyride",version:"5.5.1",defaults:{expose:!1,modal:!0,keyboard:!0,tip_location:"bottom",nub_position:"auto",scroll_speed:1500,scroll_animation:"linear",timer:0,start_timer_on_click:!0,start_offset:0,next_button:!0,prev_button:!0,tip_animation:"fade",pause_after:[],exposed:[],tip_animation_fade_speed:300,cookie_monster:!1,cookie_name:"joyride",cookie_domain:!1,cookie_expires:365,tip_container:"body",abort_on_close:!0,tip_location_patterns:{top:["bottom"],bottom:[],left:["right","top","bottom"],right:["left","top","bottom"]},post_ride_callback:function(){},post_step_callback:function(){},pre_step_callback:function(){},pre_ride_callback:function(){},post_expose_callback:function(){},template:{link:'× ',timer:'
',tip:'
',wrapper:'
',button:' ',prev_button:' ',modal:'
',expose:'
',expose_cover:'
'},expose_add_class:""},init:function(b,c,d){Foundation.inherit(this,"throttle random_str"),this.settings=this.settings||a.extend({},this.defaults,d||c),this.bindings(c,d)},go_next:function(){this.settings.$li.next().length<1?this.end():this.settings.timer>0?(clearTimeout(this.settings.automate),this.hide(),this.show(),this.startTimer()):(this.hide(),this.show())},go_prev:function(){this.settings.$li.prev().length<1||(this.settings.timer>0?(clearTimeout(this.settings.automate),this.hide(),this.show(null,!0),this.startTimer()):(this.hide(),this.show(null,!0)))},events:function(){var c=this;a(this.scope).off(".joyride").on("click.fndtn.joyride",".joyride-next-tip, .joyride-modal-bg",function(a){a.preventDefault(),this.go_next()}.bind(this)).on("click.fndtn.joyride",".joyride-prev-tip",function(a){a.preventDefault(),this.go_prev()}.bind(this)).on("click.fndtn.joyride",".joyride-close-tip",function(a){a.preventDefault(),this.end(this.settings.abort_on_close)}.bind(this)).on("keyup.fndtn.joyride",function(a){if(this.settings.keyboard&&this.settings.riding)switch(a.which){case 39:a.preventDefault(),this.go_next();break;case 37:a.preventDefault(),this.go_prev();break;case 27:a.preventDefault(),this.end(this.settings.abort_on_close)}}.bind(this)),a(b).off(".joyride").on("resize.fndtn.joyride",c.throttle(function(){if(a("["+c.attr_name()+"]").length>0&&c.settings.$next_tip&&c.settings.riding){if(c.settings.exposed.length>0){var b=a(c.settings.exposed);b.each(function(){var b=a(this);c.un_expose(b),c.expose(b)})}c.is_phone()?c.pos_phone():c.pos_default(!1)}},100))},start:function(){var b=this,c=a("["+this.attr_name()+"]",this.scope),d=["timer","scrollSpeed","startOffset","tipAnimationFadeSpeed","cookieExpires"],e=d.length;!c.length>0||(this.settings.init||this.events(),this.settings=c.data(this.attr_name(!0)+"-init"),this.settings.$content_el=c,this.settings.$body=a(this.settings.tip_container),this.settings.body_offset=a(this.settings.tip_container).position(),this.settings.$tip_content=this.settings.$content_el.find("> li"),this.settings.paused=!1,this.settings.attempts=0,this.settings.riding=!0,"function"!=typeof a.cookie&&(this.settings.cookie_monster=!1),(!this.settings.cookie_monster||this.settings.cookie_monster&&!a.cookie(this.settings.cookie_name))&&(this.settings.$tip_content.each(function(c){var f=a(this);this.settings=a.extend({},b.defaults,b.data_options(f));for(var g=e;g--;)b.settings[d[g]]=parseInt(b.settings[d[g]],10);b.create({$li:f,index:c})}),!this.settings.start_timer_on_click&&this.settings.timer>0?(this.show("init"),this.startTimer()):this.show("init")))},resume:function(){this.set_li(),this.show()},tip_template:function(b){var c,d;return b.tip_class=b.tip_class||"",c=a(this.settings.template.tip).addClass(b.tip_class),d=a.trim(a(b.li).html())+this.prev_button_text(b.prev_button_text,b.index)+this.button_text(b.button_text)+this.settings.template.link+this.timer_instance(b.index),c.append(a(this.settings.template.wrapper)),c.first().attr(this.add_namespace("data-index"),b.index),a(".joyride-content-wrapper",c).append(d),c[0]},timer_instance:function(b){var c;return c=0===b&&this.settings.start_timer_on_click&&this.settings.timer>0||0===this.settings.timer?"":a(this.settings.template.timer)[0].outerHTML},button_text:function(b){return this.settings.tip_settings.next_button?(b=a.trim(b)||"Next",b=a(this.settings.template.button).append(b)[0].outerHTML):b="",b},prev_button_text:function(b,c){return this.settings.tip_settings.prev_button?(b=a.trim(b)||"Previous",b=0==c?a(this.settings.template.prev_button).append(b).addClass("disabled")[0].outerHTML:a(this.settings.template.prev_button).append(b)[0].outerHTML):b="",b},create:function(b){this.settings.tip_settings=a.extend({},this.settings,this.data_options(b.$li));var c=b.$li.attr(this.add_namespace("data-button"))||b.$li.attr(this.add_namespace("data-text")),d=b.$li.attr(this.add_namespace("data-button-prev"))||b.$li.attr(this.add_namespace("data-prev-text")),e=b.$li.attr("class"),f=a(this.tip_template({tip_class:e,index:b.index,button_text:c,prev_button_text:d,li:b.$li}));a(this.settings.tip_container).append(f)},show:function(b,c){var e=null;if(this.settings.$li===d||-1===a.inArray(this.settings.$li.index(),this.settings.pause_after))if(this.settings.paused?this.settings.paused=!1:this.set_li(b,c),this.settings.attempts=0,this.settings.$li.length&&this.settings.$target.length>0){if(b&&(this.settings.pre_ride_callback(this.settings.$li.index(),this.settings.$next_tip),this.settings.modal&&this.show_modal()),this.settings.pre_step_callback(this.settings.$li.index(),this.settings.$next_tip),this.settings.modal&&this.settings.expose&&this.expose(),this.settings.tip_settings=a.extend({},this.settings,this.data_options(this.settings.$li)),this.settings.timer=parseInt(this.settings.timer,10),this.settings.tip_settings.tip_location_pattern=this.settings.tip_location_patterns[this.settings.tip_settings.tip_location],!/body/i.test(this.settings.$target.selector)){var f=a(".joyride-modal-bg");/pop/i.test(this.settings.tipAnimation)?f.hide():f.fadeOut(this.settings.tipAnimationFadeSpeed),this.scroll_to()}this.is_phone()?this.pos_phone(!0):this.pos_default(!0),e=this.settings.$next_tip.find(".joyride-timer-indicator"),/pop/i.test(this.settings.tip_animation)?(e.width(0),this.settings.timer>0?(this.settings.$next_tip.show(),setTimeout(function(){e.animate({width:e.parent().width()},this.settings.timer,"linear")}.bind(this),this.settings.tip_animation_fade_speed)):this.settings.$next_tip.show()):/fade/i.test(this.settings.tip_animation)&&(e.width(0),this.settings.timer>0?(this.settings.$next_tip.fadeIn(this.settings.tip_animation_fade_speed).show(),setTimeout(function(){e.animate({width:e.parent().width()},this.settings.timer,"linear")}.bind(this),this.settings.tip_animation_fade_speed)):this.settings.$next_tip.fadeIn(this.settings.tip_animation_fade_speed)),this.settings.$current_tip=this.settings.$next_tip}else this.settings.$li&&this.settings.$target.length<1?this.show(b,c):this.end();else this.settings.paused=!0},is_phone:function(){return matchMedia(Foundation.media_queries.small).matches&&!matchMedia(Foundation.media_queries.medium).matches},hide:function(){this.settings.modal&&this.settings.expose&&this.un_expose(),this.settings.modal||a(".joyride-modal-bg").hide(),this.settings.$current_tip.css("visibility","hidden"),setTimeout(a.proxy(function(){this.hide(),this.css("visibility","visible")},this.settings.$current_tip),0),this.settings.post_step_callback(this.settings.$li.index(),this.settings.$current_tip)},set_li:function(a,b){a?(this.settings.$li=this.settings.$tip_content.eq(this.settings.start_offset),this.set_next_tip(),this.settings.$current_tip=this.settings.$next_tip):(this.settings.$li=b?this.settings.$li.prev():this.settings.$li.next(),this.set_next_tip()),this.set_target()},set_next_tip:function(){this.settings.$next_tip=a(".joyride-tip-guide").eq(this.settings.$li.index()),this.settings.$next_tip.data("closed","")},set_target:function(){var b=this.settings.$li.attr(this.add_namespace("data-class")),d=this.settings.$li.attr(this.add_namespace("data-id")),e=function(){return d?a(c.getElementById(d)):b?a("."+b).first():a("body")};this.settings.$target=e()},scroll_to:function(){var c,d;c=a(b).height()/2,d=Math.ceil(this.settings.$target.offset().top-c+this.settings.$next_tip.outerHeight()),0!=d&&a("html, body").stop().animate({scrollTop:d},this.settings.scroll_speed,"swing")},paused:function(){return-1===a.inArray(this.settings.$li.index()+1,this.settings.pause_after)},restart:function(){this.hide(),this.settings.$li=d,this.show("init")},pos_default:function(a){var b=this.settings.$next_tip.find(".joyride-nub"),c=Math.ceil(b.outerWidth()/2),d=Math.ceil(b.outerHeight()/2),e=a||!1;if(e&&(this.settings.$next_tip.css("visibility","hidden"),this.settings.$next_tip.show()),/body/i.test(this.settings.$target.selector))this.settings.$li.length&&this.pos_modal(b);else{var f=this.settings.tip_settings.tipAdjustmentY?parseInt(this.settings.tip_settings.tipAdjustmentY):0,g=this.settings.tip_settings.tipAdjustmentX?parseInt(this.settings.tip_settings.tipAdjustmentX):0;this.bottom()?(this.settings.$next_tip.css(this.rtl?{top:this.settings.$target.offset().top+d+this.settings.$target.outerHeight()+f,left:this.settings.$target.offset().left+this.settings.$target.outerWidth()-this.settings.$next_tip.outerWidth()+g}:{top:this.settings.$target.offset().top+d+this.settings.$target.outerHeight()+f,left:this.settings.$target.offset().left+g}),this.nub_position(b,this.settings.tip_settings.nub_position,"top")):this.top()?(this.settings.$next_tip.css(this.rtl?{top:this.settings.$target.offset().top-this.settings.$next_tip.outerHeight()-d+f,left:this.settings.$target.offset().left+this.settings.$target.outerWidth()-this.settings.$next_tip.outerWidth()}:{top:this.settings.$target.offset().top-this.settings.$next_tip.outerHeight()-d+f,left:this.settings.$target.offset().left+g}),this.nub_position(b,this.settings.tip_settings.nub_position,"bottom")):this.right()?(this.settings.$next_tip.css({top:this.settings.$target.offset().top+f,left:this.settings.$target.outerWidth()+this.settings.$target.offset().left+c+g}),this.nub_position(b,this.settings.tip_settings.nub_position,"left")):this.left()&&(this.settings.$next_tip.css({top:this.settings.$target.offset().top+f,left:this.settings.$target.offset().left-this.settings.$next_tip.outerWidth()-c+g}),this.nub_position(b,this.settings.tip_settings.nub_position,"right")),!this.visible(this.corners(this.settings.$next_tip))&&this.settings.attempts0&&arguments[0]instanceof a)e=arguments[0];else{if(!this.settings.$target||/body/i.test(this.settings.$target.selector))return!1;e=this.settings.$target}return e.length<1?(b.console&&console.error("element not valid",e),!1):(c=a(this.settings.template.expose),this.settings.$body.append(c),c.css({top:e.offset().top,left:e.offset().left,width:e.outerWidth(!0),height:e.outerHeight(!0)}),d=a(this.settings.template.expose_cover),f={zIndex:e.css("z-index"),position:e.css("position")},g=null==e.attr("class")?"":e.attr("class"),e.css("z-index",parseInt(c.css("z-index"))+1),"static"==f.position&&e.css("position","relative"),e.data("expose-css",f),e.data("orig-class",g),e.attr("class",g+" "+this.settings.expose_add_class),d.css({top:e.offset().top,left:e.offset().left,width:e.outerWidth(!0),height:e.outerHeight(!0)}),this.settings.modal&&this.show_modal(),this.settings.$body.append(d),c.addClass(h),d.addClass(h),e.data("expose",h),this.settings.post_expose_callback(this.settings.$li.index(),this.settings.$next_tip,e),void this.add_exposed(e))},un_expose:function(){var c,d,e,f,g,h=!1;if(arguments.length>0&&arguments[0]instanceof a)d=arguments[0];else{if(!this.settings.$target||/body/i.test(this.settings.$target.selector))return!1;d=this.settings.$target}return d.length<1?(b.console&&console.error("element not valid",d),!1):(c=d.data("expose"),e=a("."+c),arguments.length>1&&(h=arguments[1]),h===!0?a(".joyride-expose-wrapper,.joyride-expose-cover").remove():e.remove(),f=d.data("expose-css"),"auto"==f.zIndex?d.css("z-index",""):d.css("z-index",f.zIndex),f.position!=d.css("position")&&("static"==f.position?d.css("position",""):d.css("position",f.position)),g=d.data("orig-class"),d.attr("class",g),d.removeData("orig-classes"),d.removeData("expose"),d.removeData("expose-z-index"),void this.remove_exposed(d))},add_exposed:function(b){this.settings.exposed=this.settings.exposed||[],b instanceof a||"object"==typeof b?this.settings.exposed.push(b[0]):"string"==typeof b&&this.settings.exposed.push(b)},remove_exposed:function(b){var c,d;for(b instanceof a?c=b[0]:"string"==typeof b&&(c=b),this.settings.exposed=this.settings.exposed||[],d=this.settings.exposed.length;d--;)if(this.settings.exposed[d]==c)return void this.settings.exposed.splice(d,1)},center:function(){var c=a(b);return this.settings.$next_tip.css({top:(c.height()-this.settings.$next_tip.outerHeight())/2+c.scrollTop(),left:(c.width()-this.settings.$next_tip.outerWidth())/2+c.scrollLeft()}),!0},bottom:function(){return/bottom/i.test(this.settings.tip_settings.tip_location)},top:function(){return/top/i.test(this.settings.tip_settings.tip_location)},right:function(){return/right/i.test(this.settings.tip_settings.tip_location)},left:function(){return/left/i.test(this.settings.tip_settings.tip_location)},corners:function(c){var d=a(b),e=d.height()/2,f=Math.ceil(this.settings.$target.offset().top-e+this.settings.$next_tip.outerHeight()),g=d.width()+d.scrollLeft(),h=d.height()+f,i=d.height()+d.scrollTop(),j=d.scrollTop();return j>f&&(j=0>f?0:f),h>i&&(i=h),[c.offset().topc.offset().left]},visible:function(a){for(var b=a.length;b--;)if(a[b])return!1;return!0},nub_position:function(a,b,c){a.addClass("auto"===b?c:b)},startTimer:function(){this.settings.$li.length?this.settings.automate=setTimeout(function(){this.hide(),this.show(),this.startTimer()}.bind(this),this.settings.timer):clearTimeout(this.settings.automate)},end:function(b){this.settings.cookie_monster&&a.cookie(this.settings.cookie_name,"ridden",{expires:this.settings.cookie_expires,domain:this.settings.cookie_domain}),this.settings.timer>0&&clearTimeout(this.settings.automate),this.settings.modal&&this.settings.expose&&this.un_expose(),a(this.scope).off("keyup.joyride"),this.settings.$next_tip.data("closed",!0),this.settings.riding=!1,a(".joyride-modal-bg").hide(),this.settings.$current_tip.hide(),("undefined"==typeof b||b===!1)&&(this.settings.post_step_callback(this.settings.$li.index(),this.settings.$current_tip),this.settings.post_ride_callback(this.settings.$li.index(),this.settings.$current_tip)),a(".joyride-tip-guide").remove()},off:function(){a(this.scope).off(".joyride"),a(b).off(".joyride"),a(".joyride-close-tip, .joyride-next-tip, .joyride-modal-bg").off(".joyride"),a(".joyride-tip-guide, .joyride-modal-bg").remove(),clearTimeout(this.settings.automate),this.settings={}},reflow:function(){}}}(jQuery,window,window.document),function(a,b){"use strict";Foundation.libs["magellan-expedition"]={name:"magellan-expedition",version:"5.5.1",settings:{active_class:"active",threshold:0,destination_threshold:20,throttle_delay:30,fixed_top:0,offset_by_height:!0,duration:700,easing:"swing"},init:function(a,b,c){Foundation.inherit(this,"throttle"),this.bindings(b,c)},events:function(){var c=this,d=c.S,e=c.settings;c.set_expedition_position(),d(c.scope).off(".magellan").on("click.fndtn.magellan","["+c.add_namespace("data-magellan-arrival")+'] a[href^="#"]',function(b){b.preventDefault();var d=a(this).closest("["+c.attr_name()+"]"),e=d.data("magellan-expedition-init"),f=this.hash.split("#").join(""),g=a('a[name="'+f+'"]');0===g.length&&(g=a("#"+f));var h=g.offset().top-e.destination_threshold+1;e.offset_by_height&&(h-=d.outerHeight()),a("html, body").stop().animate({scrollTop:h},e.duration,e.easing,function(){history.pushState?history.pushState(null,null,"#"+f):location.hash="#"+f})}).on("scroll.fndtn.magellan",c.throttle(this.check_for_arrivals.bind(this),e.throttle_delay)),a(b).on("resize.fndtn.magellan",c.throttle(this.set_expedition_position.bind(this),e.throttle_delay))},check_for_arrivals:function(){var a=this;a.update_arrivals(),a.update_expedition_positions()},set_expedition_position:function(){var b=this;a("["+this.attr_name()+"=fixed]",b.scope).each(function(){var c,d,e=a(this),f=e.data("magellan-expedition-init"),g=e.attr("styles");e.attr("style",""),c=e.offset().top+f.threshold,d=parseInt(e.data("magellan-fixed-top")),isNaN(d)||(b.settings.fixed_top=d),e.data(b.data_attr("magellan-top-offset"),c),e.attr("style",g)})},update_expedition_positions:function(){var c=this,d=a(b).scrollTop();a("["+this.attr_name()+"=fixed]",c.scope).each(function(){var b=a(this),e=b.data("magellan-expedition-init"),f=b.attr("style"),g=b.data("magellan-top-offset");if(d+c.settings.fixed_top>=g){var h=b.prev("["+c.add_namespace("data-magellan-expedition-clone")+"]");0===h.length&&(h=b.clone(),h.removeAttr(c.attr_name()),h.attr(c.add_namespace("data-magellan-expedition-clone"),""),b.before(h)),b.css({position:"fixed",top:e.fixed_top}).addClass("fixed")}else b.prev("["+c.add_namespace("data-magellan-expedition-clone")+"]").remove(),b.attr("style",f).css("position","").css("top","").removeClass("fixed")})},update_arrivals:function(){var c=this,d=a(b).scrollTop();a("["+this.attr_name()+"]",c.scope).each(function(){var b=a(this),e=b.data(c.attr_name(!0)+"-init"),f=c.offsets(b,d),g=b.find("["+c.add_namespace("data-magellan-arrival")+"]"),h=!1;f.each(function(a,d){if(d.viewport_offset>=d.top_offset){var f=b.find("["+c.add_namespace("data-magellan-arrival")+"]");return f.not(d.arrival).removeClass(e.active_class),d.arrival.addClass(e.active_class),h=!0,!0}}),h||g.removeClass(e.active_class)})},offsets:function(b,c){var d=this,e=b.data(d.attr_name(!0)+"-init"),f=c;return b.find("["+d.add_namespace("data-magellan-arrival")+"]").map(function(){var c=a(this).data(d.data_attr("magellan-arrival")),g=a("["+d.add_namespace("data-magellan-destination")+"="+c+"]");if(g.length>0){var h=g.offset().top-e.destination_threshold;return e.offset_by_height&&(h-=b.outerHeight()),h=Math.floor(h),{destination:g,arrival:a(this),top_offset:h,viewport_offset:f}}}).sort(function(a,b){return a.top_offsetb.top_offset?1:0})},data_attr:function(a){return this.namespace.length>0?this.namespace+"-"+a:a},off:function(){this.S(this.scope).off(".magellan"),this.S(b).off(".magellan")},reflow:function(){var b=this;a("["+b.add_namespace("data-magellan-expedition-clone")+"]",b.scope).remove()}}}(jQuery,window,window.document),function(a){"use strict";Foundation.libs.offcanvas={name:"offcanvas",version:"5.5.1",settings:{open_method:"move",close_on_click:!1},init:function(a,b,c){this.bindings(b,c)},events:function(){var b=this,c=b.S,d="",e="",f="";"move"===this.settings.open_method?(d="move-",e="right",f="left"):"overlap_single"===this.settings.open_method?(d="offcanvas-overlap-",e="right",f="left"):"overlap"===this.settings.open_method&&(d="offcanvas-overlap"),c(this.scope).off(".offcanvas").on("click.fndtn.offcanvas",".left-off-canvas-toggle",function(f){b.click_toggle_class(f,d+e),"overlap"!==b.settings.open_method&&c(".left-submenu").removeClass(d+e),a(".left-off-canvas-toggle").attr("aria-expanded","true")}).on("click.fndtn.offcanvas",".left-off-canvas-menu a",function(f){var g=b.get_settings(f),h=c(this).parent();!g.close_on_click||h.hasClass("has-submenu")||h.hasClass("back")?c(this).parent().hasClass("has-submenu")?(f.preventDefault(),c(this).siblings(".left-submenu").toggleClass(d+e)):h.hasClass("back")&&(f.preventDefault(),h.parent().removeClass(d+e)):(b.hide.call(b,d+e,b.get_wrapper(f)),h.parent().removeClass(d+e)),a(".left-off-canvas-toggle").attr("aria-expanded","true")}).on("click.fndtn.offcanvas",".right-off-canvas-toggle",function(e){b.click_toggle_class(e,d+f),"overlap"!==b.settings.open_method&&c(".right-submenu").removeClass(d+f),a(".right-off-canvas-toggle").attr("aria-expanded","true")}).on("click.fndtn.offcanvas",".right-off-canvas-menu a",function(e){var g=b.get_settings(e),h=c(this).parent();!g.close_on_click||h.hasClass("has-submenu")||h.hasClass("back")?c(this).parent().hasClass("has-submenu")?(e.preventDefault(),c(this).siblings(".right-submenu").toggleClass(d+f)):h.hasClass("back")&&(e.preventDefault(),h.parent().removeClass(d+f)):(b.hide.call(b,d+f,b.get_wrapper(e)),h.parent().removeClass(d+f)),a(".right-off-canvas-toggle").attr("aria-expanded","true")}).on("click.fndtn.offcanvas",".exit-off-canvas",function(g){b.click_remove_class(g,d+f),c(".right-submenu").removeClass(d+f),e&&(b.click_remove_class(g,d+e),c(".left-submenu").removeClass(d+f)),a(".right-off-canvas-toggle").attr("aria-expanded","true")}).on("click.fndtn.offcanvas",".exit-off-canvas",function(c){b.click_remove_class(c,d+f),a(".left-off-canvas-toggle").attr("aria-expanded","false"),e&&(b.click_remove_class(c,d+e),a(".right-off-canvas-toggle").attr("aria-expanded","false"))})},toggle:function(a,b){b=b||this.get_wrapper(),b.is("."+a)?this.hide(a,b):this.show(a,b)},show:function(a,b){b=b||this.get_wrapper(),b.trigger("open").trigger("open.fndtn.offcanvas"),b.addClass(a)},hide:function(a,b){b=b||this.get_wrapper(),b.trigger("close").trigger("close.fndtn.offcanvas"),b.removeClass(a)},click_toggle_class:function(a,b){a.preventDefault();var c=this.get_wrapper(a);this.toggle(b,c)},click_remove_class:function(a,b){a.preventDefault();var c=this.get_wrapper(a);this.hide(b,c)},get_settings:function(a){var b=this.S(a.target).closest("["+this.attr_name()+"]");return b.data(this.attr_name(!0)+"-init")||this.settings},get_wrapper:function(a){var b=this.S(a?a.target:this.scope).closest(".off-canvas-wrap");return 0===b.length&&(b=this.S(".off-canvas-wrap")),b},reflow:function(){}}}(jQuery,window,window.document),function(a,b,c,d){"use strict";var e=function(){},f=function(e,f){if(e.hasClass(f.slides_container_class))return this;var j,k,l,m,n,o,p=this,q=e,r=0,s=!1;p.slides=function(){return q.children(f.slide_selector)
+},p.slides().first().addClass(f.active_slide_class),p.update_slide_number=function(b){f.slide_number&&(k.find("span:first").text(parseInt(b)+1),k.find("span:last").text(p.slides().length)),f.bullets&&(l.children().removeClass(f.bullets_active_class),a(l.children().get(b)).addClass(f.bullets_active_class))},p.update_active_link=function(b){var c=a('[data-orbit-link="'+p.slides().eq(b).attr("data-orbit-slide")+'"]');c.siblings().removeClass(f.bullets_active_class),c.addClass(f.bullets_active_class)},p.build_markup=function(){q.wrap('
'),j=q.parent(),q.addClass(f.slides_container_class),f.stack_on_small&&j.addClass(f.stack_on_small_class),f.navigation_arrows&&(j.append(a(' ').addClass(f.prev_class)),j.append(a(' ').addClass(f.next_class))),f.timer&&(m=a("").addClass(f.timer_container_class),m.append("
"),m.append(a("").addClass(f.timer_progress_class)),m.addClass(f.timer_paused_class),j.append(m)),f.slide_number&&(k=a("
").addClass(f.slide_number_class),k.append("
"+f.slide_number_text+"
"),j.append(k)),f.bullets&&(l=a("
").addClass(f.bullets_container_class),j.append(l),l.wrap('
'),p.slides().each(function(b){var c=a("").attr("data-orbit-slide",b).on("click",p.link_bullet);l.append(c)}))},p._goto=function(b,c){if(b===r)return!1;"object"==typeof o&&o.restart();var d=p.slides(),e="next";if(s=!0,r>b&&(e="prev"),b>=d.length){if(!f.circular)return!1;b=0}else if(0>b){if(!f.circular)return!1;b=d.length-1}var g=a(d.get(r)),h=a(d.get(b));g.css("zIndex",2),g.removeClass(f.active_slide_class),h.css("zIndex",4).addClass(f.active_slide_class),q.trigger("before-slide-change.fndtn.orbit"),f.before_slide_change(),p.update_active_link(b);var i=function(){var a=function(){r=b,s=!1,c===!0&&(o=p.create_timer(),o.start()),p.update_slide_number(r),q.trigger("after-slide-change.fndtn.orbit",[{slide_number:r,total_slides:d.length}]),f.after_slide_change(r,d.length)};q.outerHeight()!=h.outerHeight()&&f.variable_height?q.animate({height:h.outerHeight()},250,"linear",a):a()};if(1===d.length)return i(),!1;var j=function(){"next"===e&&n.next(g,h,i),"prev"===e&&n.prev(g,h,i)};h.outerHeight()>q.outerHeight()&&f.variable_height?q.animate({height:h.outerHeight()},250,"linear",j):j()},p.next=function(a){a.stopImmediatePropagation(),a.preventDefault(),p._goto(r+1)},p.prev=function(a){a.stopImmediatePropagation(),a.preventDefault(),p._goto(r-1)},p.link_custom=function(b){b.preventDefault();var c=a(this).attr("data-orbit-link");if("string"==typeof c&&""!=(c=a.trim(c))){var d=j.find("[data-orbit-slide="+c+"]");-1!=d.index()&&p._goto(d.index())}},p.link_bullet=function(){var b=a(this).attr("data-orbit-slide");if("string"==typeof b&&""!=(b=a.trim(b)))if(isNaN(parseInt(b))){var c=j.find("[data-orbit-slide="+b+"]");-1!=c.index()&&p._goto(c.index()+1)}else p._goto(parseInt(b))},p.timer_callback=function(){p._goto(r+1,!0)},p.compute_dimensions=function(){var b=a(p.slides().get(r)),c=b.outerHeight();f.variable_height||p.slides().each(function(){a(this).outerHeight()>c&&(c=a(this).outerHeight())}),q.height(c)},p.create_timer=function(){var a=new g(j.find("."+f.timer_container_class),f,p.timer_callback);return a},p.stop_timer=function(){"object"==typeof o&&o.stop()},p.toggle_timer=function(){var a=j.find("."+f.timer_container_class);a.hasClass(f.timer_paused_class)?("undefined"==typeof o&&(o=p.create_timer()),o.start()):"object"==typeof o&&o.stop()},p.init=function(){p.build_markup(),f.timer&&(o=p.create_timer(),Foundation.utils.image_loaded(this.slides().children("img"),o.start)),n=new i(f,q),"slide"===f.animation&&(n=new h(f,q)),j.on("click","."+f.next_class,p.next),j.on("click","."+f.prev_class,p.prev),f.next_on_click&&j.on("click","."+f.slides_container_class+" [data-orbit-slide]",p.link_bullet),j.on("click",p.toggle_timer),f.swipe&&j.on("touchstart.fndtn.orbit",function(a){a.touches||(a=a.originalEvent);var b={start_page_x:a.touches[0].pageX,start_page_y:a.touches[0].pageY,start_time:(new Date).getTime(),delta_x:0,is_scrolling:d};j.data("swipe-transition",b),a.stopPropagation()}).on("touchmove.fndtn.orbit",function(a){if(a.touches||(a=a.originalEvent),!(a.touches.length>1||a.scale&&1!==a.scale)){var b=j.data("swipe-transition");if("undefined"==typeof b&&(b={}),b.delta_x=a.touches[0].pageX-b.start_page_x,"undefined"==typeof b.is_scrolling&&(b.is_scrolling=!!(b.is_scrolling||Math.abs(b.delta_x)0?b(this.scope).on("open.fndtn.reveal",this.settings.open).on("opened.fndtn.reveal",this.settings.opened).on("opened.fndtn.reveal",this.open_video).on("close.fndtn.reveal",this.settings.close).on("closed.fndtn.reveal",this.settings.closed).on("closed.fndtn.reveal",this.close_video):b(this.scope).on("open.fndtn.reveal","["+a.attr_name()+"]",this.settings.open).on("opened.fndtn.reveal","["+a.attr_name()+"]",this.settings.opened).on("opened.fndtn.reveal","["+a.attr_name()+"]",this.open_video).on("close.fndtn.reveal","["+a.attr_name()+"]",this.settings.close).on("closed.fndtn.reveal","["+a.attr_name()+"]",this.settings.closed).on("closed.fndtn.reveal","["+a.attr_name()+"]",this.close_video),!0},key_up_on:function(){var a=this;return a.S("body").off("keyup.fndtn.reveal").on("keyup.fndtn.reveal",function(b){var c=a.S("["+a.attr_name()+"].open"),d=c.data(a.attr_name(!0)+"-init")||a.settings;d&&27===b.which&&d.close_on_esc&&!a.locked&&a.close.call(a,c)}),!0},key_up_off:function(){return this.S("body").off("keyup.fndtn.reveal"),!0},open:function(c,d){var e,f=this;c?"undefined"!=typeof c.selector?e=f.S("#"+c.data(f.data_attr("reveal-id"))).first():(e=f.S(this.scope),d=c):e=f.S(this.scope);var g=e.data(f.attr_name(!0)+"-init");if(g=g||this.settings,e.hasClass("open")&&c.attr("data-reveal-id")==e.attr("id"))return f.close(e);if(!e.hasClass("open")){var h=f.S("["+f.attr_name()+"].open");if("undefined"==typeof e.data("css-top")&&e.data("css-top",parseInt(e.css("top"),10)).data("offset",this.cache_offset(e)),this.key_up_on(e),e.on("open.fndtn.reveal").trigger("open.fndtn.reveal"),h.length<1&&this.toggle_bg(e,!0),"string"==typeof d&&(d={url:d}),"undefined"!=typeof d&&d.url){var i="undefined"!=typeof d.success?d.success:null;a.extend(d,{success:function(b,c,d){if(a.isFunction(i)){var j=i(b,c,d);"string"==typeof j&&(b=j)}e.html(b),f.S(e).foundation("section","reflow"),f.S(e).children().foundation(),h.length>0&&(g.multiple_opened?this.to_back(h):this.hide(h,g.css.close)),f.show(e,g.css.open)}}),a.ajax(d)}else h.length>0&&(g.multiple_opened?this.to_back(h):this.hide(h,g.css.close)),this.show(e,g.css.open)}f.S(b).trigger("resize")},close:function(b){var b=b&&b.length?b:this.S(this.scope),c=this.S("["+this.attr_name()+"].open"),d=b.data(this.attr_name(!0)+"-init")||this.settings;c.length>0&&(this.locked=!0,this.key_up_off(b),b.trigger("close").trigger("close.fndtn.reveal"),(d.multiple_opened&&1===c.length||!d.multiple_opened||b.length>1)&&(this.toggle_bg(b,!1),this.to_front(b)),d.multiple_opened?(this.hide(b,d.css.close,d),this.to_front(a(a.makeArray(c).reverse()[1]))):this.hide(c,d.css.close,d))},close_targets:function(){var a="."+this.settings.dismiss_modal_class;return this.settings.close_on_background_click?a+", ."+this.settings.bg_class:a},toggle_bg:function(b,c){0===this.S("."+this.settings.bg_class).length&&(this.settings.bg=a("
",{"class":this.settings.bg_class}).appendTo("body").hide());var e=this.settings.bg.filter(":visible").length>0;c!=e&&((c==d?e:!c)?this.hide(this.settings.bg):this.show(this.settings.bg))},show:function(c,d){if(d){var f=c.data(this.attr_name(!0)+"-init")||this.settings,g=f.root_element;if(0===c.parent(g).length){var h=c.wrap('
').parent();c.on("closed.fndtn.reveal.wrapped",function(){c.detach().appendTo(h),c.unwrap().unbind("closed.fndtn.reveal.wrapped")}),c.detach().appendTo(g)}var i=e(f.animation);if(i.animate||(this.locked=!1),i.pop){d.top=a(b).scrollTop()-c.data("offset")+"px";var j={top:a(b).scrollTop()+c.data("css-top")+"px",opacity:1};return setTimeout(function(){return c.css(d).animate(j,f.animation_speed,"linear",function(){this.locked=!1,c.trigger("opened").trigger("opened.fndtn.reveal")}.bind(this)).addClass("open")}.bind(this),f.animation_speed/2)}if(i.fade){d.top=a(b).scrollTop()+c.data("css-top")+"px";var j={opacity:1};return setTimeout(function(){return c.css(d).animate(j,f.animation_speed,"linear",function(){this.locked=!1,c.trigger("opened").trigger("opened.fndtn.reveal")}.bind(this)).addClass("open")}.bind(this),f.animation_speed/2)}return c.css(d).show().css({opacity:1}).addClass("open").trigger("opened").trigger("opened.fndtn.reveal")}var f=this.settings;return e(f.animation).fade?c.fadeIn(f.animation_speed/2):(this.locked=!1,c.show())},to_back:function(a){a.addClass("toback")},to_front:function(a){a.removeClass("toback")},hide:function(c,d){if(d){var f=c.data(this.attr_name(!0)+"-init");f=f||this.settings;var g=e(f.animation);if(g.animate||(this.locked=!1),g.pop){var h={top:-a(b).scrollTop()-c.data("offset")+"px",opacity:0};return setTimeout(function(){return c.animate(h,f.animation_speed,"linear",function(){this.locked=!1,c.css(d).trigger("closed").trigger("closed.fndtn.reveal")}.bind(this)).removeClass("open")}.bind(this),f.animation_speed/2)}if(g.fade){var h={opacity:0};return setTimeout(function(){return c.animate(h,f.animation_speed,"linear",function(){this.locked=!1,c.css(d).trigger("closed").trigger("closed.fndtn.reveal")}.bind(this)).removeClass("open")}.bind(this),f.animation_speed/2)}return c.hide().css(d).removeClass("open").trigger("closed").trigger("closed.fndtn.reveal")}var f=this.settings;return e(f.animation).fade?c.fadeOut(f.animation_speed/2):c.hide()},close_video:function(b){var c=a(".flex-video",b.target),d=a("iframe",c);d.length>0&&(d.attr("data-src",d[0].src),d.attr("src",d.attr("src")),c.hide())},open_video:function(b){var c=a(".flex-video",b.target),e=c.find("iframe");if(e.length>0){var f=e.attr("data-src");if("string"==typeof f)e[0].src=e.attr("data-src");else{var g=e[0].src;e[0].src=d,e[0].src=g}c.show()}},data_attr:function(a){return this.namespace.length>0?this.namespace+"-"+a:a},cache_offset:function(a){var b=a.show().height()+parseInt(a.css("top"),10);return a.hide(),b},off:function(){a(this.scope).off(".fndtn.reveal")},reflow:function(){}}}(jQuery,window,window.document),function(a,b){"use strict";Foundation.libs.slider={name:"slider",version:"5.5.1",settings:{start:0,end:100,step:1,precision:null,initial:null,display_selector:"",vertical:!1,trigger_input_change:!1,on_change:function(){}},cache:{},init:function(a,b,c){Foundation.inherit(this,"throttle"),this.bindings(b,c),this.reflow()},events:function(){var c=this;a(this.scope).off(".slider").on("mousedown.fndtn.slider touchstart.fndtn.slider pointerdown.fndtn.slider","["+c.attr_name()+"]:not(.disabled, [disabled]) .range-slider-handle",function(b){c.cache.active||(b.preventDefault(),c.set_active_slider(a(b.target)))}).on("mousemove.fndtn.slider touchmove.fndtn.slider pointermove.fndtn.slider",function(d){if(c.cache.active)if(d.preventDefault(),a.data(c.cache.active[0],"settings").vertical){var e=0;d.pageY||(e=b.scrollY),c.calculate_position(c.cache.active,c.get_cursor_position(d,"y")+e)}else c.calculate_position(c.cache.active,c.get_cursor_position(d,"x"))}).on("mouseup.fndtn.slider touchend.fndtn.slider pointerup.fndtn.slider",function(){c.remove_active_slider()}).on("change.fndtn.slider",function(){c.settings.on_change()}),c.S(b).on("resize.fndtn.slider",c.throttle(function(){c.reflow()},300))},get_cursor_position:function(a,b){var c,d="page"+b.toUpperCase(),e="client"+b.toUpperCase();return"undefined"!=typeof a[d]?c=a[d]:"undefined"!=typeof a.originalEvent[e]?c=a.originalEvent[e]:a.originalEvent.touches&&a.originalEvent.touches[0]&&"undefined"!=typeof a.originalEvent.touches[0][e]?c=a.originalEvent.touches[0][e]:a.currentPoint&&"undefined"!=typeof a.currentPoint[b]&&(c=a.currentPoint[b]),c},set_active_slider:function(a){this.cache.active=a},remove_active_slider:function(){this.cache.active=null},calculate_position:function(b,c){var d=this,e=a.data(b[0],"settings"),f=(a.data(b[0],"handle_l"),a.data(b[0],"handle_o"),a.data(b[0],"bar_l")),g=a.data(b[0],"bar_o");requestAnimationFrame(function(){var a;a=Foundation.rtl&&!e.vertical?d.limit_to((g+f-c)/f,0,1):d.limit_to((c-g)/f,0,1),a=e.vertical?1-a:a;var h=d.normalized_value(a,e.start,e.end,e.step,e.precision);d.set_ui(b,h)})},set_ui:function(b,c){var d=a.data(b[0],"settings"),e=a.data(b[0],"handle_l"),f=a.data(b[0],"bar_l"),g=this.normalized_percentage(c,d.start,d.end),h=g*(f-e)-1,i=100*g,j=b.parent(),k=b.parent().children("input[type=hidden]");Foundation.rtl&&!d.vertical&&(h=-h),h=d.vertical?-h+f-e+1:h,this.set_translate(b,h,d.vertical),d.vertical?b.siblings(".range-slider-active-segment").css("height",i+"%"):b.siblings(".range-slider-active-segment").css("width",i+"%"),j.attr(this.attr_name(),c).trigger("change").trigger("change.fndtn.slider"),k.val(c),d.trigger_input_change&&k.trigger("change"),b[0].hasAttribute("aria-valuemin")||b.attr({"aria-valuemin":d.start,"aria-valuemax":d.end}),b.attr("aria-valuenow",c),""!=d.display_selector&&a(d.display_selector).each(function(){this.hasOwnProperty("value")?a(this).val(c):a(this).text(c)})},normalized_percentage:function(a,b,c){return Math.min(1,(a-b)/(c-b))},normalized_value:function(a,b,c,d,e){var f=c-b,g=a*f,h=(g-g%d)/d,i=g%d,j=i>=.5*d?d:0;return(h*d+j+b).toFixed(e)},set_translate:function(b,c,d){d?a(b).css("-webkit-transform","translateY("+c+"px)").css("-moz-transform","translateY("+c+"px)").css("-ms-transform","translateY("+c+"px)").css("-o-transform","translateY("+c+"px)").css("transform","translateY("+c+"px)"):a(b).css("-webkit-transform","translateX("+c+"px)").css("-moz-transform","translateX("+c+"px)").css("-ms-transform","translateX("+c+"px)").css("-o-transform","translateX("+c+"px)").css("transform","translateX("+c+"px)")},limit_to:function(a,b,c){return Math.min(Math.max(a,b),c)},initialize_settings:function(b){var c,d=a.extend({},this.settings,this.data_options(a(b).parent()));null===d.precision&&(c=(""+d.step).match(/\.([\d]*)/),d.precision=c&&c[1]?c[1].length:0),d.vertical?(a.data(b,"bar_o",a(b).parent().offset().top),a.data(b,"bar_l",a(b).parent().outerHeight()),a.data(b,"handle_o",a(b).offset().top),a.data(b,"handle_l",a(b).outerHeight())):(a.data(b,"bar_o",a(b).parent().offset().left),a.data(b,"bar_l",a(b).parent().outerWidth()),a.data(b,"handle_o",a(b).offset().left),a.data(b,"handle_l",a(b).outerWidth())),a.data(b,"bar",a(b).parent()),a.data(b,"settings",d)},set_initial_position:function(b){var c=a.data(b.children(".range-slider-handle")[0],"settings"),d="number"!=typeof c.initial||isNaN(c.initial)?Math.floor(.5*(c.end-c.start)/c.step)*c.step+c.start:c.initial,e=b.children(".range-slider-handle");this.set_ui(e,d)},set_value:function(b){var c=this;a("["+c.attr_name()+"]",this.scope).each(function(){a(this).attr(c.attr_name(),b)}),a(this.scope).attr(c.attr_name())&&a(this.scope).attr(c.attr_name(),b),c.reflow()},reflow:function(){var b=this;b.S("["+this.attr_name()+"]").each(function(){var c=a(this).children(".range-slider-handle")[0],d=a(this).attr(b.attr_name());b.initialize_settings(c),d?b.set_ui(a(c),parseFloat(d)):b.set_initial_position(a(this))})}}}(jQuery,window,window.document),function(a,b,c,d){"use strict";Foundation.libs.tab={name:"tab",version:"5.5.1",settings:{active_class:"active",callback:function(){},deep_linking:!1,scroll_to_content:!0,is_hover:!1},default_tab_hashes:[],init:function(a,c,d){var e=this,f=this.S;this.bindings(c,d),e.entry_location=b.location.href,this.handle_location_hash_change(),f("["+this.attr_name()+"] > .active > a",this.scope).each(function(){e.default_tab_hashes.push(this.hash)})},events:function(){var a=this,c=this.S,d=function(b){var d=c(this).closest("["+a.attr_name()+"]").data(a.attr_name(!0)+"-init");(!d.is_hover||Modernizr.touch)&&(b.preventDefault(),b.stopPropagation(),a.toggle_active_tab(c(this).parent()))};c(this.scope).off(".tab").on("focus.fndtn.tab","["+this.attr_name()+"] > * > a",d).on("click.fndtn.tab","["+this.attr_name()+"] > * > a",d).on("mouseenter.fndtn.tab","["+this.attr_name()+"] > * > a",function(){var b=c(this).closest("["+a.attr_name()+"]").data(a.attr_name(!0)+"-init");b.is_hover&&a.toggle_active_tab(c(this).parent())}),c(b).on("hashchange.fndtn.tab",function(b){b.preventDefault(),a.handle_location_hash_change()})},handle_location_hash_change:function(){var b=this,c=this.S;c("["+this.attr_name()+"]",this.scope).each(function(){var e=c(this).data(b.attr_name(!0)+"-init");if(e.deep_linking){var f;if(f=e.scroll_to_content?b.scope.location.hash:b.scope.location.hash.replace("fndtn-",""),""!=f){var g=c(f);if(g.hasClass("content")&&g.parent().hasClass("tabs-content"))b.toggle_active_tab(a("["+b.attr_name()+"] > * > a[href="+f+"]").parent());else{var h=g.closest(".content").attr("id");h!=d&&b.toggle_active_tab(a("["+b.attr_name()+"] > * > a[href=#"+h+"]").parent(),f)}}else for(var i=0;i * > a[href="+b.default_tab_hashes[i]+"]").parent())}})},toggle_active_tab:function(e,f){var g=this,h=g.S,i=e.closest("["+this.attr_name()+"]"),j=e.find("a"),k=e.children("a").first(),l="#"+k.attr("href").split("#")[1],m=h(l),n=e.siblings(),o=i.data(this.attr_name(!0)+"-init"),p=function(b){var d,e=a(this),f=a(this).parents("li").prev().children('[role="tab"]'),g=a(this).parents("li").next().children('[role="tab"]');switch(b.keyCode){case 37:d=f;break;case 39:d=g;break;default:d=!1}d.length&&(e.attr({tabindex:"-1","aria-selected":null}),d.attr({tabindex:"0","aria-selected":!0}).focus()),a('[role="tabpanel"]').attr("aria-hidden","true"),a("#"+a(c.activeElement).attr("href").substring(1)).attr("aria-hidden",null)},q=function(a){var c=b.location.href===g.entry_location,d=o.scroll_to_content?g.default_tab_hashes[0]:c?b.location.hash:"fndtn-"+g.default_tab_hashes[0].replace("#","");c&&a===d||(b.location.hash=a)};h(this).data(this.data_attr("tab-content"))&&(l="#"+h(this).data(this.data_attr("tab-content")).split("#")[1],m=h(l)),o.deep_linking&&(o.scroll_to_content?(q(f||l),f==d||f==l?e.parent()[0].scrollIntoView():h(l)[0].scrollIntoView()):q(f!=d?"fndtn-"+f.replace("#",""):"fndtn-"+l.replace("#",""))),e.addClass(o.active_class).triggerHandler("opened"),j.attr({"aria-selected":"true",tabindex:0}),n.removeClass(o.active_class),n.find("a").attr({"aria-selected":"false",tabindex:-1}),m.siblings().removeClass(o.active_class).attr({"aria-hidden":"true",tabindex:-1}),m.addClass(o.active_class).attr("aria-hidden","false").removeAttr("tabindex"),o.callback(e),m.triggerHandler("toggled",[e]),i.triggerHandler("toggled",[m]),j.off("keydown").on("keydown",p)},data_attr:function(a){return this.namespace.length>0?this.namespace+"-"+a:a},off:function(){},reflow:function(){}}}(jQuery,window,window.document),function(a,b){"use strict";Foundation.libs.tooltip={name:"tooltip",version:"5.5.1",settings:{additional_inheritable_classes:[],tooltip_class:".tooltip",append_to:"body",touch_close_text:"Tap To Close",disable_for_touch:!1,hover_delay:200,show_on:"all",tip_template:function(a,b){return''+b+' '}},cache:{},init:function(a,b,c){Foundation.inherit(this,"random_str"),this.bindings(b,c)},should_show:function(b){var c=a.extend({},this.settings,this.data_options(b));return"all"===c.show_on?!0:this.small()&&"small"===c.show_on?!0:this.medium()&&"medium"===c.show_on?!0:this.large()&&"large"===c.show_on?!0:!1},medium:function(){return matchMedia(Foundation.media_queries.medium).matches},large:function(){return matchMedia(Foundation.media_queries.large).matches},events:function(b){var c=this,d=c.S;c.create(this.S(b)),a(this.scope).off(".tooltip").on("mouseenter.fndtn.tooltip mouseleave.fndtn.tooltip touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip","["+this.attr_name()+"]",function(b){var e=d(this),f=a.extend({},c.settings,c.data_options(e)),g=!1;if(Modernizr.touch&&/touchstart|MSPointerDown/i.test(b.type)&&d(b.target).is("a"))return!1;if(/mouse/i.test(b.type)&&c.ie_touch(b))return!1;if(e.hasClass("open"))Modernizr.touch&&/touchstart|MSPointerDown/i.test(b.type)&&b.preventDefault(),c.hide(e);else{if(f.disable_for_touch&&Modernizr.touch&&/touchstart|MSPointerDown/i.test(b.type))return;!f.disable_for_touch&&Modernizr.touch&&/touchstart|MSPointerDown/i.test(b.type)&&(b.preventDefault(),d(f.tooltip_class+".open").hide(),g=!0),/enter|over/i.test(b.type)?this.timer=setTimeout(function(){c.showTip(e)}.bind(this),c.settings.hover_delay):"mouseout"===b.type||"mouseleave"===b.type?(clearTimeout(this.timer),c.hide(e)):c.showTip(e)}}).on("mouseleave.fndtn.tooltip touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip","["+this.attr_name()+"].open",function(b){return/mouse/i.test(b.type)&&c.ie_touch(b)?!1:void(("touch"!=a(this).data("tooltip-open-event-type")||"mouseleave"!=b.type)&&("mouse"==a(this).data("tooltip-open-event-type")&&/MSPointerDown|touchstart/i.test(b.type)?c.convert_to_touch(a(this)):c.hide(a(this))))}).on("DOMNodeRemoved DOMAttrModified","["+this.attr_name()+"]:not(a)",function(){c.hide(d(this))})},ie_touch:function(){return!1},showTip:function(a){var b=this.getTip(a);return this.should_show(a,b)?this.show(a):void 0},getTip:function(b){var c=this.selector(b),d=a.extend({},this.settings,this.data_options(b)),e=null;return c&&(e=this.S('span[data-selector="'+c+'"]'+d.tooltip_class)),"object"==typeof e?e:!1},selector:function(a){var b=a.attr("id"),c=a.attr(this.attr_name())||a.attr("data-selector");return(b&&b.length<1||!b)&&"string"!=typeof c&&(c=this.random_str(6),a.attr("data-selector",c).attr("aria-describedby",c)),b&&b.length>0?b:c},create:function(c){var d=this,e=a.extend({},this.settings,this.data_options(c)),f=this.settings.tip_template;"string"==typeof e.tip_template&&b.hasOwnProperty(e.tip_template)&&(f=b[e.tip_template]);var g=a(f(this.selector(c),a("
").html(c.attr("title")).html())),h=this.inheritable_classes(c);g.addClass(h).appendTo(e.append_to),Modernizr.touch&&(g.append(''+e.touch_close_text+" "),g.on("touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip",function(){d.hide(c)})),c.removeAttr("title").attr("title","")},reposition:function(b,c,d){var e,f,g,h,i;if(c.css("visibility","hidden").show(),e=b.data("width"),f=c.children(".nub"),g=f.outerHeight(),h=f.outerHeight(),c.css(this.small()?{width:"100%"}:{width:e?e:"auto"}),i=function(a,b,c,d,e){return a.css({top:b?b:"auto",bottom:d?d:"auto",left:e?e:"auto",right:c?c:"auto"}).end()},i(c,b.offset().top+b.outerHeight()+10,"auto","auto",b.offset().left),this.small())i(c,b.offset().top+b.outerHeight()+10,"auto","auto",12.5,a(this.scope).width()),c.addClass("tip-override"),i(f,-g,"auto","auto",b.offset().left);else{var j=b.offset().left;Foundation.rtl&&(f.addClass("rtl"),j=b.offset().left+b.outerWidth()-c.outerWidth()),i(c,b.offset().top+b.outerHeight()+10,"auto","auto",j),c.removeClass("tip-override"),d&&d.indexOf("tip-top")>-1?(Foundation.rtl&&f.addClass("rtl"),i(c,b.offset().top-c.outerHeight(),"auto","auto",j).removeClass("tip-override")):d&&d.indexOf("tip-left")>-1?(i(c,b.offset().top+b.outerHeight()/2-c.outerHeight()/2,"auto","auto",b.offset().left-c.outerWidth()-g).removeClass("tip-override"),f.removeClass("rtl")):d&&d.indexOf("tip-right")>-1&&(i(c,b.offset().top+b.outerHeight()/2-c.outerHeight()/2,"auto","auto",b.offset().left+b.outerWidth()+g).removeClass("tip-override"),f.removeClass("rtl"))}c.css("visibility","visible").hide()},small:function(){return matchMedia(Foundation.media_queries.small).matches&&!matchMedia(Foundation.media_queries.medium).matches},inheritable_classes:function(b){var c=a.extend({},this.settings,this.data_options(b)),d=["tip-top","tip-left","tip-bottom","tip-right","radius","round"].concat(c.additional_inheritable_classes),e=b.attr("class"),f=e?a.map(e.split(" "),function(b){return-1!==a.inArray(b,d)?b:void 0}).join(" "):"";return a.trim(f)},convert_to_touch:function(b){var c=this,d=c.getTip(b),e=a.extend({},c.settings,c.data_options(b));0===d.find(".tap-to-close").length&&(d.append(''+e.touch_close_text+" "),d.on("click.fndtn.tooltip.tapclose touchstart.fndtn.tooltip.tapclose MSPointerDown.fndtn.tooltip.tapclose",function(){c.hide(b)})),b.data("tooltip-open-event-type","touch")},show:function(a){var b=this.getTip(a);"touch"==a.data("tooltip-open-event-type")&&this.convert_to_touch(a),this.reposition(a,b,a.attr("class")),a.addClass("open"),b.fadeIn(150)},hide:function(a){var b=this.getTip(a);b.fadeOut(150,function(){b.find(".tap-to-close").remove(),b.off("click.fndtn.tooltip.tapclose MSPointerDown.fndtn.tapclose"),a.removeClass("open")})},off:function(){var b=this;this.S(this.scope).off(".fndtn.tooltip"),this.S(this.settings.tooltip_class).each(function(c){a("["+b.attr_name()+"]").eq(c).attr("title",a(this).text())}).remove()},reflow:function(){}}}(jQuery,window,window.document),function(a,b,c){"use strict";Foundation.libs.topbar={name:"topbar",version:"5.5.1",settings:{index:0,sticky_class:"sticky",custom_back_text:!0,back_text:"Back",mobile_show_parent_link:!0,is_hover:!0,scrolltop:!0,sticky_on:"all"},init:function(b,c,d){Foundation.inherit(this,"add_custom_rule register_media throttle");var e=this;e.register_media("topbar","foundation-mq-topbar"),this.bindings(c,d),e.S("["+this.attr_name()+"]",this.scope).each(function(){{var b=a(this),c=b.data(e.attr_name(!0)+"-init");e.S("section, .top-bar-section",this)}b.data("index",0);var d=b.parent();d.hasClass("fixed")||e.is_sticky(b,d,c)?(e.settings.sticky_class=c.sticky_class,e.settings.sticky_topbar=b,b.data("height",d.outerHeight()),b.data("stickyoffset",d.offset().top)):b.data("height",b.outerHeight()),c.assembled||e.assemble(b),c.is_hover?e.S(".has-dropdown",b).addClass("not-click"):e.S(".has-dropdown",b).removeClass("not-click"),e.add_custom_rule(".f-topbar-fixed { padding-top: "+b.data("height")+"px }"),d.hasClass("fixed")&&e.S("body").addClass("f-topbar-fixed")})},is_sticky:function(a,b,c){var d=b.hasClass(c.sticky_class),e=matchMedia(Foundation.media_queries.small).matches,f=matchMedia(Foundation.media_queries.medium).matches,g=matchMedia(Foundation.media_queries.large).matches;return d&&"all"===c.sticky_on?!0:d&&this.small()&&-1!==c.sticky_on.indexOf("small")&&e&&!f&&!g?!0:d&&this.medium()&&-1!==c.sticky_on.indexOf("medium")&&e&&f&&!g?!0:d&&this.large()&&-1!==c.sticky_on.indexOf("large")&&e&&f&&g?!0:d&&navigator.userAgent.match(/(iPad|iPhone|iPod)/g)?!0:!1},toggle:function(c){var d,e=this;d=c?e.S(c).closest("["+this.attr_name()+"]"):e.S("["+this.attr_name()+"]");
+var f=d.data(this.attr_name(!0)+"-init"),g=e.S("section, .top-bar-section",d);e.breakpoint()&&(e.rtl?(g.css({right:"0%"}),a(">.name",g).css({right:"100%"})):(g.css({left:"0%"}),a(">.name",g).css({left:"100%"})),e.S("li.moved",g).removeClass("moved"),d.data("index",0),d.toggleClass("expanded").css("height","")),f.scrolltop?d.hasClass("expanded")?d.parent().hasClass("fixed")&&(f.scrolltop?(d.parent().removeClass("fixed"),d.addClass("fixed"),e.S("body").removeClass("f-topbar-fixed"),b.scrollTo(0,0)):d.parent().removeClass("expanded")):d.hasClass("fixed")&&(d.parent().addClass("fixed"),d.removeClass("fixed"),e.S("body").addClass("f-topbar-fixed")):(e.is_sticky(d,d.parent(),f)&&d.parent().addClass("fixed"),d.parent().hasClass("fixed")&&(d.hasClass("expanded")?(d.addClass("fixed"),d.parent().addClass("expanded"),e.S("body").addClass("f-topbar-fixed")):(d.removeClass("fixed"),d.parent().removeClass("expanded"),e.update_sticky_positioning())))},timer:null,events:function(){var c=this,d=this.S;d(this.scope).off(".topbar").on("click.fndtn.topbar","["+this.attr_name()+"] .toggle-topbar",function(a){a.preventDefault(),c.toggle(this)}).on("click.fndtn.topbar",'.top-bar .top-bar-section li a[href^="#"],['+this.attr_name()+'] .top-bar-section li a[href^="#"]',function(){var b=a(this).closest("li");!c.breakpoint()||b.hasClass("back")||b.hasClass("has-dropdown")||c.toggle()}).on("click.fndtn.topbar","["+this.attr_name()+"] li.has-dropdown",function(b){var e=d(this),f=d(b.target),g=e.closest("["+c.attr_name()+"]"),h=g.data(c.attr_name(!0)+"-init");return f.data("revealId")?void c.toggle():void(c.breakpoint()||(!h.is_hover||Modernizr.touch)&&(b.stopImmediatePropagation(),e.hasClass("hover")?(e.removeClass("hover").find("li").removeClass("hover"),e.parents("li.hover").removeClass("hover")):(e.addClass("hover"),a(e).siblings().removeClass("hover"),"A"===f[0].nodeName&&f.parent().hasClass("has-dropdown")&&b.preventDefault())))}).on("click.fndtn.topbar","["+this.attr_name()+"] .has-dropdown>a",function(a){if(c.breakpoint()){a.preventDefault();var b=d(this),e=b.closest("["+c.attr_name()+"]"),f=e.find("section, .top-bar-section"),g=(b.next(".dropdown").outerHeight(),b.closest("li"));e.data("index",e.data("index")+1),g.addClass("moved"),c.rtl?(f.css({right:-(100*e.data("index"))+"%"}),f.find(">.name").css({right:100*e.data("index")+"%"})):(f.css({left:-(100*e.data("index"))+"%"}),f.find(">.name").css({left:100*e.data("index")+"%"})),e.css("height",b.siblings("ul").outerHeight(!0)+e.data("height"))}}),d(b).off(".topbar").on("resize.fndtn.topbar",c.throttle(function(){c.resize.call(c)},50)).trigger("resize").trigger("resize.fndtn.topbar").load(function(){d(this).trigger("resize.fndtn.topbar")}),d("body").off(".topbar").on("click.fndtn.topbar",function(a){var b=d(a.target).closest("li").closest("li.hover");b.length>0||d("["+c.attr_name()+"] li.hover").removeClass("hover")}),d(this.scope).on("click.fndtn.topbar","["+this.attr_name()+"] .has-dropdown .back",function(a){a.preventDefault();var b=d(this),e=b.closest("["+c.attr_name()+"]"),f=e.find("section, .top-bar-section"),g=(e.data(c.attr_name(!0)+"-init"),b.closest("li.moved")),h=g.parent();e.data("index",e.data("index")-1),c.rtl?(f.css({right:-(100*e.data("index"))+"%"}),f.find(">.name").css({right:100*e.data("index")+"%"})):(f.css({left:-(100*e.data("index"))+"%"}),f.find(">.name").css({left:100*e.data("index")+"%"})),0===e.data("index")?e.css("height",""):e.css("height",h.outerHeight(!0)+e.data("height")),setTimeout(function(){g.removeClass("moved")},300)}),d(this.scope).find(".dropdown a").focus(function(){a(this).parents(".has-dropdown").addClass("hover")}).blur(function(){a(this).parents(".has-dropdown").removeClass("hover")})},resize:function(){var a=this;a.S("["+this.attr_name()+"]").each(function(){var b,d=a.S(this),e=d.data(a.attr_name(!0)+"-init"),f=d.parent("."+a.settings.sticky_class);if(!a.breakpoint()){var g=d.hasClass("expanded");d.css("height","").removeClass("expanded").find("li").removeClass("hover"),g&&a.toggle(d)}a.is_sticky(d,f,e)&&(f.hasClass("fixed")?(f.removeClass("fixed"),b=f.offset().top,a.S(c.body).hasClass("f-topbar-fixed")&&(b-=d.data("height")),d.data("stickyoffset",b),f.addClass("fixed")):(b=f.offset().top,d.data("stickyoffset",b)))})},breakpoint:function(){return!matchMedia(Foundation.media_queries.topbar).matches},small:function(){return matchMedia(Foundation.media_queries.small).matches},medium:function(){return matchMedia(Foundation.media_queries.medium).matches},large:function(){return matchMedia(Foundation.media_queries.large).matches},assemble:function(b){var c=this,d=b.data(this.attr_name(!0)+"-init"),e=c.S("section, .top-bar-section",b);e.detach(),c.S(".has-dropdown>a",e).each(function(){var b,e=c.S(this),f=e.siblings(".dropdown"),g=e.attr("href");f.find(".title.back").length||(b=a(1==d.mobile_show_parent_link&&g?''+e.html()+" ":' '),a("h5>a",b).html(1==d.custom_back_text?d.back_text:"« "+e.html()),f.prepend(b))}),e.appendTo(b),this.sticky(),this.assembled(b)},assembled:function(b){b.data(this.attr_name(!0),a.extend({},b.data(this.attr_name(!0)),{assembled:!0}))},height:function(b){var c=0,d=this;return a("> li",b).each(function(){c+=d.S(this).outerHeight(!0)}),c},sticky:function(){var a=this;this.S(b).on("scroll",function(){a.update_sticky_positioning()})},update_sticky_positioning:function(){var a="."+this.settings.sticky_class,c=this.S(b),d=this;if(d.settings.sticky_topbar&&d.is_sticky(this.settings.sticky_topbar,this.settings.sticky_topbar.parent(),this.settings)){var e=this.settings.sticky_topbar.data("stickyoffset");d.S(a).hasClass("expanded")||(c.scrollTop()>e?d.S(a).hasClass("fixed")||(d.S(a).addClass("fixed"),d.S("body").addClass("f-topbar-fixed")):c.scrollTop()<=e&&d.S(a).hasClass("fixed")&&(d.S(a).removeClass("fixed"),d.S("body").removeClass("f-topbar-fixed")))}},off:function(){this.S(this.scope).off(".fndtn.topbar"),this.S(b).off(".fndtn.topbar")},reflow:function(){}}}(jQuery,window,window.document);
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.abide.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.abide.js
new file mode 100644
index 00000000..9eefe326
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.abide.js
@@ -0,0 +1,340 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.abide = {
+ name : 'abide',
+
+ version : '5.5.1',
+
+ settings : {
+ live_validate : true,
+ validate_on_blur : true,
+ focus_on_invalid : true,
+ error_labels : true, // labels with a for="inputId" will recieve an `error` class
+ error_class : 'error',
+ timeout : 1000,
+ patterns : {
+ alpha : /^[a-zA-Z]+$/,
+ alpha_numeric : /^[a-zA-Z0-9]+$/,
+ integer : /^[-+]?\d+$/,
+ number : /^[-+]?\d*(?:[\.\,]\d+)?$/,
+
+ // amex, visa, diners
+ card : /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/,
+ cvv : /^([0-9]){3,4}$/,
+
+ // http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
+ email : /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/,
+
+ url : /^(https?|ftp|file|ssh):\/\/(((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/,
+ // abc.de
+ domain : /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,8}$/,
+
+ datetime : /^([0-2][0-9]{3})\-([0-1][0-9])\-([0-3][0-9])T([0-5][0-9])\:([0-5][0-9])\:([0-5][0-9])(Z|([\-\+]([0-1][0-9])\:00))$/,
+ // YYYY-MM-DD
+ date : /(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))$/,
+ // HH:MM:SS
+ time : /^(0[0-9]|1[0-9]|2[0-3])(:[0-5][0-9]){2}$/,
+ dateISO : /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/,
+ // MM/DD/YYYY
+ month_day_year : /^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.]\d{4}$/,
+ // DD/MM/YYYY
+ day_month_year : /^(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.]\d{4}$/,
+
+ // #FFF or #FFFFFF
+ color : /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/
+ },
+ validators : {
+ equalTo : function (el, required, parent) {
+ var from = document.getElementById(el.getAttribute(this.add_namespace('data-equalto'))).value,
+ to = el.value,
+ valid = (from === to);
+
+ return valid;
+ }
+ }
+ },
+
+ timer : null,
+
+ init : function (scope, method, options) {
+ this.bindings(method, options);
+ },
+
+ events : function (scope) {
+ var self = this,
+ form = self.S(scope).attr('novalidate', 'novalidate'),
+ settings = form.data(this.attr_name(true) + '-init') || {};
+
+ this.invalid_attr = this.add_namespace('data-invalid');
+
+ form
+ .off('.abide')
+ .on('submit.fndtn.abide validate.fndtn.abide', function (e) {
+ var is_ajax = /ajax/i.test(self.S(this).attr(self.attr_name()));
+ return self.validate(self.S(this).find('input, textarea, select').get(), e, is_ajax);
+ })
+ .on('reset', function () {
+ return self.reset($(this));
+ })
+ .find('input, textarea, select')
+ .off('.abide')
+ .on('blur.fndtn.abide change.fndtn.abide', function (e) {
+ if (settings.validate_on_blur === true) {
+ self.validate([this], e);
+ }
+ })
+ .on('keydown.fndtn.abide', function (e) {
+ if (settings.live_validate === true && e.which != 9) {
+ clearTimeout(self.timer);
+ self.timer = setTimeout(function () {
+ self.validate([this], e);
+ }.bind(this), settings.timeout);
+ }
+ });
+ },
+
+ reset : function (form) {
+ form.removeAttr(this.invalid_attr);
+ $(this.invalid_attr, form).removeAttr(this.invalid_attr);
+ $('.' + this.settings.error_class, form).not('small').removeClass(this.settings.error_class);
+ },
+
+ validate : function (els, e, is_ajax) {
+ var validations = this.parse_patterns(els),
+ validation_count = validations.length,
+ form = this.S(els[0]).closest('form'),
+ submit_event = /submit/.test(e.type);
+
+ // Has to count up to make sure the focus gets applied to the top error
+ for (var i = 0; i < validation_count; i++) {
+ if (!validations[i] && (submit_event || is_ajax)) {
+ if (this.settings.focus_on_invalid) {
+ els[i].focus();
+ }
+ form.trigger('invalid').trigger('invalid.fndtn.abide');
+ this.S(els[i]).closest('form').attr(this.invalid_attr, '');
+ return false;
+ }
+ }
+
+ if (submit_event || is_ajax) {
+ form.trigger('valid').trigger('valid.fndtn.abide');
+ }
+
+ form.removeAttr(this.invalid_attr);
+
+ if (is_ajax) {
+ return false;
+ }
+
+ return true;
+ },
+
+ parse_patterns : function (els) {
+ var i = els.length,
+ el_patterns = [];
+
+ while (i--) {
+ el_patterns.push(this.pattern(els[i]));
+ }
+
+ return this.check_validation_and_apply_styles(el_patterns);
+ },
+
+ pattern : function (el) {
+ var type = el.getAttribute('type'),
+ required = typeof el.getAttribute('required') === 'string';
+
+ var pattern = el.getAttribute('pattern') || '';
+
+ if (this.settings.patterns.hasOwnProperty(pattern) && pattern.length > 0) {
+ return [el, this.settings.patterns[pattern], required];
+ } else if (pattern.length > 0) {
+ return [el, new RegExp(pattern), required];
+ }
+
+ if (this.settings.patterns.hasOwnProperty(type)) {
+ return [el, this.settings.patterns[type], required];
+ }
+
+ pattern = /.*/;
+
+ return [el, pattern, required];
+ },
+
+ // TODO: Break this up into smaller methods, getting hard to read.
+ check_validation_and_apply_styles : function (el_patterns) {
+ var i = el_patterns.length,
+ validations = [],
+ form = this.S(el_patterns[0][0]).closest('[data-' + this.attr_name(true) + ']'),
+ settings = form.data(this.attr_name(true) + '-init') || {};
+ while (i--) {
+ var el = el_patterns[i][0],
+ required = el_patterns[i][2],
+ value = el.value.trim(),
+ direct_parent = this.S(el).parent(),
+ validator = el.getAttribute(this.add_namespace('data-abide-validator')),
+ is_radio = el.type === 'radio',
+ is_checkbox = el.type === 'checkbox',
+ label = this.S('label[for="' + el.getAttribute('id') + '"]'),
+ valid_length = (required) ? (el.value.length > 0) : true,
+ el_validations = [];
+
+ var parent, valid;
+
+ // support old way to do equalTo validations
+ if (el.getAttribute(this.add_namespace('data-equalto'))) { validator = 'equalTo' }
+
+ if (!direct_parent.is('label')) {
+ parent = direct_parent;
+ } else {
+ parent = direct_parent.parent();
+ }
+
+ if (validator) {
+ valid = this.settings.validators[validator].apply(this, [el, required, parent]);
+ el_validations.push(valid);
+ }
+
+ if (is_radio && required) {
+ el_validations.push(this.valid_radio(el, required));
+ } else if (is_checkbox && required) {
+ el_validations.push(this.valid_checkbox(el, required));
+ } else {
+
+ if (el_patterns[i][1].test(value) && valid_length ||
+ !required && el.value.length < 1 || $(el).attr('disabled')) {
+ el_validations.push(true);
+ } else {
+ el_validations.push(false);
+ }
+
+ el_validations = [el_validations.every(function (valid) {return valid;})];
+
+ if (el_validations[0]) {
+ this.S(el).removeAttr(this.invalid_attr);
+ el.setAttribute('aria-invalid', 'false');
+ el.removeAttribute('aria-describedby');
+ parent.removeClass(this.settings.error_class);
+ if (label.length > 0 && this.settings.error_labels) {
+ label.removeClass(this.settings.error_class).removeAttr('role');
+ }
+ $(el).triggerHandler('valid');
+ } else {
+ this.S(el).attr(this.invalid_attr, '');
+ el.setAttribute('aria-invalid', 'true');
+
+ // Try to find the error associated with the input
+ var errorElem = parent.find('small.' + this.settings.error_class, 'span.' + this.settings.error_class);
+ var errorID = errorElem.length > 0 ? errorElem[0].id : '';
+ if (errorID.length > 0) {
+ el.setAttribute('aria-describedby', errorID);
+ }
+
+ // el.setAttribute('aria-describedby', $(el).find('.error')[0].id);
+ parent.addClass(this.settings.error_class);
+ if (label.length > 0 && this.settings.error_labels) {
+ label.addClass(this.settings.error_class).attr('role', 'alert');
+ }
+ $(el).triggerHandler('invalid');
+ }
+ }
+ validations.push(el_validations[0]);
+ }
+ validations = [validations.every(function (valid) {return valid;})];
+ return validations;
+ },
+
+ valid_checkbox : function (el, required) {
+ var el = this.S(el),
+ valid = (el.is(':checked') || !required || el.get(0).getAttribute('disabled'));
+
+ if (valid) {
+ el.removeAttr(this.invalid_attr).parent().removeClass(this.settings.error_class);
+ } else {
+ el.attr(this.invalid_attr, '').parent().addClass(this.settings.error_class);
+ }
+
+ return valid;
+ },
+
+ valid_radio : function (el, required) {
+ var name = el.getAttribute('name'),
+ group = this.S(el).closest('[data-' + this.attr_name(true) + ']').find("[name='" + name + "']"),
+ count = group.length,
+ valid = false,
+ disabled = false;
+
+ // Has to count up to make sure the focus gets applied to the top error
+ for (var i=0; i < count; i++) {
+ if( group[i].getAttribute('disabled') ){
+ disabled=true;
+ valid=true;
+ } else {
+ if (group[i].checked){
+ valid = true;
+ } else {
+ if( disabled ){
+ valid = false;
+ }
+ }
+ }
+ }
+
+ // Has to count up to make sure the focus gets applied to the top error
+ for (var i = 0; i < count; i++) {
+ if (valid) {
+ this.S(group[i]).removeAttr(this.invalid_attr).parent().removeClass(this.settings.error_class);
+ } else {
+ this.S(group[i]).attr(this.invalid_attr, '').parent().addClass(this.settings.error_class);
+ }
+ }
+
+ return valid;
+ },
+
+ valid_equal : function (el, required, parent) {
+ var from = document.getElementById(el.getAttribute(this.add_namespace('data-equalto'))).value,
+ to = el.value,
+ valid = (from === to);
+
+ if (valid) {
+ this.S(el).removeAttr(this.invalid_attr);
+ parent.removeClass(this.settings.error_class);
+ if (label.length > 0 && settings.error_labels) {
+ label.removeClass(this.settings.error_class);
+ }
+ } else {
+ this.S(el).attr(this.invalid_attr, '');
+ parent.addClass(this.settings.error_class);
+ if (label.length > 0 && settings.error_labels) {
+ label.addClass(this.settings.error_class);
+ }
+ }
+
+ return valid;
+ },
+
+ valid_oneof : function (el, required, parent, doNotValidateOthers) {
+ var el = this.S(el),
+ others = this.S('[' + this.add_namespace('data-oneof') + ']'),
+ valid = others.filter(':checked').length > 0;
+
+ if (valid) {
+ el.removeAttr(this.invalid_attr).parent().removeClass(this.settings.error_class);
+ } else {
+ el.attr(this.invalid_attr, '').parent().addClass(this.settings.error_class);
+ }
+
+ if (!doNotValidateOthers) {
+ var _this = this;
+ others.each(function () {
+ _this.valid_oneof.call(_this, this, null, null, true);
+ });
+ }
+
+ return valid;
+ }
+ };
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.accordion.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.accordion.js
new file mode 100644
index 00000000..483d8194
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.accordion.js
@@ -0,0 +1,67 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.accordion = {
+ name : 'accordion',
+
+ version : '5.5.1',
+
+ settings : {
+ content_class : 'content',
+ active_class : 'active',
+ multi_expand : false,
+ toggleable : true,
+ callback : function () {}
+ },
+
+ init : function (scope, method, options) {
+ this.bindings(method, options);
+ },
+
+ events : function () {
+ var self = this;
+ var S = this.S;
+ S(this.scope)
+ .off('.fndtn.accordion')
+ .on('click.fndtn.accordion', '[' + this.attr_name() + '] > .accordion-navigation > a', function (e) {
+ var accordion = S(this).closest('[' + self.attr_name() + ']'),
+ groupSelector = self.attr_name() + '=' + accordion.attr(self.attr_name()),
+ settings = accordion.data(self.attr_name(true) + '-init') || self.settings,
+ target = S('#' + this.href.split('#')[1]),
+ aunts = $('> .accordion-navigation', accordion),
+ siblings = aunts.children('.' + settings.content_class),
+ active_content = siblings.filter('.' + settings.active_class);
+
+ e.preventDefault();
+
+ if (accordion.attr(self.attr_name())) {
+ siblings = siblings.add('[' + groupSelector + '] dd > ' + '.' + settings.content_class);
+ aunts = aunts.add('[' + groupSelector + '] .accordion-navigation');
+ }
+
+ if (settings.toggleable && target.is(active_content)) {
+ target.parent('.accordion-navigation').toggleClass(settings.active_class, false);
+ target.toggleClass(settings.active_class, false);
+ settings.callback(target);
+ target.triggerHandler('toggled', [accordion]);
+ accordion.triggerHandler('toggled', [target]);
+ return;
+ }
+
+ if (!settings.multi_expand) {
+ siblings.removeClass(settings.active_class);
+ aunts.removeClass(settings.active_class);
+ }
+
+ target.addClass(settings.active_class).parent().addClass(settings.active_class);
+ settings.callback(target);
+ target.triggerHandler('toggled', [accordion]);
+ accordion.triggerHandler('toggled', [target]);
+ });
+ },
+
+ off : function () {},
+
+ reflow : function () {}
+ };
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.alert.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.alert.js
new file mode 100644
index 00000000..763a22f6
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.alert.js
@@ -0,0 +1,43 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.alert = {
+ name : 'alert',
+
+ version : '5.5.1',
+
+ settings : {
+ callback : function () {}
+ },
+
+ init : function (scope, method, options) {
+ this.bindings(method, options);
+ },
+
+ events : function () {
+ var self = this,
+ S = this.S;
+
+ $(this.scope).off('.alert').on('click.fndtn.alert', '[' + this.attr_name() + '] .close', function (e) {
+ var alertBox = S(this).closest('[' + self.attr_name() + ']'),
+ settings = alertBox.data(self.attr_name(true) + '-init') || self.settings;
+
+ e.preventDefault();
+ if (Modernizr.csstransitions) {
+ alertBox.addClass('alert-close');
+ alertBox.on('transitionend webkitTransitionEnd oTransitionEnd', function (e) {
+ S(this).trigger('close').trigger('close.fndtn.alert').remove();
+ settings.callback();
+ });
+ } else {
+ alertBox.fadeOut(300, function () {
+ S(this).trigger('close').trigger('close.fndtn.alert').remove();
+ settings.callback();
+ });
+ }
+ });
+ },
+
+ reflow : function () {}
+ };
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.clearing.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.clearing.js
new file mode 100644
index 00000000..e7bd4582
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.clearing.js
@@ -0,0 +1,556 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.clearing = {
+ name : 'clearing',
+
+ version : '5.5.1',
+
+ settings : {
+ templates : {
+ viewing : '× ' +
+ '
' +
+ '
' +
+ '
'
+ },
+
+ // comma delimited list of selectors that, on click, will close clearing,
+ // add 'div.clearing-blackout, div.visible-img' to close on background click
+ close_selectors : '.clearing-close, div.clearing-blackout',
+
+ // Default to the entire li element.
+ open_selectors : '',
+
+ // Image will be skipped in carousel.
+ skip_selector : '',
+
+ touch_label : '',
+
+ // event initializers and locks
+ init : false,
+ locked : false
+ },
+
+ init : function (scope, method, options) {
+ var self = this;
+ Foundation.inherit(this, 'throttle image_loaded');
+
+ this.bindings(method, options);
+
+ if (self.S(this.scope).is('[' + this.attr_name() + ']')) {
+ this.assemble(self.S('li', this.scope));
+ } else {
+ self.S('[' + this.attr_name() + ']', this.scope).each(function () {
+ self.assemble(self.S('li', this));
+ });
+ }
+ },
+
+ events : function (scope) {
+ var self = this,
+ S = self.S,
+ $scroll_container = $('.scroll-container');
+
+ if ($scroll_container.length > 0) {
+ this.scope = $scroll_container;
+ }
+
+ S(this.scope)
+ .off('.clearing')
+ .on('click.fndtn.clearing', 'ul[' + this.attr_name() + '] li ' + this.settings.open_selectors,
+ function (e, current, target) {
+ var current = current || S(this),
+ target = target || current,
+ next = current.next('li'),
+ settings = current.closest('[' + self.attr_name() + ']').data(self.attr_name(true) + '-init'),
+ image = S(e.target);
+
+ e.preventDefault();
+
+ if (!settings) {
+ self.init();
+ settings = current.closest('[' + self.attr_name() + ']').data(self.attr_name(true) + '-init');
+ }
+
+ // if clearing is open and the current image is
+ // clicked, go to the next image in sequence
+ if (target.hasClass('visible') &&
+ current[0] === target[0] &&
+ next.length > 0 && self.is_open(current)) {
+ target = next;
+ image = S('img', target);
+ }
+
+ // set current and target to the clicked li if not otherwise defined.
+ self.open(image, current, target);
+ self.update_paddles(target);
+ })
+
+ .on('click.fndtn.clearing', '.clearing-main-next',
+ function (e) { self.nav(e, 'next') })
+ .on('click.fndtn.clearing', '.clearing-main-prev',
+ function (e) { self.nav(e, 'prev') })
+ .on('click.fndtn.clearing', this.settings.close_selectors,
+ function (e) { Foundation.libs.clearing.close(e, this) });
+
+ $(document).on('keydown.fndtn.clearing',
+ function (e) { self.keydown(e) });
+
+ S(window).off('.clearing').on('resize.fndtn.clearing',
+ function () { self.resize() });
+
+ this.swipe_events(scope);
+ },
+
+ swipe_events : function (scope) {
+ var self = this,
+ S = self.S;
+
+ S(this.scope)
+ .on('touchstart.fndtn.clearing', '.visible-img', function (e) {
+ if (!e.touches) { e = e.originalEvent; }
+ var data = {
+ start_page_x : e.touches[0].pageX,
+ start_page_y : e.touches[0].pageY,
+ start_time : (new Date()).getTime(),
+ delta_x : 0,
+ is_scrolling : undefined
+ };
+
+ S(this).data('swipe-transition', data);
+ e.stopPropagation();
+ })
+ .on('touchmove.fndtn.clearing', '.visible-img', function (e) {
+ if (!e.touches) {
+ e = e.originalEvent;
+ }
+ // Ignore pinch/zoom events
+ if (e.touches.length > 1 || e.scale && e.scale !== 1) {
+ return;
+ }
+
+ var data = S(this).data('swipe-transition');
+
+ if (typeof data === 'undefined') {
+ data = {};
+ }
+
+ data.delta_x = e.touches[0].pageX - data.start_page_x;
+
+ if (Foundation.rtl) {
+ data.delta_x = -data.delta_x;
+ }
+
+ if (typeof data.is_scrolling === 'undefined') {
+ data.is_scrolling = !!( data.is_scrolling || Math.abs(data.delta_x) < Math.abs(e.touches[0].pageY - data.start_page_y) );
+ }
+
+ if (!data.is_scrolling && !data.active) {
+ e.preventDefault();
+ var direction = (data.delta_x < 0) ? 'next' : 'prev';
+ data.active = true;
+ self.nav(e, direction);
+ }
+ })
+ .on('touchend.fndtn.clearing', '.visible-img', function (e) {
+ S(this).data('swipe-transition', {});
+ e.stopPropagation();
+ });
+ },
+
+ assemble : function ($li) {
+ var $el = $li.parent();
+
+ if ($el.parent().hasClass('carousel')) {
+ return;
+ }
+
+ $el.after('
');
+
+ var grid = $el.detach(),
+ grid_outerHTML = '';
+
+ if (grid[0] == null) {
+ return;
+ } else {
+ grid_outerHTML = grid[0].outerHTML;
+ }
+
+ var holder = this.S('#foundationClearingHolder'),
+ settings = $el.data(this.attr_name(true) + '-init'),
+ data = {
+ grid : '' + grid_outerHTML + '
',
+ viewing : settings.templates.viewing
+ },
+ wrapper = '' + data.viewing +
+ data.grid + '
',
+ touch_label = this.settings.touch_label;
+
+ if (Modernizr.touch) {
+ wrapper = $(wrapper).find('.clearing-touch-label').html(touch_label).end();
+ }
+
+ holder.after(wrapper).remove();
+ },
+
+ open : function ($image, current, target) {
+ var self = this,
+ body = $(document.body),
+ root = target.closest('.clearing-assembled'),
+ container = self.S('div', root).first(),
+ visible_image = self.S('.visible-img', container),
+ image = self.S('img', visible_image).not($image),
+ label = self.S('.clearing-touch-label', container),
+ error = false;
+
+ // Event to disable scrolling on touch devices when Clearing is activated
+ $('body').on('touchmove', function (e) {
+ e.preventDefault();
+ });
+
+ image.error(function () {
+ error = true;
+ });
+
+ function startLoad() {
+ setTimeout(function () {
+ this.image_loaded(image, function () {
+ if (image.outerWidth() === 1 && !error) {
+ startLoad.call(this);
+ } else {
+ cb.call(this, image);
+ }
+ }.bind(this));
+ }.bind(this), 100);
+ }
+
+ function cb (image) {
+ var $image = $(image);
+ $image.css('visibility', 'visible');
+ // toggle the gallery
+ body.css('overflow', 'hidden');
+ root.addClass('clearing-blackout');
+ container.addClass('clearing-container');
+ visible_image.show();
+ this.fix_height(target)
+ .caption(self.S('.clearing-caption', visible_image), self.S('img', target))
+ .center_and_label(image, label)
+ .shift(current, target, function () {
+ target.closest('li').siblings().removeClass('visible');
+ target.closest('li').addClass('visible');
+ });
+ visible_image.trigger('opened.fndtn.clearing')
+ }
+
+ if (!this.locked()) {
+ visible_image.trigger('open.fndtn.clearing');
+ // set the image to the selected thumbnail
+ image
+ .attr('src', this.load($image))
+ .css('visibility', 'hidden');
+
+ startLoad.call(this);
+ }
+ },
+
+ close : function (e, el) {
+ e.preventDefault();
+
+ var root = (function (target) {
+ if (/blackout/.test(target.selector)) {
+ return target;
+ } else {
+ return target.closest('.clearing-blackout');
+ }
+ }($(el))),
+ body = $(document.body), container, visible_image;
+
+ if (el === e.target && root) {
+ body.css('overflow', '');
+ container = $('div', root).first();
+ visible_image = $('.visible-img', container);
+ visible_image.trigger('close.fndtn.clearing');
+ this.settings.prev_index = 0;
+ $('ul[' + this.attr_name() + ']', root)
+ .attr('style', '').closest('.clearing-blackout')
+ .removeClass('clearing-blackout');
+ container.removeClass('clearing-container');
+ visible_image.hide();
+ visible_image.trigger('closed.fndtn.clearing');
+ }
+
+ // Event to re-enable scrolling on touch devices
+ $('body').off('touchmove');
+
+ return false;
+ },
+
+ is_open : function (current) {
+ return current.parent().prop('style').length > 0;
+ },
+
+ keydown : function (e) {
+ var clearing = $('.clearing-blackout ul[' + this.attr_name() + ']'),
+ NEXT_KEY = this.rtl ? 37 : 39,
+ PREV_KEY = this.rtl ? 39 : 37,
+ ESC_KEY = 27;
+
+ if (e.which === NEXT_KEY) {
+ this.go(clearing, 'next');
+ }
+ if (e.which === PREV_KEY) {
+ this.go(clearing, 'prev');
+ }
+ if (e.which === ESC_KEY) {
+ this.S('a.clearing-close').trigger('click').trigger('click.fndtn.clearing');
+ }
+ },
+
+ nav : function (e, direction) {
+ var clearing = $('ul[' + this.attr_name() + ']', '.clearing-blackout');
+
+ e.preventDefault();
+ this.go(clearing, direction);
+ },
+
+ resize : function () {
+ var image = $('img', '.clearing-blackout .visible-img'),
+ label = $('.clearing-touch-label', '.clearing-blackout');
+
+ if (image.length) {
+ this.center_and_label(image, label);
+ image.trigger('resized.fndtn.clearing')
+ }
+ },
+
+ // visual adjustments
+ fix_height : function (target) {
+ var lis = target.parent().children(),
+ self = this;
+
+ lis.each(function () {
+ var li = self.S(this),
+ image = li.find('img');
+
+ if (li.height() > image.outerHeight()) {
+ li.addClass('fix-height');
+ }
+ })
+ .closest('ul')
+ .width(lis.length * 100 + '%');
+
+ return this;
+ },
+
+ update_paddles : function (target) {
+ target = target.closest('li');
+ var visible_image = target
+ .closest('.carousel')
+ .siblings('.visible-img');
+
+ if (target.next().length > 0) {
+ this.S('.clearing-main-next', visible_image).removeClass('disabled');
+ } else {
+ this.S('.clearing-main-next', visible_image).addClass('disabled');
+ }
+
+ if (target.prev().length > 0) {
+ this.S('.clearing-main-prev', visible_image).removeClass('disabled');
+ } else {
+ this.S('.clearing-main-prev', visible_image).addClass('disabled');
+ }
+ },
+
+ center_and_label : function (target, label) {
+ if (!this.rtl && label.length > 0) {
+ label.css({
+ marginLeft : -(label.outerWidth() / 2),
+ marginTop : -(target.outerHeight() / 2)-label.outerHeight()-10
+ });
+ } else {
+ label.css({
+ marginRight : -(label.outerWidth() / 2),
+ marginTop : -(target.outerHeight() / 2)-label.outerHeight()-10,
+ left: 'auto',
+ right: '50%'
+ });
+ }
+ return this;
+ },
+
+ // image loading and preloading
+
+ load : function ($image) {
+ var href;
+
+ if ($image[0].nodeName === 'A') {
+ href = $image.attr('href');
+ } else {
+ href = $image.closest('a').attr('href');
+ }
+
+ this.preload($image);
+
+ if (href) {
+ return href;
+ }
+ return $image.attr('src');
+ },
+
+ preload : function ($image) {
+ this
+ .img($image.closest('li').next())
+ .img($image.closest('li').prev());
+ },
+
+ img : function (img) {
+ if (img.length) {
+ var new_img = new Image(),
+ new_a = this.S('a', img);
+
+ if (new_a.length) {
+ new_img.src = new_a.attr('href');
+ } else {
+ new_img.src = this.S('img', img).attr('src');
+ }
+ }
+ return this;
+ },
+
+ // image caption
+
+ caption : function (container, $image) {
+ var caption = $image.attr('data-caption');
+
+ if (caption) {
+ container
+ .html(caption)
+ .show();
+ } else {
+ container
+ .text('')
+ .hide();
+ }
+ return this;
+ },
+
+ // directional methods
+
+ go : function ($ul, direction) {
+ var current = this.S('.visible', $ul),
+ target = current[direction]();
+
+ // Check for skip selector.
+ if (this.settings.skip_selector && target.find(this.settings.skip_selector).length != 0) {
+ target = target[direction]();
+ }
+
+ if (target.length) {
+ this.S('img', target)
+ .trigger('click', [current, target]).trigger('click.fndtn.clearing', [current, target])
+ .trigger('change.fndtn.clearing');
+ }
+ },
+
+ shift : function (current, target, callback) {
+ var clearing = target.parent(),
+ old_index = this.settings.prev_index || target.index(),
+ direction = this.direction(clearing, current, target),
+ dir = this.rtl ? 'right' : 'left',
+ left = parseInt(clearing.css('left'), 10),
+ width = target.outerWidth(),
+ skip_shift;
+
+ var dir_obj = {};
+
+ // we use jQuery animate instead of CSS transitions because we
+ // need a callback to unlock the next animation
+ // needs support for RTL **
+ if (target.index() !== old_index && !/skip/.test(direction)) {
+ if (/left/.test(direction)) {
+ this.lock();
+ dir_obj[dir] = left + width;
+ clearing.animate(dir_obj, 300, this.unlock());
+ } else if (/right/.test(direction)) {
+ this.lock();
+ dir_obj[dir] = left - width;
+ clearing.animate(dir_obj, 300, this.unlock());
+ }
+ } else if (/skip/.test(direction)) {
+ // the target image is not adjacent to the current image, so
+ // do we scroll right or not
+ skip_shift = target.index() - this.settings.up_count;
+ this.lock();
+
+ if (skip_shift > 0) {
+ dir_obj[dir] = -(skip_shift * width);
+ clearing.animate(dir_obj, 300, this.unlock());
+ } else {
+ dir_obj[dir] = 0;
+ clearing.animate(dir_obj, 300, this.unlock());
+ }
+ }
+
+ callback();
+ },
+
+ direction : function ($el, current, target) {
+ var lis = this.S('li', $el),
+ li_width = lis.outerWidth() + (lis.outerWidth() / 4),
+ up_count = Math.floor(this.S('.clearing-container').outerWidth() / li_width) - 1,
+ target_index = lis.index(target),
+ response;
+
+ this.settings.up_count = up_count;
+
+ if (this.adjacent(this.settings.prev_index, target_index)) {
+ if ((target_index > up_count) && target_index > this.settings.prev_index) {
+ response = 'right';
+ } else if ((target_index > up_count - 1) && target_index <= this.settings.prev_index) {
+ response = 'left';
+ } else {
+ response = false;
+ }
+ } else {
+ response = 'skip';
+ }
+
+ this.settings.prev_index = target_index;
+
+ return response;
+ },
+
+ adjacent : function (current_index, target_index) {
+ for (var i = target_index + 1; i >= target_index - 1; i--) {
+ if (i === current_index) {
+ return true;
+ }
+ }
+ return false;
+ },
+
+ // lock management
+
+ lock : function () {
+ this.settings.locked = true;
+ },
+
+ unlock : function () {
+ this.settings.locked = false;
+ },
+
+ locked : function () {
+ return this.settings.locked;
+ },
+
+ off : function () {
+ this.S(this.scope).off('.fndtn.clearing');
+ this.S(window).off('.fndtn.clearing');
+ },
+
+ reflow : function () {
+ this.init();
+ }
+ };
+
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.dropdown.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.dropdown.js
new file mode 100644
index 00000000..4fa8b313
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.dropdown.js
@@ -0,0 +1,448 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.dropdown = {
+ name : 'dropdown',
+
+ version : '5.5.1',
+
+ settings : {
+ active_class : 'open',
+ disabled_class : 'disabled',
+ mega_class : 'mega',
+ align : 'bottom',
+ is_hover : false,
+ hover_timeout : 150,
+ opened : function () {},
+ closed : function () {}
+ },
+
+ init : function (scope, method, options) {
+ Foundation.inherit(this, 'throttle');
+
+ $.extend(true, this.settings, method, options);
+ this.bindings(method, options);
+ },
+
+ events : function (scope) {
+ var self = this,
+ S = self.S;
+
+ S(this.scope)
+ .off('.dropdown')
+ .on('click.fndtn.dropdown', '[' + this.attr_name() + ']', function (e) {
+ var settings = S(this).data(self.attr_name(true) + '-init') || self.settings;
+ if (!settings.is_hover || Modernizr.touch) {
+ e.preventDefault();
+ if (S(this).parent('[data-reveal-id]')) {
+ e.stopPropagation();
+ }
+ self.toggle($(this));
+ }
+ })
+ .on('mouseenter.fndtn.dropdown', '[' + this.attr_name() + '], [' + this.attr_name() + '-content]', function (e) {
+ var $this = S(this),
+ dropdown,
+ target;
+
+ clearTimeout(self.timeout);
+
+ if ($this.data(self.data_attr())) {
+ dropdown = S('#' + $this.data(self.data_attr()));
+ target = $this;
+ } else {
+ dropdown = $this;
+ target = S('[' + self.attr_name() + '="' + dropdown.attr('id') + '"]');
+ }
+
+ var settings = target.data(self.attr_name(true) + '-init') || self.settings;
+
+ if (S(e.currentTarget).data(self.data_attr()) && settings.is_hover) {
+ self.closeall.call(self);
+ }
+
+ if (settings.is_hover) {
+ self.open.apply(self, [dropdown, target]);
+ }
+ })
+ .on('mouseleave.fndtn.dropdown', '[' + this.attr_name() + '], [' + this.attr_name() + '-content]', function (e) {
+ var $this = S(this);
+ var settings;
+
+ if ($this.data(self.data_attr())) {
+ settings = $this.data(self.data_attr(true) + '-init') || self.settings;
+ } else {
+ var target = S('[' + self.attr_name() + '="' + S(this).attr('id') + '"]'),
+ settings = target.data(self.attr_name(true) + '-init') || self.settings;
+ }
+
+ self.timeout = setTimeout(function () {
+ if ($this.data(self.data_attr())) {
+ if (settings.is_hover) {
+ self.close.call(self, S('#' + $this.data(self.data_attr())));
+ }
+ } else {
+ if (settings.is_hover) {
+ self.close.call(self, $this);
+ }
+ }
+ }.bind(this), settings.hover_timeout);
+ })
+ .on('click.fndtn.dropdown', function (e) {
+ var parent = S(e.target).closest('[' + self.attr_name() + '-content]');
+ var links = parent.find('a');
+
+ if (links.length > 0 && parent.attr('aria-autoclose') !== 'false') {
+ self.close.call(self, S('[' + self.attr_name() + '-content]'));
+ }
+
+ if (e.target !== document && !$.contains(document.documentElement, e.target)) {
+ return;
+ }
+
+ if (S(e.target).closest('[' + self.attr_name() + ']').length > 0) {
+ return;
+ }
+
+ if (!(S(e.target).data('revealId')) &&
+ (parent.length > 0 && (S(e.target).is('[' + self.attr_name() + '-content]') ||
+ $.contains(parent.first()[0], e.target)))) {
+ e.stopPropagation();
+ return;
+ }
+
+ self.close.call(self, S('[' + self.attr_name() + '-content]'));
+ })
+ .on('opened.fndtn.dropdown', '[' + self.attr_name() + '-content]', function () {
+ self.settings.opened.call(this);
+ })
+ .on('closed.fndtn.dropdown', '[' + self.attr_name() + '-content]', function () {
+ self.settings.closed.call(this);
+ });
+
+ S(window)
+ .off('.dropdown')
+ .on('resize.fndtn.dropdown', self.throttle(function () {
+ self.resize.call(self);
+ }, 50));
+
+ this.resize();
+ },
+
+ close : function (dropdown) {
+ var self = this;
+ dropdown.each(function () {
+ var original_target = $('[' + self.attr_name() + '=' + dropdown[0].id + ']') || $('aria-controls=' + dropdown[0].id + ']');
+ original_target.attr('aria-expanded', 'false');
+ if (self.S(this).hasClass(self.settings.active_class)) {
+ self.S(this)
+ .css(Foundation.rtl ? 'right' : 'left', '-99999px')
+ .attr('aria-hidden', 'true')
+ .removeClass(self.settings.active_class)
+ .prev('[' + self.attr_name() + ']')
+ .removeClass(self.settings.active_class)
+ .removeData('target');
+
+ self.S(this).trigger('closed').trigger('closed.fndtn.dropdown', [dropdown]);
+ }
+ });
+ dropdown.removeClass('f-open-' + this.attr_name(true));
+ },
+
+ closeall : function () {
+ var self = this;
+ $.each(self.S('.f-open-' + this.attr_name(true)), function () {
+ self.close.call(self, self.S(this));
+ });
+ },
+
+ open : function (dropdown, target) {
+ this
+ .css(dropdown
+ .addClass(this.settings.active_class), target);
+ dropdown.prev('[' + this.attr_name() + ']').addClass(this.settings.active_class);
+ dropdown.data('target', target.get(0)).trigger('opened').trigger('opened.fndtn.dropdown', [dropdown, target]);
+ dropdown.attr('aria-hidden', 'false');
+ target.attr('aria-expanded', 'true');
+ dropdown.focus();
+ dropdown.addClass('f-open-' + this.attr_name(true));
+ },
+
+ data_attr : function () {
+ if (this.namespace.length > 0) {
+ return this.namespace + '-' + this.name;
+ }
+
+ return this.name;
+ },
+
+ toggle : function (target) {
+ if (target.hasClass(this.settings.disabled_class)) {
+ return;
+ }
+ var dropdown = this.S('#' + target.data(this.data_attr()));
+ if (dropdown.length === 0) {
+ // No dropdown found, not continuing
+ return;
+ }
+
+ this.close.call(this, this.S('[' + this.attr_name() + '-content]').not(dropdown));
+
+ if (dropdown.hasClass(this.settings.active_class)) {
+ this.close.call(this, dropdown);
+ if (dropdown.data('target') !== target.get(0)) {
+ this.open.call(this, dropdown, target);
+ }
+ } else {
+ this.open.call(this, dropdown, target);
+ }
+ },
+
+ resize : function () {
+ var dropdown = this.S('[' + this.attr_name() + '-content].open');
+ var target = $(dropdown.data("target"));
+
+ if (dropdown.length && target.length) {
+ this.css(dropdown, target);
+ }
+ },
+
+ css : function (dropdown, target) {
+ var left_offset = Math.max((target.width() - dropdown.width()) / 2, 8),
+ settings = target.data(this.attr_name(true) + '-init') || this.settings;
+
+ this.clear_idx();
+
+ if (this.small()) {
+ var p = this.dirs.bottom.call(dropdown, target, settings);
+
+ dropdown.attr('style', '').removeClass('drop-left drop-right drop-top').css({
+ position : 'absolute',
+ width : '95%',
+ 'max-width' : 'none',
+ top : p.top
+ });
+
+ dropdown.css(Foundation.rtl ? 'right' : 'left', left_offset);
+ } else {
+
+ this.style(dropdown, target, settings);
+ }
+
+ return dropdown;
+ },
+
+ style : function (dropdown, target, settings) {
+ var css = $.extend({position : 'absolute'},
+ this.dirs[settings.align].call(dropdown, target, settings));
+
+ dropdown.attr('style', '').css(css);
+ },
+
+ // return CSS property object
+ // `this` is the dropdown
+ dirs : {
+ // Calculate target offset
+ _base : function (t) {
+ var o_p = this.offsetParent(),
+ o = o_p.offset(),
+ p = t.offset();
+
+ p.top -= o.top;
+ p.left -= o.left;
+
+ //set some flags on the p object to pass along
+ p.missRight = false;
+ p.missTop = false;
+ p.missLeft = false;
+ p.leftRightFlag = false;
+
+ //lets see if the panel will be off the screen
+ //get the actual width of the page and store it
+ var actualBodyWidth;
+ if (document.getElementsByClassName('row')[0]) {
+ actualBodyWidth = document.getElementsByClassName('row')[0].clientWidth;
+ } else {
+ actualBodyWidth = window.outerWidth;
+ }
+
+ var actualMarginWidth = (window.outerWidth - actualBodyWidth) / 2;
+ var actualBoundary = actualBodyWidth;
+
+ if (!this.hasClass('mega')) {
+ //miss top
+ if (t.offset().top <= this.outerHeight()) {
+ p.missTop = true;
+ actualBoundary = window.outerWidth - actualMarginWidth;
+ p.leftRightFlag = true;
+ }
+
+ //miss right
+ if (t.offset().left + this.outerWidth() > t.offset().left + actualMarginWidth && t.offset().left - actualMarginWidth > this.outerWidth()) {
+ p.missRight = true;
+ p.missLeft = false;
+ }
+
+ //miss left
+ if (t.offset().left - this.outerWidth() <= 0) {
+ p.missLeft = true;
+ p.missRight = false;
+ }
+ }
+
+ return p;
+ },
+
+ top : function (t, s) {
+ var self = Foundation.libs.dropdown,
+ p = self.dirs._base.call(this, t);
+
+ this.addClass('drop-top');
+
+ if (p.missTop == true) {
+ p.top = p.top + t.outerHeight() + this.outerHeight();
+ this.removeClass('drop-top');
+ }
+
+ if (p.missRight == true) {
+ p.left = p.left - this.outerWidth() + t.outerWidth();
+ }
+
+ if (t.outerWidth() < this.outerWidth() || self.small() || this.hasClass(s.mega_menu)) {
+ self.adjust_pip(this, t, s, p);
+ }
+
+ if (Foundation.rtl) {
+ return {left : p.left - this.outerWidth() + t.outerWidth(),
+ top : p.top - this.outerHeight()};
+ }
+
+ return {left : p.left, top : p.top - this.outerHeight()};
+ },
+
+ bottom : function (t, s) {
+ var self = Foundation.libs.dropdown,
+ p = self.dirs._base.call(this, t);
+
+ if (p.missRight == true) {
+ p.left = p.left - this.outerWidth() + t.outerWidth();
+ }
+
+ if (t.outerWidth() < this.outerWidth() || self.small() || this.hasClass(s.mega_menu)) {
+ self.adjust_pip(this, t, s, p);
+ }
+
+ if (self.rtl) {
+ return {left : p.left - this.outerWidth() + t.outerWidth(), top : p.top + t.outerHeight()};
+ }
+
+ return {left : p.left, top : p.top + t.outerHeight()};
+ },
+
+ left : function (t, s) {
+ var p = Foundation.libs.dropdown.dirs._base.call(this, t);
+
+ this.addClass('drop-left');
+
+ if (p.missLeft == true) {
+ p.left = p.left + this.outerWidth();
+ p.top = p.top + t.outerHeight();
+ this.removeClass('drop-left');
+ }
+
+ return {left : p.left - this.outerWidth(), top : p.top};
+ },
+
+ right : function (t, s) {
+ var p = Foundation.libs.dropdown.dirs._base.call(this, t);
+
+ this.addClass('drop-right');
+
+ if (p.missRight == true) {
+ p.left = p.left - this.outerWidth();
+ p.top = p.top + t.outerHeight();
+ this.removeClass('drop-right');
+ } else {
+ p.triggeredRight = true;
+ }
+
+ var self = Foundation.libs.dropdown;
+
+ if (t.outerWidth() < this.outerWidth() || self.small() || this.hasClass(s.mega_menu)) {
+ self.adjust_pip(this, t, s, p);
+ }
+
+ return {left : p.left + t.outerWidth(), top : p.top};
+ }
+ },
+
+ // Insert rule to style psuedo elements
+ adjust_pip : function (dropdown, target, settings, position) {
+ var sheet = Foundation.stylesheet,
+ pip_offset_base = 8;
+
+ if (dropdown.hasClass(settings.mega_class)) {
+ pip_offset_base = position.left + (target.outerWidth() / 2) - 8;
+ } else if (this.small()) {
+ pip_offset_base += position.left - 8;
+ }
+
+ this.rule_idx = sheet.cssRules.length;
+
+ //default
+ var sel_before = '.f-dropdown.open:before',
+ sel_after = '.f-dropdown.open:after',
+ css_before = 'left: ' + pip_offset_base + 'px;',
+ css_after = 'left: ' + (pip_offset_base - 1) + 'px;';
+
+ if (position.missRight == true) {
+ pip_offset_base = dropdown.outerWidth() - 23;
+ sel_before = '.f-dropdown.open:before',
+ sel_after = '.f-dropdown.open:after',
+ css_before = 'left: ' + pip_offset_base + 'px;',
+ css_after = 'left: ' + (pip_offset_base - 1) + 'px;';
+ }
+
+ //just a case where right is fired, but its not missing right
+ if (position.triggeredRight == true) {
+ sel_before = '.f-dropdown.open:before',
+ sel_after = '.f-dropdown.open:after',
+ css_before = 'left:-12px;',
+ css_after = 'left:-14px;';
+ }
+
+ if (sheet.insertRule) {
+ sheet.insertRule([sel_before, '{', css_before, '}'].join(' '), this.rule_idx);
+ sheet.insertRule([sel_after, '{', css_after, '}'].join(' '), this.rule_idx + 1);
+ } else {
+ sheet.addRule(sel_before, css_before, this.rule_idx);
+ sheet.addRule(sel_after, css_after, this.rule_idx + 1);
+ }
+ },
+
+ // Remove old dropdown rule index
+ clear_idx : function () {
+ var sheet = Foundation.stylesheet;
+
+ if (typeof this.rule_idx !== 'undefined') {
+ sheet.deleteRule(this.rule_idx);
+ sheet.deleteRule(this.rule_idx);
+ delete this.rule_idx;
+ }
+ },
+
+ small : function () {
+ return matchMedia(Foundation.media_queries.small).matches &&
+ !matchMedia(Foundation.media_queries.medium).matches;
+ },
+
+ off : function () {
+ this.S(this.scope).off('.fndtn.dropdown');
+ this.S('html, body').off('.fndtn.dropdown');
+ this.S(window).off('.fndtn.dropdown');
+ this.S('[data-dropdown-content]').off('.fndtn.dropdown');
+ },
+
+ reflow : function () {}
+ };
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.equalizer.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.equalizer.js
new file mode 100644
index 00000000..dd912a75
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.equalizer.js
@@ -0,0 +1,77 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.equalizer = {
+ name : 'equalizer',
+
+ version : '5.5.1',
+
+ settings : {
+ use_tallest : true,
+ before_height_change : $.noop,
+ after_height_change : $.noop,
+ equalize_on_stack : false
+ },
+
+ init : function (scope, method, options) {
+ Foundation.inherit(this, 'image_loaded');
+ this.bindings(method, options);
+ this.reflow();
+ },
+
+ events : function () {
+ this.S(window).off('.equalizer').on('resize.fndtn.equalizer', function (e) {
+ this.reflow();
+ }.bind(this));
+ },
+
+ equalize : function (equalizer) {
+ var isStacked = false,
+ vals = equalizer.find('[' + this.attr_name() + '-watch]:visible'),
+ settings = equalizer.data(this.attr_name(true) + '-init');
+
+ if (vals.length === 0) {
+ return;
+ }
+ var firstTopOffset = vals.first().offset().top;
+ settings.before_height_change();
+ equalizer.trigger('before-height-change').trigger('before-height-change.fndth.equalizer');
+ vals.height('inherit');
+ vals.each(function () {
+ var el = $(this);
+ if (el.offset().top !== firstTopOffset) {
+ isStacked = true;
+ }
+ });
+
+ if (settings.equalize_on_stack === false) {
+ if (isStacked) {
+ return;
+ }
+ };
+
+ var heights = vals.map(function () { return $(this).outerHeight(false) }).get();
+
+ if (settings.use_tallest) {
+ var max = Math.max.apply(null, heights);
+ vals.css('height', max);
+ } else {
+ var min = Math.min.apply(null, heights);
+ vals.css('height', min);
+ }
+ settings.after_height_change();
+ equalizer.trigger('after-height-change').trigger('after-height-change.fndtn.equalizer');
+ },
+
+ reflow : function () {
+ var self = this;
+
+ this.S('[' + this.attr_name() + ']', this.scope).each(function () {
+ var $eq_target = $(this);
+ self.image_loaded(self.S('img', this), function () {
+ self.equalize($eq_target)
+ });
+ });
+ }
+ };
+})(jQuery, window, window.document);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.interchange.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.interchange.js
new file mode 100644
index 00000000..9162a4c4
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.interchange.js
@@ -0,0 +1,354 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.interchange = {
+ name : 'interchange',
+
+ version : '5.5.1',
+
+ cache : {},
+
+ images_loaded : false,
+ nodes_loaded : false,
+
+ settings : {
+ load_attr : 'interchange',
+
+ named_queries : {
+ 'default' : 'only screen',
+ 'small' : Foundation.media_queries['small'],
+ 'small-only' : Foundation.media_queries['small-only'],
+ 'medium' : Foundation.media_queries['medium'],
+ 'medium-only' : Foundation.media_queries['medium-only'],
+ 'large' : Foundation.media_queries['large'],
+ 'large-only' : Foundation.media_queries['large-only'],
+ 'xlarge' : Foundation.media_queries['xlarge'],
+ 'xlarge-only' : Foundation.media_queries['xlarge-only'],
+ 'xxlarge' : Foundation.media_queries['xxlarge'],
+ 'landscape' : 'only screen and (orientation: landscape)',
+ 'portrait' : 'only screen and (orientation: portrait)',
+ 'retina' : 'only screen and (-webkit-min-device-pixel-ratio: 2),' +
+ 'only screen and (min--moz-device-pixel-ratio: 2),' +
+ 'only screen and (-o-min-device-pixel-ratio: 2/1),' +
+ 'only screen and (min-device-pixel-ratio: 2),' +
+ 'only screen and (min-resolution: 192dpi),' +
+ 'only screen and (min-resolution: 2dppx)'
+ },
+
+ directives : {
+ replace : function (el, path, trigger) {
+ // The trigger argument, if called within the directive, fires
+ // an event named after the directive on the element, passing
+ // any parameters along to the event that you pass to trigger.
+ //
+ // ex. trigger(), trigger([a, b, c]), or trigger(a, b, c)
+ //
+ // This allows you to bind a callback like so:
+ // $('#interchangeContainer').on('replace', function (e, a, b, c) {
+ // console.log($(this).html(), a, b, c);
+ // });
+
+ if (/IMG/.test(el[0].nodeName)) {
+ var orig_path = el[0].src;
+
+ if (new RegExp(path, 'i').test(orig_path)) {
+ return;
+ }
+
+ el[0].src = path;
+
+ return trigger(el[0].src);
+ }
+ var last_path = el.data(this.data_attr + '-last-path'),
+ self = this;
+
+ if (last_path == path) {
+ return;
+ }
+
+ if (/\.(gif|jpg|jpeg|tiff|png)([?#].*)?/i.test(path)) {
+ $(el).css('background-image', 'url(' + path + ')');
+ el.data('interchange-last-path', path);
+ return trigger(path);
+ }
+
+ return $.get(path, function (response) {
+ el.html(response);
+ el.data(self.data_attr + '-last-path', path);
+ trigger();
+ });
+
+ }
+ }
+ },
+
+ init : function (scope, method, options) {
+ Foundation.inherit(this, 'throttle random_str');
+
+ this.data_attr = this.set_data_attr();
+ $.extend(true, this.settings, method, options);
+ this.bindings(method, options);
+ this.load('images');
+ this.load('nodes');
+ },
+
+ get_media_hash : function () {
+ var mediaHash = '';
+ for (var queryName in this.settings.named_queries ) {
+ mediaHash += matchMedia(this.settings.named_queries[queryName]).matches.toString();
+ }
+ return mediaHash;
+ },
+
+ events : function () {
+ var self = this, prevMediaHash;
+
+ $(window)
+ .off('.interchange')
+ .on('resize.fndtn.interchange', self.throttle(function () {
+ var currMediaHash = self.get_media_hash();
+ if (currMediaHash !== prevMediaHash) {
+ self.resize();
+ }
+ prevMediaHash = currMediaHash;
+ }, 50));
+
+ return this;
+ },
+
+ resize : function () {
+ var cache = this.cache;
+
+ if (!this.images_loaded || !this.nodes_loaded) {
+ setTimeout($.proxy(this.resize, this), 50);
+ return;
+ }
+
+ for (var uuid in cache) {
+ if (cache.hasOwnProperty(uuid)) {
+ var passed = this.results(uuid, cache[uuid]);
+
+ if (passed) {
+ this.settings.directives[passed
+ .scenario[1]].call(this, passed.el, passed.scenario[0], (function (passed) {
+ if (arguments[0] instanceof Array) {
+ var args = arguments[0];
+ } else {
+ var args = Array.prototype.slice.call(arguments, 0);
+ }
+
+ return function() {
+ passed.el.trigger(passed.scenario[1], args);
+ }
+ }(passed)));
+ }
+ }
+ }
+
+ },
+
+ results : function (uuid, scenarios) {
+ var count = scenarios.length;
+
+ if (count > 0) {
+ var el = this.S('[' + this.add_namespace('data-uuid') + '="' + uuid + '"]');
+
+ while (count--) {
+ var mq, rule = scenarios[count][2];
+ if (this.settings.named_queries.hasOwnProperty(rule)) {
+ mq = matchMedia(this.settings.named_queries[rule]);
+ } else {
+ mq = matchMedia(rule);
+ }
+ if (mq.matches) {
+ return {el : el, scenario : scenarios[count]};
+ }
+ }
+ }
+
+ return false;
+ },
+
+ load : function (type, force_update) {
+ if (typeof this['cached_' + type] === 'undefined' || force_update) {
+ this['update_' + type]();
+ }
+
+ return this['cached_' + type];
+ },
+
+ update_images : function () {
+ var images = this.S('img[' + this.data_attr + ']'),
+ count = images.length,
+ i = count,
+ loaded_count = 0,
+ data_attr = this.data_attr;
+
+ this.cache = {};
+ this.cached_images = [];
+ this.images_loaded = (count === 0);
+
+ while (i--) {
+ loaded_count++;
+ if (images[i]) {
+ var str = images[i].getAttribute(data_attr) || '';
+
+ if (str.length > 0) {
+ this.cached_images.push(images[i]);
+ }
+ }
+
+ if (loaded_count === count) {
+ this.images_loaded = true;
+ this.enhance('images');
+ }
+ }
+
+ return this;
+ },
+
+ update_nodes : function () {
+ var nodes = this.S('[' + this.data_attr + ']').not('img'),
+ count = nodes.length,
+ i = count,
+ loaded_count = 0,
+ data_attr = this.data_attr;
+
+ this.cached_nodes = [];
+ this.nodes_loaded = (count === 0);
+
+ while (i--) {
+ loaded_count++;
+ var str = nodes[i].getAttribute(data_attr) || '';
+
+ if (str.length > 0) {
+ this.cached_nodes.push(nodes[i]);
+ }
+
+ if (loaded_count === count) {
+ this.nodes_loaded = true;
+ this.enhance('nodes');
+ }
+ }
+
+ return this;
+ },
+
+ enhance : function (type) {
+ var i = this['cached_' + type].length;
+
+ while (i--) {
+ this.object($(this['cached_' + type][i]));
+ }
+
+ return $(window).trigger('resize').trigger('resize.fndtn.interchange');
+ },
+
+ convert_directive : function (directive) {
+
+ var trimmed = this.trim(directive);
+
+ if (trimmed.length > 0) {
+ return trimmed;
+ }
+
+ return 'replace';
+ },
+
+ parse_scenario : function (scenario) {
+ // This logic had to be made more complex since some users were using commas in the url path
+ // So we cannot simply just split on a comma
+ var directive_match = scenario[0].match(/(.+),\s*(\w+)\s*$/),
+ media_query = scenario[1];
+
+ if (directive_match) {
+ var path = directive_match[1],
+ directive = directive_match[2];
+ } else {
+ var cached_split = scenario[0].split(/,\s*$/),
+ path = cached_split[0],
+ directive = '';
+ }
+
+ return [this.trim(path), this.convert_directive(directive), this.trim(media_query)];
+ },
+
+ object : function (el) {
+ var raw_arr = this.parse_data_attr(el),
+ scenarios = [],
+ i = raw_arr.length;
+
+ if (i > 0) {
+ while (i--) {
+ var split = raw_arr[i].split(/\(([^\)]*?)(\))$/);
+
+ if (split.length > 1) {
+ var params = this.parse_scenario(split);
+ scenarios.push(params);
+ }
+ }
+ }
+
+ return this.store(el, scenarios);
+ },
+
+ store : function (el, scenarios) {
+ var uuid = this.random_str(),
+ current_uuid = el.data(this.add_namespace('uuid', true));
+
+ if (this.cache[current_uuid]) {
+ return this.cache[current_uuid];
+ }
+
+ el.attr(this.add_namespace('data-uuid'), uuid);
+
+ return this.cache[uuid] = scenarios;
+ },
+
+ trim : function (str) {
+
+ if (typeof str === 'string') {
+ return $.trim(str);
+ }
+
+ return str;
+ },
+
+ set_data_attr : function (init) {
+ if (init) {
+ if (this.namespace.length > 0) {
+ return this.namespace + '-' + this.settings.load_attr;
+ }
+
+ return this.settings.load_attr;
+ }
+
+ if (this.namespace.length > 0) {
+ return 'data-' + this.namespace + '-' + this.settings.load_attr;
+ }
+
+ return 'data-' + this.settings.load_attr;
+ },
+
+ parse_data_attr : function (el) {
+ var raw = el.attr(this.attr_name()).split(/\[(.*?)\]/),
+ i = raw.length,
+ output = [];
+
+ while (i--) {
+ if (raw[i].replace(/[\W\d]+/, '').length > 4) {
+ output.push(raw[i]);
+ }
+ }
+
+ return output;
+ },
+
+ reflow : function () {
+ this.load('images', true);
+ this.load('nodes', true);
+ }
+
+ };
+
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.joyride.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.joyride.js
new file mode 100644
index 00000000..7b259c37
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.joyride.js
@@ -0,0 +1,932 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ var Modernizr = Modernizr || false;
+
+ Foundation.libs.joyride = {
+ name : 'joyride',
+
+ version : '5.5.1',
+
+ defaults : {
+ expose : false, // turn on or off the expose feature
+ modal : true, // Whether to cover page with modal during the tour
+ keyboard : true, // enable left, right and esc keystrokes
+ tip_location : 'bottom', // 'top' or 'bottom' in relation to parent
+ nub_position : 'auto', // override on a per tooltip bases
+ scroll_speed : 1500, // Page scrolling speed in milliseconds, 0 = no scroll animation
+ scroll_animation : 'linear', // supports 'swing' and 'linear', extend with jQuery UI.
+ timer : 0, // 0 = no timer , all other numbers = timer in milliseconds
+ start_timer_on_click : true, // true or false - true requires clicking the first button start the timer
+ start_offset : 0, // the index of the tooltip you want to start on (index of the li)
+ next_button : true, // true or false to control whether a next button is used
+ prev_button : true, // true or false to control whether a prev button is used
+ tip_animation : 'fade', // 'pop' or 'fade' in each tip
+ pause_after : [], // array of indexes where to pause the tour after
+ exposed : [], // array of expose elements
+ tip_animation_fade_speed : 300, // when tipAnimation = 'fade' this is speed in milliseconds for the transition
+ cookie_monster : false, // true or false to control whether cookies are used
+ cookie_name : 'joyride', // Name the cookie you'll use
+ cookie_domain : false, // Will this cookie be attached to a domain, ie. '.notableapp.com'
+ cookie_expires : 365, // set when you would like the cookie to expire.
+ tip_container : 'body', // Where will the tip be attached
+ abort_on_close : true, // When true, the close event will not fire any callback
+ tip_location_patterns : {
+ top : ['bottom'],
+ bottom : [], // bottom should not need to be repositioned
+ left : ['right', 'top', 'bottom'],
+ right : ['left', 'top', 'bottom']
+ },
+ post_ride_callback : function () {}, // A method to call once the tour closes (canceled or complete)
+ post_step_callback : function () {}, // A method to call after each step
+ pre_step_callback : function () {}, // A method to call before each step
+ pre_ride_callback : function () {}, // A method to call before the tour starts (passed index, tip, and cloned exposed element)
+ post_expose_callback : function () {}, // A method to call after an element has been exposed
+ template : { // HTML segments for tip layout
+ link : '× ',
+ timer : '
',
+ tip : '
',
+ wrapper : '
',
+ button : ' ',
+ prev_button : ' ',
+ modal : '
',
+ expose : '
',
+ expose_cover : '
'
+ },
+ expose_add_class : '' // One or more space-separated class names to be added to exposed element
+ },
+
+ init : function (scope, method, options) {
+ Foundation.inherit(this, 'throttle random_str');
+
+ this.settings = this.settings || $.extend({}, this.defaults, (options || method));
+
+ this.bindings(method, options)
+ },
+
+ go_next : function () {
+ if (this.settings.$li.next().length < 1) {
+ this.end();
+ } else if (this.settings.timer > 0) {
+ clearTimeout(this.settings.automate);
+ this.hide();
+ this.show();
+ this.startTimer();
+ } else {
+ this.hide();
+ this.show();
+ }
+ },
+
+ go_prev : function () {
+ if (this.settings.$li.prev().length < 1) {
+ // Do nothing if there are no prev element
+ } else if (this.settings.timer > 0) {
+ clearTimeout(this.settings.automate);
+ this.hide();
+ this.show(null, true);
+ this.startTimer();
+ } else {
+ this.hide();
+ this.show(null, true);
+ }
+ },
+
+ events : function () {
+ var self = this;
+
+ $(this.scope)
+ .off('.joyride')
+ .on('click.fndtn.joyride', '.joyride-next-tip, .joyride-modal-bg', function (e) {
+ e.preventDefault();
+ this.go_next()
+ }.bind(this))
+ .on('click.fndtn.joyride', '.joyride-prev-tip', function (e) {
+ e.preventDefault();
+ this.go_prev();
+ }.bind(this))
+
+ .on('click.fndtn.joyride', '.joyride-close-tip', function (e) {
+ e.preventDefault();
+ this.end(this.settings.abort_on_close);
+ }.bind(this))
+
+ .on('keyup.fndtn.joyride', function (e) {
+ // Don't do anything if keystrokes are disabled
+ // or if the joyride is not being shown
+ if (!this.settings.keyboard || !this.settings.riding) {
+ return;
+ }
+
+ switch (e.which) {
+ case 39: // right arrow
+ e.preventDefault();
+ this.go_next();
+ break;
+ case 37: // left arrow
+ e.preventDefault();
+ this.go_prev();
+ break;
+ case 27: // escape
+ e.preventDefault();
+ this.end(this.settings.abort_on_close);
+ }
+ }.bind(this));
+
+ $(window)
+ .off('.joyride')
+ .on('resize.fndtn.joyride', self.throttle(function () {
+ if ($('[' + self.attr_name() + ']').length > 0 && self.settings.$next_tip && self.settings.riding) {
+ if (self.settings.exposed.length > 0) {
+ var $els = $(self.settings.exposed);
+
+ $els.each(function () {
+ var $this = $(this);
+ self.un_expose($this);
+ self.expose($this);
+ });
+ }
+
+ if (self.is_phone()) {
+ self.pos_phone();
+ } else {
+ self.pos_default(false);
+ }
+ }
+ }, 100));
+ },
+
+ start : function () {
+ var self = this,
+ $this = $('[' + this.attr_name() + ']', this.scope),
+ integer_settings = ['timer', 'scrollSpeed', 'startOffset', 'tipAnimationFadeSpeed', 'cookieExpires'],
+ int_settings_count = integer_settings.length;
+
+ if (!$this.length > 0) {
+ return;
+ }
+
+ if (!this.settings.init) {
+ this.events();
+ }
+
+ this.settings = $this.data(this.attr_name(true) + '-init');
+
+ // non configureable settings
+ this.settings.$content_el = $this;
+ this.settings.$body = $(this.settings.tip_container);
+ this.settings.body_offset = $(this.settings.tip_container).position();
+ this.settings.$tip_content = this.settings.$content_el.find('> li');
+ this.settings.paused = false;
+ this.settings.attempts = 0;
+ this.settings.riding = true;
+
+ // can we create cookies?
+ if (typeof $.cookie !== 'function') {
+ this.settings.cookie_monster = false;
+ }
+
+ // generate the tips and insert into dom.
+ if (!this.settings.cookie_monster || this.settings.cookie_monster && !$.cookie(this.settings.cookie_name)) {
+ this.settings.$tip_content.each(function (index) {
+ var $this = $(this);
+ this.settings = $.extend({}, self.defaults, self.data_options($this));
+
+ // Make sure that settings parsed from data_options are integers where necessary
+ var i = int_settings_count;
+ while (i--) {
+ self.settings[integer_settings[i]] = parseInt(self.settings[integer_settings[i]], 10);
+ }
+ self.create({$li : $this, index : index});
+ });
+
+ // show first tip
+ if (!this.settings.start_timer_on_click && this.settings.timer > 0) {
+ this.show('init');
+ this.startTimer();
+ } else {
+ this.show('init');
+ }
+
+ }
+ },
+
+ resume : function () {
+ this.set_li();
+ this.show();
+ },
+
+ tip_template : function (opts) {
+ var $blank, content;
+
+ opts.tip_class = opts.tip_class || '';
+
+ $blank = $(this.settings.template.tip).addClass(opts.tip_class);
+ content = $.trim($(opts.li).html()) +
+ this.prev_button_text(opts.prev_button_text, opts.index) +
+ this.button_text(opts.button_text) +
+ this.settings.template.link +
+ this.timer_instance(opts.index);
+
+ $blank.append($(this.settings.template.wrapper));
+ $blank.first().attr(this.add_namespace('data-index'), opts.index);
+ $('.joyride-content-wrapper', $blank).append(content);
+
+ return $blank[0];
+ },
+
+ timer_instance : function (index) {
+ var txt;
+
+ if ((index === 0 && this.settings.start_timer_on_click && this.settings.timer > 0) || this.settings.timer === 0) {
+ txt = '';
+ } else {
+ txt = $(this.settings.template.timer)[0].outerHTML;
+ }
+ return txt;
+ },
+
+ button_text : function (txt) {
+ if (this.settings.tip_settings.next_button) {
+ txt = $.trim(txt) || 'Next';
+ txt = $(this.settings.template.button).append(txt)[0].outerHTML;
+ } else {
+ txt = '';
+ }
+ return txt;
+ },
+
+ prev_button_text : function (txt, idx) {
+ if (this.settings.tip_settings.prev_button) {
+ txt = $.trim(txt) || 'Previous';
+
+ // Add the disabled class to the button if it's the first element
+ if (idx == 0) {
+ txt = $(this.settings.template.prev_button).append(txt).addClass('disabled')[0].outerHTML;
+ } else {
+ txt = $(this.settings.template.prev_button).append(txt)[0].outerHTML;
+ }
+ } else {
+ txt = '';
+ }
+ return txt;
+ },
+
+ create : function (opts) {
+ this.settings.tip_settings = $.extend({}, this.settings, this.data_options(opts.$li));
+ var buttonText = opts.$li.attr(this.add_namespace('data-button')) || opts.$li.attr(this.add_namespace('data-text')),
+ prevButtonText = opts.$li.attr(this.add_namespace('data-button-prev')) || opts.$li.attr(this.add_namespace('data-prev-text')),
+ tipClass = opts.$li.attr('class'),
+ $tip_content = $(this.tip_template({
+ tip_class : tipClass,
+ index : opts.index,
+ button_text : buttonText,
+ prev_button_text : prevButtonText,
+ li : opts.$li
+ }));
+
+ $(this.settings.tip_container).append($tip_content);
+ },
+
+ show : function (init, is_prev) {
+ var $timer = null;
+
+ // are we paused?
+ if (this.settings.$li === undefined || ($.inArray(this.settings.$li.index(), this.settings.pause_after) === -1)) {
+
+ // don't go to the next li if the tour was paused
+ if (this.settings.paused) {
+ this.settings.paused = false;
+ } else {
+ this.set_li(init, is_prev);
+ }
+
+ this.settings.attempts = 0;
+
+ if (this.settings.$li.length && this.settings.$target.length > 0) {
+ if (init) { //run when we first start
+ this.settings.pre_ride_callback(this.settings.$li.index(), this.settings.$next_tip);
+ if (this.settings.modal) {
+ this.show_modal();
+ }
+ }
+
+ this.settings.pre_step_callback(this.settings.$li.index(), this.settings.$next_tip);
+
+ if (this.settings.modal && this.settings.expose) {
+ this.expose();
+ }
+
+ this.settings.tip_settings = $.extend({}, this.settings, this.data_options(this.settings.$li));
+
+ this.settings.timer = parseInt(this.settings.timer, 10);
+
+ this.settings.tip_settings.tip_location_pattern = this.settings.tip_location_patterns[this.settings.tip_settings.tip_location];
+
+ // scroll and hide bg if not modal
+ if (!/body/i.test(this.settings.$target.selector)) {
+ var joyridemodalbg = $('.joyride-modal-bg');
+ if (/pop/i.test(this.settings.tipAnimation)) {
+ joyridemodalbg.hide();
+ } else {
+ joyridemodalbg.fadeOut(this.settings.tipAnimationFadeSpeed);
+ }
+ this.scroll_to();
+ }
+
+ if (this.is_phone()) {
+ this.pos_phone(true);
+ } else {
+ this.pos_default(true);
+ }
+
+ $timer = this.settings.$next_tip.find('.joyride-timer-indicator');
+
+ if (/pop/i.test(this.settings.tip_animation)) {
+
+ $timer.width(0);
+
+ if (this.settings.timer > 0) {
+
+ this.settings.$next_tip.show();
+
+ setTimeout(function () {
+ $timer.animate({
+ width : $timer.parent().width()
+ }, this.settings.timer, 'linear');
+ }.bind(this), this.settings.tip_animation_fade_speed);
+
+ } else {
+ this.settings.$next_tip.show();
+
+ }
+
+ } else if (/fade/i.test(this.settings.tip_animation)) {
+
+ $timer.width(0);
+
+ if (this.settings.timer > 0) {
+
+ this.settings.$next_tip
+ .fadeIn(this.settings.tip_animation_fade_speed)
+ .show();
+
+ setTimeout(function () {
+ $timer.animate({
+ width : $timer.parent().width()
+ }, this.settings.timer, 'linear');
+ }.bind(this), this.settings.tip_animation_fade_speed);
+
+ } else {
+ this.settings.$next_tip.fadeIn(this.settings.tip_animation_fade_speed);
+ }
+ }
+
+ this.settings.$current_tip = this.settings.$next_tip;
+
+ // skip non-existant targets
+ } else if (this.settings.$li && this.settings.$target.length < 1) {
+
+ this.show(init, is_prev);
+
+ } else {
+
+ this.end();
+
+ }
+ } else {
+
+ this.settings.paused = true;
+
+ }
+
+ },
+
+ is_phone : function () {
+ return matchMedia(Foundation.media_queries.small).matches &&
+ !matchMedia(Foundation.media_queries.medium).matches;
+ },
+
+ hide : function () {
+ if (this.settings.modal && this.settings.expose) {
+ this.un_expose();
+ }
+
+ if (!this.settings.modal) {
+ $('.joyride-modal-bg').hide();
+ }
+
+ // Prevent scroll bouncing...wait to remove from layout
+ this.settings.$current_tip.css('visibility', 'hidden');
+ setTimeout($.proxy(function () {
+ this.hide();
+ this.css('visibility', 'visible');
+ }, this.settings.$current_tip), 0);
+ this.settings.post_step_callback(this.settings.$li.index(),
+ this.settings.$current_tip);
+ },
+
+ set_li : function (init, is_prev) {
+ if (init) {
+ this.settings.$li = this.settings.$tip_content.eq(this.settings.start_offset);
+ this.set_next_tip();
+ this.settings.$current_tip = this.settings.$next_tip;
+ } else {
+ if (is_prev) {
+ this.settings.$li = this.settings.$li.prev();
+ } else {
+ this.settings.$li = this.settings.$li.next();
+ }
+ this.set_next_tip();
+ }
+
+ this.set_target();
+ },
+
+ set_next_tip : function () {
+ this.settings.$next_tip = $('.joyride-tip-guide').eq(this.settings.$li.index());
+ this.settings.$next_tip.data('closed', '');
+ },
+
+ set_target : function () {
+ var cl = this.settings.$li.attr(this.add_namespace('data-class')),
+ id = this.settings.$li.attr(this.add_namespace('data-id')),
+ $sel = function () {
+ if (id) {
+ return $(document.getElementById(id));
+ } else if (cl) {
+ return $('.' + cl).first();
+ } else {
+ return $('body');
+ }
+ };
+
+ this.settings.$target = $sel();
+ },
+
+ scroll_to : function () {
+ var window_half, tipOffset;
+
+ window_half = $(window).height() / 2;
+ tipOffset = Math.ceil(this.settings.$target.offset().top - window_half + this.settings.$next_tip.outerHeight());
+
+ if (tipOffset != 0) {
+ $('html, body').stop().animate({
+ scrollTop : tipOffset
+ }, this.settings.scroll_speed, 'swing');
+ }
+ },
+
+ paused : function () {
+ return ($.inArray((this.settings.$li.index() + 1), this.settings.pause_after) === -1);
+ },
+
+ restart : function () {
+ this.hide();
+ this.settings.$li = undefined;
+ this.show('init');
+ },
+
+ pos_default : function (init) {
+ var $nub = this.settings.$next_tip.find('.joyride-nub'),
+ nub_width = Math.ceil($nub.outerWidth() / 2),
+ nub_height = Math.ceil($nub.outerHeight() / 2),
+ toggle = init || false;
+
+ // tip must not be "display: none" to calculate position
+ if (toggle) {
+ this.settings.$next_tip.css('visibility', 'hidden');
+ this.settings.$next_tip.show();
+ }
+
+ if (!/body/i.test(this.settings.$target.selector)) {
+ var topAdjustment = this.settings.tip_settings.tipAdjustmentY ? parseInt(this.settings.tip_settings.tipAdjustmentY) : 0,
+ leftAdjustment = this.settings.tip_settings.tipAdjustmentX ? parseInt(this.settings.tip_settings.tipAdjustmentX) : 0;
+
+ if (this.bottom()) {
+ if (this.rtl) {
+ this.settings.$next_tip.css({
+ top : (this.settings.$target.offset().top + nub_height + this.settings.$target.outerHeight() + topAdjustment),
+ left : this.settings.$target.offset().left + this.settings.$target.outerWidth() - this.settings.$next_tip.outerWidth() + leftAdjustment});
+ } else {
+ this.settings.$next_tip.css({
+ top : (this.settings.$target.offset().top + nub_height + this.settings.$target.outerHeight() + topAdjustment),
+ left : this.settings.$target.offset().left + leftAdjustment});
+ }
+
+ this.nub_position($nub, this.settings.tip_settings.nub_position, 'top');
+
+ } else if (this.top()) {
+ if (this.rtl) {
+ this.settings.$next_tip.css({
+ top : (this.settings.$target.offset().top - this.settings.$next_tip.outerHeight() - nub_height + topAdjustment),
+ left : this.settings.$target.offset().left + this.settings.$target.outerWidth() - this.settings.$next_tip.outerWidth()});
+ } else {
+ this.settings.$next_tip.css({
+ top : (this.settings.$target.offset().top - this.settings.$next_tip.outerHeight() - nub_height + topAdjustment),
+ left : this.settings.$target.offset().left + leftAdjustment});
+ }
+
+ this.nub_position($nub, this.settings.tip_settings.nub_position, 'bottom');
+
+ } else if (this.right()) {
+
+ this.settings.$next_tip.css({
+ top : this.settings.$target.offset().top + topAdjustment,
+ left : (this.settings.$target.outerWidth() + this.settings.$target.offset().left + nub_width + leftAdjustment)});
+
+ this.nub_position($nub, this.settings.tip_settings.nub_position, 'left');
+
+ } else if (this.left()) {
+
+ this.settings.$next_tip.css({
+ top : this.settings.$target.offset().top + topAdjustment,
+ left : (this.settings.$target.offset().left - this.settings.$next_tip.outerWidth() - nub_width + leftAdjustment)});
+
+ this.nub_position($nub, this.settings.tip_settings.nub_position, 'right');
+
+ }
+
+ if (!this.visible(this.corners(this.settings.$next_tip)) && this.settings.attempts < this.settings.tip_settings.tip_location_pattern.length) {
+
+ $nub.removeClass('bottom')
+ .removeClass('top')
+ .removeClass('right')
+ .removeClass('left');
+
+ this.settings.tip_settings.tip_location = this.settings.tip_settings.tip_location_pattern[this.settings.attempts];
+
+ this.settings.attempts++;
+
+ this.pos_default();
+
+ }
+
+ } else if (this.settings.$li.length) {
+
+ this.pos_modal($nub);
+
+ }
+
+ if (toggle) {
+ this.settings.$next_tip.hide();
+ this.settings.$next_tip.css('visibility', 'visible');
+ }
+
+ },
+
+ pos_phone : function (init) {
+ var tip_height = this.settings.$next_tip.outerHeight(),
+ tip_offset = this.settings.$next_tip.offset(),
+ target_height = this.settings.$target.outerHeight(),
+ $nub = $('.joyride-nub', this.settings.$next_tip),
+ nub_height = Math.ceil($nub.outerHeight() / 2),
+ toggle = init || false;
+
+ $nub.removeClass('bottom')
+ .removeClass('top')
+ .removeClass('right')
+ .removeClass('left');
+
+ if (toggle) {
+ this.settings.$next_tip.css('visibility', 'hidden');
+ this.settings.$next_tip.show();
+ }
+
+ if (!/body/i.test(this.settings.$target.selector)) {
+
+ if (this.top()) {
+
+ this.settings.$next_tip.offset({top : this.settings.$target.offset().top - tip_height - nub_height});
+ $nub.addClass('bottom');
+
+ } else {
+
+ this.settings.$next_tip.offset({top : this.settings.$target.offset().top + target_height + nub_height});
+ $nub.addClass('top');
+
+ }
+
+ } else if (this.settings.$li.length) {
+ this.pos_modal($nub);
+ }
+
+ if (toggle) {
+ this.settings.$next_tip.hide();
+ this.settings.$next_tip.css('visibility', 'visible');
+ }
+ },
+
+ pos_modal : function ($nub) {
+ this.center();
+ $nub.hide();
+
+ this.show_modal();
+ },
+
+ show_modal : function () {
+ if (!this.settings.$next_tip.data('closed')) {
+ var joyridemodalbg = $('.joyride-modal-bg');
+ if (joyridemodalbg.length < 1) {
+ var joyridemodalbg = $(this.settings.template.modal);
+ joyridemodalbg.appendTo('body');
+ }
+
+ if (/pop/i.test(this.settings.tip_animation)) {
+ joyridemodalbg.show();
+ } else {
+ joyridemodalbg.fadeIn(this.settings.tip_animation_fade_speed);
+ }
+ }
+ },
+
+ expose : function () {
+ var expose,
+ exposeCover,
+ el,
+ origCSS,
+ origClasses,
+ randId = 'expose-' + this.random_str(6);
+
+ if (arguments.length > 0 && arguments[0] instanceof $) {
+ el = arguments[0];
+ } else if (this.settings.$target && !/body/i.test(this.settings.$target.selector)) {
+ el = this.settings.$target;
+ } else {
+ return false;
+ }
+
+ if (el.length < 1) {
+ if (window.console) {
+ console.error('element not valid', el);
+ }
+ return false;
+ }
+
+ expose = $(this.settings.template.expose);
+ this.settings.$body.append(expose);
+ expose.css({
+ top : el.offset().top,
+ left : el.offset().left,
+ width : el.outerWidth(true),
+ height : el.outerHeight(true)
+ });
+
+ exposeCover = $(this.settings.template.expose_cover);
+
+ origCSS = {
+ zIndex : el.css('z-index'),
+ position : el.css('position')
+ };
+
+ origClasses = el.attr('class') == null ? '' : el.attr('class');
+
+ el.css('z-index', parseInt(expose.css('z-index')) + 1);
+
+ if (origCSS.position == 'static') {
+ el.css('position', 'relative');
+ }
+
+ el.data('expose-css', origCSS);
+ el.data('orig-class', origClasses);
+ el.attr('class', origClasses + ' ' + this.settings.expose_add_class);
+
+ exposeCover.css({
+ top : el.offset().top,
+ left : el.offset().left,
+ width : el.outerWidth(true),
+ height : el.outerHeight(true)
+ });
+
+ if (this.settings.modal) {
+ this.show_modal();
+ }
+
+ this.settings.$body.append(exposeCover);
+ expose.addClass(randId);
+ exposeCover.addClass(randId);
+ el.data('expose', randId);
+ this.settings.post_expose_callback(this.settings.$li.index(), this.settings.$next_tip, el);
+ this.add_exposed(el);
+ },
+
+ un_expose : function () {
+ var exposeId,
+ el,
+ expose,
+ origCSS,
+ origClasses,
+ clearAll = false;
+
+ if (arguments.length > 0 && arguments[0] instanceof $) {
+ el = arguments[0];
+ } else if (this.settings.$target && !/body/i.test(this.settings.$target.selector)) {
+ el = this.settings.$target;
+ } else {
+ return false;
+ }
+
+ if (el.length < 1) {
+ if (window.console) {
+ console.error('element not valid', el);
+ }
+ return false;
+ }
+
+ exposeId = el.data('expose');
+ expose = $('.' + exposeId);
+
+ if (arguments.length > 1) {
+ clearAll = arguments[1];
+ }
+
+ if (clearAll === true) {
+ $('.joyride-expose-wrapper,.joyride-expose-cover').remove();
+ } else {
+ expose.remove();
+ }
+
+ origCSS = el.data('expose-css');
+
+ if (origCSS.zIndex == 'auto') {
+ el.css('z-index', '');
+ } else {
+ el.css('z-index', origCSS.zIndex);
+ }
+
+ if (origCSS.position != el.css('position')) {
+ if (origCSS.position == 'static') {// this is default, no need to set it.
+ el.css('position', '');
+ } else {
+ el.css('position', origCSS.position);
+ }
+ }
+
+ origClasses = el.data('orig-class');
+ el.attr('class', origClasses);
+ el.removeData('orig-classes');
+
+ el.removeData('expose');
+ el.removeData('expose-z-index');
+ this.remove_exposed(el);
+ },
+
+ add_exposed : function (el) {
+ this.settings.exposed = this.settings.exposed || [];
+ if (el instanceof $ || typeof el === 'object') {
+ this.settings.exposed.push(el[0]);
+ } else if (typeof el == 'string') {
+ this.settings.exposed.push(el);
+ }
+ },
+
+ remove_exposed : function (el) {
+ var search, i;
+ if (el instanceof $) {
+ search = el[0]
+ } else if (typeof el == 'string') {
+ search = el;
+ }
+
+ this.settings.exposed = this.settings.exposed || [];
+ i = this.settings.exposed.length;
+
+ while (i--) {
+ if (this.settings.exposed[i] == search) {
+ this.settings.exposed.splice(i, 1);
+ return;
+ }
+ }
+ },
+
+ center : function () {
+ var $w = $(window);
+
+ this.settings.$next_tip.css({
+ top : ((($w.height() - this.settings.$next_tip.outerHeight()) / 2) + $w.scrollTop()),
+ left : ((($w.width() - this.settings.$next_tip.outerWidth()) / 2) + $w.scrollLeft())
+ });
+
+ return true;
+ },
+
+ bottom : function () {
+ return /bottom/i.test(this.settings.tip_settings.tip_location);
+ },
+
+ top : function () {
+ return /top/i.test(this.settings.tip_settings.tip_location);
+ },
+
+ right : function () {
+ return /right/i.test(this.settings.tip_settings.tip_location);
+ },
+
+ left : function () {
+ return /left/i.test(this.settings.tip_settings.tip_location);
+ },
+
+ corners : function (el) {
+ var w = $(window),
+ window_half = w.height() / 2,
+ //using this to calculate since scroll may not have finished yet.
+ tipOffset = Math.ceil(this.settings.$target.offset().top - window_half + this.settings.$next_tip.outerHeight()),
+ right = w.width() + w.scrollLeft(),
+ offsetBottom = w.height() + tipOffset,
+ bottom = w.height() + w.scrollTop(),
+ top = w.scrollTop();
+
+ if (tipOffset < top) {
+ if (tipOffset < 0) {
+ top = 0;
+ } else {
+ top = tipOffset;
+ }
+ }
+
+ if (offsetBottom > bottom) {
+ bottom = offsetBottom;
+ }
+
+ return [
+ el.offset().top < top,
+ right < el.offset().left + el.outerWidth(),
+ bottom < el.offset().top + el.outerHeight(),
+ w.scrollLeft() > el.offset().left
+ ];
+ },
+
+ visible : function (hidden_corners) {
+ var i = hidden_corners.length;
+
+ while (i--) {
+ if (hidden_corners[i]) {
+ return false;
+ }
+ }
+
+ return true;
+ },
+
+ nub_position : function (nub, pos, def) {
+ if (pos === 'auto') {
+ nub.addClass(def);
+ } else {
+ nub.addClass(pos);
+ }
+ },
+
+ startTimer : function () {
+ if (this.settings.$li.length) {
+ this.settings.automate = setTimeout(function () {
+ this.hide();
+ this.show();
+ this.startTimer();
+ }.bind(this), this.settings.timer);
+ } else {
+ clearTimeout(this.settings.automate);
+ }
+ },
+
+ end : function (abort) {
+ if (this.settings.cookie_monster) {
+ $.cookie(this.settings.cookie_name, 'ridden', {expires : this.settings.cookie_expires, domain : this.settings.cookie_domain});
+ }
+
+ if (this.settings.timer > 0) {
+ clearTimeout(this.settings.automate);
+ }
+
+ if (this.settings.modal && this.settings.expose) {
+ this.un_expose();
+ }
+
+ // Unplug keystrokes listener
+ $(this.scope).off('keyup.joyride')
+
+ this.settings.$next_tip.data('closed', true);
+ this.settings.riding = false;
+
+ $('.joyride-modal-bg').hide();
+ this.settings.$current_tip.hide();
+
+ if (typeof abort === 'undefined' || abort === false) {
+ this.settings.post_step_callback(this.settings.$li.index(), this.settings.$current_tip);
+ this.settings.post_ride_callback(this.settings.$li.index(), this.settings.$current_tip);
+ }
+
+ $('.joyride-tip-guide').remove();
+ },
+
+ off : function () {
+ $(this.scope).off('.joyride');
+ $(window).off('.joyride');
+ $('.joyride-close-tip, .joyride-next-tip, .joyride-modal-bg').off('.joyride');
+ $('.joyride-tip-guide, .joyride-modal-bg').remove();
+ clearTimeout(this.settings.automate);
+ this.settings = {};
+ },
+
+ reflow : function () {}
+ };
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.js
new file mode 100644
index 00000000..65e63040
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.js
@@ -0,0 +1,703 @@
+/*
+ * Foundation Responsive Library
+ * http://foundation.zurb.com
+ * Copyright 2014, ZURB
+ * Free to use under the MIT license.
+ * http://www.opensource.org/licenses/mit-license.php
+*/
+
+(function ($, window, document, undefined) {
+ 'use strict';
+
+ var header_helpers = function (class_array) {
+ var i = class_array.length;
+ var head = $('head');
+
+ while (i--) {
+ if (head.has('.' + class_array[i]).length === 0) {
+ head.append(' ');
+ }
+ }
+ };
+
+ header_helpers([
+ 'foundation-mq-small',
+ 'foundation-mq-small-only',
+ 'foundation-mq-medium',
+ 'foundation-mq-medium-only',
+ 'foundation-mq-large',
+ 'foundation-mq-large-only',
+ 'foundation-mq-xlarge',
+ 'foundation-mq-xlarge-only',
+ 'foundation-mq-xxlarge',
+ 'foundation-data-attribute-namespace']);
+
+ // Enable FastClick if present
+
+ $(function () {
+ if (typeof FastClick !== 'undefined') {
+ // Don't attach to body if undefined
+ if (typeof document.body !== 'undefined') {
+ FastClick.attach(document.body);
+ }
+ }
+ });
+
+ // private Fast Selector wrapper,
+ // returns jQuery object. Only use where
+ // getElementById is not available.
+ var S = function (selector, context) {
+ if (typeof selector === 'string') {
+ if (context) {
+ var cont;
+ if (context.jquery) {
+ cont = context[0];
+ if (!cont) {
+ return context;
+ }
+ } else {
+ cont = context;
+ }
+ return $(cont.querySelectorAll(selector));
+ }
+
+ return $(document.querySelectorAll(selector));
+ }
+
+ return $(selector, context);
+ };
+
+ // Namespace functions.
+
+ var attr_name = function (init) {
+ var arr = [];
+ if (!init) {
+ arr.push('data');
+ }
+ if (this.namespace.length > 0) {
+ arr.push(this.namespace);
+ }
+ arr.push(this.name);
+
+ return arr.join('-');
+ };
+
+ var add_namespace = function (str) {
+ var parts = str.split('-'),
+ i = parts.length,
+ arr = [];
+
+ while (i--) {
+ if (i !== 0) {
+ arr.push(parts[i]);
+ } else {
+ if (this.namespace.length > 0) {
+ arr.push(this.namespace, parts[i]);
+ } else {
+ arr.push(parts[i]);
+ }
+ }
+ }
+
+ return arr.reverse().join('-');
+ };
+
+ // Event binding and data-options updating.
+
+ var bindings = function (method, options) {
+ var self = this,
+ bind = function(){
+ var $this = S(this),
+ should_bind_events = !$this.data(self.attr_name(true) + '-init');
+ $this.data(self.attr_name(true) + '-init', $.extend({}, self.settings, (options || method), self.data_options($this)));
+
+ if (should_bind_events) {
+ self.events(this);
+ }
+ };
+
+ if (S(this.scope).is('[' + this.attr_name() +']')) {
+ bind.call(this.scope);
+ } else {
+ S('[' + this.attr_name() +']', this.scope).each(bind);
+ }
+ // # Patch to fix #5043 to move this *after* the if/else clause in order for Backbone and similar frameworks to have improved control over event binding and data-options updating.
+ if (typeof method === 'string') {
+ return this[method].call(this, options);
+ }
+
+ };
+
+ var single_image_loaded = function (image, callback) {
+ function loaded () {
+ callback(image[0]);
+ }
+
+ function bindLoad () {
+ this.one('load', loaded);
+
+ if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
+ var src = this.attr( 'src' ),
+ param = src.match( /\?/ ) ? '&' : '?';
+
+ param += 'random=' + (new Date()).getTime();
+ this.attr('src', src + param);
+ }
+ }
+
+ if (!image.attr('src')) {
+ loaded();
+ return;
+ }
+
+ if (image[0].complete || image[0].readyState === 4) {
+ loaded();
+ } else {
+ bindLoad.call(image);
+ }
+ };
+
+ /*
+ https://github.com/paulirish/matchMedia.js
+ */
+
+ window.matchMedia = window.matchMedia || (function ( doc ) {
+
+ 'use strict';
+
+ var bool,
+ docElem = doc.documentElement,
+ refNode = docElem.firstElementChild || docElem.firstChild,
+ // fakeBody required for
+ fakeBody = doc.createElement( 'body' ),
+ div = doc.createElement( 'div' );
+
+ div.id = 'mq-test-1';
+ div.style.cssText = 'position:absolute;top:-100em';
+ fakeBody.style.background = 'none';
+ fakeBody.appendChild(div);
+
+ return function (q) {
+
+ div.innerHTML = '';
+
+ docElem.insertBefore( fakeBody, refNode );
+ bool = div.offsetWidth === 42;
+ docElem.removeChild( fakeBody );
+
+ return {
+ matches : bool,
+ media : q
+ };
+
+ };
+
+ }( document ));
+
+ /*
+ * jquery.requestAnimationFrame
+ * https://github.com/gnarf37/jquery-requestAnimationFrame
+ * Requires jQuery 1.8+
+ *
+ * Copyright (c) 2012 Corey Frang
+ * Licensed under the MIT license.
+ */
+
+ (function(jQuery) {
+
+
+ // requestAnimationFrame polyfill adapted from Erik Möller
+ // fixes from Paul Irish and Tino Zijdel
+ // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
+ // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
+
+ var animating,
+ lastTime = 0,
+ vendors = ['webkit', 'moz'],
+ requestAnimationFrame = window.requestAnimationFrame,
+ cancelAnimationFrame = window.cancelAnimationFrame,
+ jqueryFxAvailable = 'undefined' !== typeof jQuery.fx;
+
+ for (; lastTime < vendors.length && !requestAnimationFrame; lastTime++) {
+ requestAnimationFrame = window[ vendors[lastTime] + 'RequestAnimationFrame' ];
+ cancelAnimationFrame = cancelAnimationFrame ||
+ window[ vendors[lastTime] + 'CancelAnimationFrame' ] ||
+ window[ vendors[lastTime] + 'CancelRequestAnimationFrame' ];
+ }
+
+ function raf() {
+ if (animating) {
+ requestAnimationFrame(raf);
+
+ if (jqueryFxAvailable) {
+ jQuery.fx.tick();
+ }
+ }
+ }
+
+ if (requestAnimationFrame) {
+ // use rAF
+ window.requestAnimationFrame = requestAnimationFrame;
+ window.cancelAnimationFrame = cancelAnimationFrame;
+
+ if (jqueryFxAvailable) {
+ jQuery.fx.timer = function (timer) {
+ if (timer() && jQuery.timers.push(timer) && !animating) {
+ animating = true;
+ raf();
+ }
+ };
+
+ jQuery.fx.stop = function () {
+ animating = false;
+ };
+ }
+ } else {
+ // polyfill
+ window.requestAnimationFrame = function (callback) {
+ var currTime = new Date().getTime(),
+ timeToCall = Math.max(0, 16 - (currTime - lastTime)),
+ id = window.setTimeout(function () {
+ callback(currTime + timeToCall);
+ }, timeToCall);
+ lastTime = currTime + timeToCall;
+ return id;
+ };
+
+ window.cancelAnimationFrame = function (id) {
+ clearTimeout(id);
+ };
+
+ }
+
+ }( $ ));
+
+ function removeQuotes (string) {
+ if (typeof string === 'string' || string instanceof String) {
+ string = string.replace(/^['\\/"]+|(;\s?})+|['\\/"]+$/g, '');
+ }
+
+ return string;
+ }
+
+ window.Foundation = {
+ name : 'Foundation',
+
+ version : '5.5.1',
+
+ media_queries : {
+ 'small' : S('.foundation-mq-small').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
+ 'small-only' : S('.foundation-mq-small-only').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
+ 'medium' : S('.foundation-mq-medium').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
+ 'medium-only' : S('.foundation-mq-medium-only').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
+ 'large' : S('.foundation-mq-large').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
+ 'large-only' : S('.foundation-mq-large-only').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
+ 'xlarge' : S('.foundation-mq-xlarge').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
+ 'xlarge-only' : S('.foundation-mq-xlarge-only').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
+ 'xxlarge' : S('.foundation-mq-xxlarge').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, '')
+ },
+
+ stylesheet : $('').appendTo('head')[0].sheet,
+
+ global : {
+ namespace : undefined
+ },
+
+ init : function (scope, libraries, method, options, response) {
+ var args = [scope, method, options, response],
+ responses = [];
+
+ // check RTL
+ this.rtl = /rtl/i.test(S('html').attr('dir'));
+
+ // set foundation global scope
+ this.scope = scope || this.scope;
+
+ this.set_namespace();
+
+ if (libraries && typeof libraries === 'string' && !/reflow/i.test(libraries)) {
+ if (this.libs.hasOwnProperty(libraries)) {
+ responses.push(this.init_lib(libraries, args));
+ }
+ } else {
+ for (var lib in this.libs) {
+ responses.push(this.init_lib(lib, libraries));
+ }
+ }
+
+ S(window).load(function () {
+ S(window)
+ .trigger('resize.fndtn.clearing')
+ .trigger('resize.fndtn.dropdown')
+ .trigger('resize.fndtn.equalizer')
+ .trigger('resize.fndtn.interchange')
+ .trigger('resize.fndtn.joyride')
+ .trigger('resize.fndtn.magellan')
+ .trigger('resize.fndtn.topbar')
+ .trigger('resize.fndtn.slider');
+ });
+
+ return scope;
+ },
+
+ init_lib : function (lib, args) {
+ if (this.libs.hasOwnProperty(lib)) {
+ this.patch(this.libs[lib]);
+
+ if (args && args.hasOwnProperty(lib)) {
+ if (typeof this.libs[lib].settings !== 'undefined') {
+ $.extend(true, this.libs[lib].settings, args[lib]);
+ } else if (typeof this.libs[lib].defaults !== 'undefined') {
+ $.extend(true, this.libs[lib].defaults, args[lib]);
+ }
+ return this.libs[lib].init.apply(this.libs[lib], [this.scope, args[lib]]);
+ }
+
+ args = args instanceof Array ? args : new Array(args);
+ return this.libs[lib].init.apply(this.libs[lib], args);
+ }
+
+ return function () {};
+ },
+
+ patch : function (lib) {
+ lib.scope = this.scope;
+ lib.namespace = this.global.namespace;
+ lib.rtl = this.rtl;
+ lib['data_options'] = this.utils.data_options;
+ lib['attr_name'] = attr_name;
+ lib['add_namespace'] = add_namespace;
+ lib['bindings'] = bindings;
+ lib['S'] = this.utils.S;
+ },
+
+ inherit : function (scope, methods) {
+ var methods_arr = methods.split(' '),
+ i = methods_arr.length;
+
+ while (i--) {
+ if (this.utils.hasOwnProperty(methods_arr[i])) {
+ scope[methods_arr[i]] = this.utils[methods_arr[i]];
+ }
+ }
+ },
+
+ set_namespace : function () {
+
+ // Description:
+ // Don't bother reading the namespace out of the meta tag
+ // if the namespace has been set globally in javascript
+ //
+ // Example:
+ // Foundation.global.namespace = 'my-namespace';
+ // or make it an empty string:
+ // Foundation.global.namespace = '';
+ //
+ //
+
+ // If the namespace has not been set (is undefined), try to read it out of the meta element.
+ // Otherwise use the globally defined namespace, even if it's empty ('')
+ var namespace = ( this.global.namespace === undefined ) ? $('.foundation-data-attribute-namespace').css('font-family') : this.global.namespace;
+
+ // Finally, if the namsepace is either undefined or false, set it to an empty string.
+ // Otherwise use the namespace value.
+ this.global.namespace = ( namespace === undefined || /false/i.test(namespace) ) ? '' : namespace;
+ },
+
+ libs : {},
+
+ // methods that can be inherited in libraries
+ utils : {
+
+ // Description:
+ // Fast Selector wrapper returns jQuery object. Only use where getElementById
+ // is not available.
+ //
+ // Arguments:
+ // Selector (String): CSS selector describing the element(s) to be
+ // returned as a jQuery object.
+ //
+ // Scope (String): CSS selector describing the area to be searched. Default
+ // is document.
+ //
+ // Returns:
+ // Element (jQuery Object): jQuery object containing elements matching the
+ // selector within the scope.
+ S : S,
+
+ // Description:
+ // Executes a function a max of once every n milliseconds
+ //
+ // Arguments:
+ // Func (Function): Function to be throttled.
+ //
+ // Delay (Integer): Function execution threshold in milliseconds.
+ //
+ // Returns:
+ // Lazy_function (Function): Function with throttling applied.
+ throttle : function (func, delay) {
+ var timer = null;
+
+ return function () {
+ var context = this, args = arguments;
+
+ if (timer == null) {
+ timer = setTimeout(function () {
+ func.apply(context, args);
+ timer = null;
+ }, delay);
+ }
+ };
+ },
+
+ // Description:
+ // Executes a function when it stops being invoked for n seconds
+ // Modified version of _.debounce() http://underscorejs.org
+ //
+ // Arguments:
+ // Func (Function): Function to be debounced.
+ //
+ // Delay (Integer): Function execution threshold in milliseconds.
+ //
+ // Immediate (Bool): Whether the function should be called at the beginning
+ // of the delay instead of the end. Default is false.
+ //
+ // Returns:
+ // Lazy_function (Function): Function with debouncing applied.
+ debounce : function (func, delay, immediate) {
+ var timeout, result;
+ return function () {
+ var context = this, args = arguments;
+ var later = function () {
+ timeout = null;
+ if (!immediate) {
+ result = func.apply(context, args);
+ }
+ };
+ var callNow = immediate && !timeout;
+ clearTimeout(timeout);
+ timeout = setTimeout(later, delay);
+ if (callNow) {
+ result = func.apply(context, args);
+ }
+ return result;
+ };
+ },
+
+ // Description:
+ // Parses data-options attribute
+ //
+ // Arguments:
+ // El (jQuery Object): Element to be parsed.
+ //
+ // Returns:
+ // Options (Javascript Object): Contents of the element's data-options
+ // attribute.
+ data_options : function (el, data_attr_name) {
+ data_attr_name = data_attr_name || 'options';
+ var opts = {}, ii, p, opts_arr,
+ data_options = function (el) {
+ var namespace = Foundation.global.namespace;
+
+ if (namespace.length > 0) {
+ return el.data(namespace + '-' + data_attr_name);
+ }
+
+ return el.data(data_attr_name);
+ };
+
+ var cached_options = data_options(el);
+
+ if (typeof cached_options === 'object') {
+ return cached_options;
+ }
+
+ opts_arr = (cached_options || ':').split(';');
+ ii = opts_arr.length;
+
+ function isNumber (o) {
+ return !isNaN (o - 0) && o !== null && o !== '' && o !== false && o !== true;
+ }
+
+ function trim (str) {
+ if (typeof str === 'string') {
+ return $.trim(str);
+ }
+ return str;
+ }
+
+ while (ii--) {
+ p = opts_arr[ii].split(':');
+ p = [p[0], p.slice(1).join(':')];
+
+ if (/true/i.test(p[1])) {
+ p[1] = true;
+ }
+ if (/false/i.test(p[1])) {
+ p[1] = false;
+ }
+ if (isNumber(p[1])) {
+ if (p[1].indexOf('.') === -1) {
+ p[1] = parseInt(p[1], 10);
+ } else {
+ p[1] = parseFloat(p[1]);
+ }
+ }
+
+ if (p.length === 2 && p[0].length > 0) {
+ opts[trim(p[0])] = trim(p[1]);
+ }
+ }
+
+ return opts;
+ },
+
+ // Description:
+ // Adds JS-recognizable media queries
+ //
+ // Arguments:
+ // Media (String): Key string for the media query to be stored as in
+ // Foundation.media_queries
+ //
+ // Class (String): Class name for the generated tag
+ register_media : function (media, media_class) {
+ if (Foundation.media_queries[media] === undefined) {
+ $('head').append(' ');
+ Foundation.media_queries[media] = removeQuotes($('.' + media_class).css('font-family'));
+ }
+ },
+
+ // Description:
+ // Add custom CSS within a JS-defined media query
+ //
+ // Arguments:
+ // Rule (String): CSS rule to be appended to the document.
+ //
+ // Media (String): Optional media query string for the CSS rule to be
+ // nested under.
+ add_custom_rule : function (rule, media) {
+ if (media === undefined && Foundation.stylesheet) {
+ Foundation.stylesheet.insertRule(rule, Foundation.stylesheet.cssRules.length);
+ } else {
+ var query = Foundation.media_queries[media];
+
+ if (query !== undefined) {
+ Foundation.stylesheet.insertRule('@media ' +
+ Foundation.media_queries[media] + '{ ' + rule + ' }');
+ }
+ }
+ },
+
+ // Description:
+ // Performs a callback function when an image is fully loaded
+ //
+ // Arguments:
+ // Image (jQuery Object): Image(s) to check if loaded.
+ //
+ // Callback (Function): Function to execute when image is fully loaded.
+ image_loaded : function (images, callback) {
+ var self = this,
+ unloaded = images.length;
+
+ if (unloaded === 0) {
+ callback(images);
+ }
+
+ images.each(function () {
+ single_image_loaded(self.S(this), function () {
+ unloaded -= 1;
+ if (unloaded === 0) {
+ callback(images);
+ }
+ });
+ });
+ },
+
+ // Description:
+ // Returns a random, alphanumeric string
+ //
+ // Arguments:
+ // Length (Integer): Length of string to be generated. Defaults to random
+ // integer.
+ //
+ // Returns:
+ // Rand (String): Pseudo-random, alphanumeric string.
+ random_str : function () {
+ if (!this.fidx) {
+ this.fidx = 0;
+ }
+ this.prefix = this.prefix || [(this.name || 'F'), (+new Date).toString(36)].join('-');
+
+ return this.prefix + (this.fidx++).toString(36);
+ },
+
+ // Description:
+ // Helper for window.matchMedia
+ //
+ // Arguments:
+ // mq (String): Media query
+ //
+ // Returns:
+ // (Boolean): Whether the media query passes or not
+ match : function (mq) {
+ return window.matchMedia(mq).matches;
+ },
+
+ // Description:
+ // Helpers for checking Foundation default media queries with JS
+ //
+ // Returns:
+ // (Boolean): Whether the media query passes or not
+
+ is_small_up : function () {
+ return this.match(Foundation.media_queries.small);
+ },
+
+ is_medium_up : function () {
+ return this.match(Foundation.media_queries.medium);
+ },
+
+ is_large_up : function () {
+ return this.match(Foundation.media_queries.large);
+ },
+
+ is_xlarge_up : function () {
+ return this.match(Foundation.media_queries.xlarge);
+ },
+
+ is_xxlarge_up : function () {
+ return this.match(Foundation.media_queries.xxlarge);
+ },
+
+ is_small_only : function () {
+ return !this.is_medium_up() && !this.is_large_up() && !this.is_xlarge_up() && !this.is_xxlarge_up();
+ },
+
+ is_medium_only : function () {
+ return this.is_medium_up() && !this.is_large_up() && !this.is_xlarge_up() && !this.is_xxlarge_up();
+ },
+
+ is_large_only : function () {
+ return this.is_medium_up() && this.is_large_up() && !this.is_xlarge_up() && !this.is_xxlarge_up();
+ },
+
+ is_xlarge_only : function () {
+ return this.is_medium_up() && this.is_large_up() && this.is_xlarge_up() && !this.is_xxlarge_up();
+ },
+
+ is_xxlarge_only : function () {
+ return this.is_medium_up() && this.is_large_up() && this.is_xlarge_up() && this.is_xxlarge_up();
+ }
+ }
+ };
+
+ $.fn.foundation = function () {
+ var args = Array.prototype.slice.call(arguments, 0);
+
+ return this.each(function () {
+ Foundation.init.apply(Foundation, [this].concat(args));
+ return this;
+ });
+ };
+
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.magellan.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.magellan.js
new file mode 100644
index 00000000..d8e1ebfa
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.magellan.js
@@ -0,0 +1,203 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs['magellan-expedition'] = {
+ name : 'magellan-expedition',
+
+ version : '5.5.1',
+
+ settings : {
+ active_class : 'active',
+ threshold : 0, // pixels from the top of the expedition for it to become fixes
+ destination_threshold : 20, // pixels from the top of destination for it to be considered active
+ throttle_delay : 30, // calculation throttling to increase framerate
+ fixed_top : 0, // top distance in pixels assigend to the fixed element on scroll
+ offset_by_height : true, // whether to offset the destination by the expedition height. Usually you want this to be true, unless your expedition is on the side.
+ duration : 700, // animation duration time
+ easing : 'swing' // animation easing
+ },
+
+ init : function (scope, method, options) {
+ Foundation.inherit(this, 'throttle');
+ this.bindings(method, options);
+ },
+
+ events : function () {
+ var self = this,
+ S = self.S,
+ settings = self.settings;
+
+ // initialize expedition offset
+ self.set_expedition_position();
+
+ S(self.scope)
+ .off('.magellan')
+ .on('click.fndtn.magellan', '[' + self.add_namespace('data-magellan-arrival') + '] a[href^="#"]', function (e) {
+ e.preventDefault();
+ var expedition = $(this).closest('[' + self.attr_name() + ']'),
+ settings = expedition.data('magellan-expedition-init'),
+ hash = this.hash.split('#').join(''),
+ target = $('a[name="' + hash + '"]');
+
+ if (target.length === 0) {
+ target = $('#' + hash);
+
+ }
+
+ // Account for expedition height if fixed position
+ var scroll_top = target.offset().top - settings.destination_threshold + 1;
+ if (settings.offset_by_height) {
+ scroll_top = scroll_top - expedition.outerHeight();
+ }
+
+ $('html, body').stop().animate({
+ 'scrollTop' : scroll_top
+ }, settings.duration, settings.easing, function () {
+ if (history.pushState) {
+ history.pushState(null, null, '#' + hash);
+ } else {
+ location.hash = '#' + hash;
+ }
+ });
+ })
+ .on('scroll.fndtn.magellan', self.throttle(this.check_for_arrivals.bind(this), settings.throttle_delay));
+
+ $(window)
+ .on('resize.fndtn.magellan', self.throttle(this.set_expedition_position.bind(this), settings.throttle_delay));
+ },
+
+ check_for_arrivals : function () {
+ var self = this;
+ self.update_arrivals();
+ self.update_expedition_positions();
+ },
+
+ set_expedition_position : function () {
+ var self = this;
+ $('[' + this.attr_name() + '=fixed]', self.scope).each(function (idx, el) {
+ var expedition = $(this),
+ settings = expedition.data('magellan-expedition-init'),
+ styles = expedition.attr('styles'), // save styles
+ top_offset, fixed_top;
+
+ expedition.attr('style', '');
+ top_offset = expedition.offset().top + settings.threshold;
+
+ //set fixed-top by attribute
+ fixed_top = parseInt(expedition.data('magellan-fixed-top'));
+ if (!isNaN(fixed_top)) {
+ self.settings.fixed_top = fixed_top;
+ }
+
+ expedition.data(self.data_attr('magellan-top-offset'), top_offset);
+ expedition.attr('style', styles);
+ });
+ },
+
+ update_expedition_positions : function () {
+ var self = this,
+ window_top_offset = $(window).scrollTop();
+
+ $('[' + this.attr_name() + '=fixed]', self.scope).each(function () {
+ var expedition = $(this),
+ settings = expedition.data('magellan-expedition-init'),
+ styles = expedition.attr('style'), // save styles
+ top_offset = expedition.data('magellan-top-offset');
+
+ //scroll to the top distance
+ if (window_top_offset + self.settings.fixed_top >= top_offset) {
+ // Placeholder allows height calculations to be consistent even when
+ // appearing to switch between fixed/non-fixed placement
+ var placeholder = expedition.prev('[' + self.add_namespace('data-magellan-expedition-clone') + ']');
+ if (placeholder.length === 0) {
+ placeholder = expedition.clone();
+ placeholder.removeAttr(self.attr_name());
+ placeholder.attr(self.add_namespace('data-magellan-expedition-clone'), '');
+ expedition.before(placeholder);
+ }
+ expedition.css({position :'fixed', top : settings.fixed_top}).addClass('fixed');
+ } else {
+ expedition.prev('[' + self.add_namespace('data-magellan-expedition-clone') + ']').remove();
+ expedition.attr('style', styles).css('position', '').css('top', '').removeClass('fixed');
+ }
+ });
+ },
+
+ update_arrivals : function () {
+ var self = this,
+ window_top_offset = $(window).scrollTop();
+
+ $('[' + this.attr_name() + ']', self.scope).each(function () {
+ var expedition = $(this),
+ settings = expedition.data(self.attr_name(true) + '-init'),
+ offsets = self.offsets(expedition, window_top_offset),
+ arrivals = expedition.find('[' + self.add_namespace('data-magellan-arrival') + ']'),
+ active_item = false;
+ offsets.each(function (idx, item) {
+ if (item.viewport_offset >= item.top_offset) {
+ var arrivals = expedition.find('[' + self.add_namespace('data-magellan-arrival') + ']');
+ arrivals.not(item.arrival).removeClass(settings.active_class);
+ item.arrival.addClass(settings.active_class);
+ active_item = true;
+ return true;
+ }
+ });
+
+ if (!active_item) {
+ arrivals.removeClass(settings.active_class);
+ }
+ });
+ },
+
+ offsets : function (expedition, window_offset) {
+ var self = this,
+ settings = expedition.data(self.attr_name(true) + '-init'),
+ viewport_offset = window_offset;
+
+ return expedition.find('[' + self.add_namespace('data-magellan-arrival') + ']').map(function (idx, el) {
+ var name = $(this).data(self.data_attr('magellan-arrival')),
+ dest = $('[' + self.add_namespace('data-magellan-destination') + '=' + name + ']');
+ if (dest.length > 0) {
+ var top_offset = dest.offset().top - settings.destination_threshold;
+ if (settings.offset_by_height) {
+ top_offset = top_offset - expedition.outerHeight();
+ }
+ top_offset = Math.floor(top_offset);
+ return {
+ destination : dest,
+ arrival : $(this),
+ top_offset : top_offset,
+ viewport_offset : viewport_offset
+ }
+ }
+ }).sort(function (a, b) {
+ if (a.top_offset < b.top_offset) {
+ return -1;
+ }
+ if (a.top_offset > b.top_offset) {
+ return 1;
+ }
+ return 0;
+ });
+ },
+
+ data_attr : function (str) {
+ if (this.namespace.length > 0) {
+ return this.namespace + '-' + str;
+ }
+
+ return str;
+ },
+
+ off : function () {
+ this.S(this.scope).off('.magellan');
+ this.S(window).off('.magellan');
+ },
+
+ reflow : function () {
+ var self = this;
+ // remove placeholder expeditions used for height calculation purposes
+ $('[' + self.add_namespace('data-magellan-expedition-clone') + ']', self.scope).remove();
+ }
+ };
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.offcanvas.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.offcanvas.js
new file mode 100644
index 00000000..51ce3530
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.offcanvas.js
@@ -0,0 +1,152 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.offcanvas = {
+ name : 'offcanvas',
+
+ version : '5.5.1',
+
+ settings : {
+ open_method : 'move',
+ close_on_click : false
+ },
+
+ init : function (scope, method, options) {
+ this.bindings(method, options);
+ },
+
+ events : function () {
+ var self = this,
+ S = self.S,
+ move_class = '',
+ right_postfix = '',
+ left_postfix = '';
+
+ if (this.settings.open_method === 'move') {
+ move_class = 'move-';
+ right_postfix = 'right';
+ left_postfix = 'left';
+ } else if (this.settings.open_method === 'overlap_single') {
+ move_class = 'offcanvas-overlap-';
+ right_postfix = 'right';
+ left_postfix = 'left';
+ } else if (this.settings.open_method === 'overlap') {
+ move_class = 'offcanvas-overlap';
+ }
+
+ S(this.scope).off('.offcanvas')
+ .on('click.fndtn.offcanvas', '.left-off-canvas-toggle', function (e) {
+ self.click_toggle_class(e, move_class + right_postfix);
+ if (self.settings.open_method !== 'overlap') {
+ S('.left-submenu').removeClass(move_class + right_postfix);
+ }
+ $('.left-off-canvas-toggle').attr('aria-expanded', 'true');
+ })
+ .on('click.fndtn.offcanvas', '.left-off-canvas-menu a', function (e) {
+ var settings = self.get_settings(e);
+ var parent = S(this).parent();
+
+ if (settings.close_on_click && !parent.hasClass('has-submenu') && !parent.hasClass('back')) {
+ self.hide.call(self, move_class + right_postfix, self.get_wrapper(e));
+ parent.parent().removeClass(move_class + right_postfix);
+ } else if (S(this).parent().hasClass('has-submenu')) {
+ e.preventDefault();
+ S(this).siblings('.left-submenu').toggleClass(move_class + right_postfix);
+ } else if (parent.hasClass('back')) {
+ e.preventDefault();
+ parent.parent().removeClass(move_class + right_postfix);
+ }
+ $('.left-off-canvas-toggle').attr('aria-expanded', 'true');
+ })
+ .on('click.fndtn.offcanvas', '.right-off-canvas-toggle', function (e) {
+ self.click_toggle_class(e, move_class + left_postfix);
+ if (self.settings.open_method !== 'overlap') {
+ S('.right-submenu').removeClass(move_class + left_postfix);
+ }
+ $('.right-off-canvas-toggle').attr('aria-expanded', 'true');
+ })
+ .on('click.fndtn.offcanvas', '.right-off-canvas-menu a', function (e) {
+ var settings = self.get_settings(e);
+ var parent = S(this).parent();
+
+ if (settings.close_on_click && !parent.hasClass('has-submenu') && !parent.hasClass('back')) {
+ self.hide.call(self, move_class + left_postfix, self.get_wrapper(e));
+ parent.parent().removeClass(move_class + left_postfix);
+ } else if (S(this).parent().hasClass('has-submenu')) {
+ e.preventDefault();
+ S(this).siblings('.right-submenu').toggleClass(move_class + left_postfix);
+ } else if (parent.hasClass('back')) {
+ e.preventDefault();
+ parent.parent().removeClass(move_class + left_postfix);
+ }
+ $('.right-off-canvas-toggle').attr('aria-expanded', 'true');
+ })
+ .on('click.fndtn.offcanvas', '.exit-off-canvas', function (e) {
+ self.click_remove_class(e, move_class + left_postfix);
+ S('.right-submenu').removeClass(move_class + left_postfix);
+ if (right_postfix) {
+ self.click_remove_class(e, move_class + right_postfix);
+ S('.left-submenu').removeClass(move_class + left_postfix);
+ }
+ $('.right-off-canvas-toggle').attr('aria-expanded', 'true');
+ })
+ .on('click.fndtn.offcanvas', '.exit-off-canvas', function (e) {
+ self.click_remove_class(e, move_class + left_postfix);
+ $('.left-off-canvas-toggle').attr('aria-expanded', 'false');
+ if (right_postfix) {
+ self.click_remove_class(e, move_class + right_postfix);
+ $('.right-off-canvas-toggle').attr('aria-expanded', 'false');
+ }
+ });
+ },
+
+ toggle : function (class_name, $off_canvas) {
+ $off_canvas = $off_canvas || this.get_wrapper();
+ if ($off_canvas.is('.' + class_name)) {
+ this.hide(class_name, $off_canvas);
+ } else {
+ this.show(class_name, $off_canvas);
+ }
+ },
+
+ show : function (class_name, $off_canvas) {
+ $off_canvas = $off_canvas || this.get_wrapper();
+ $off_canvas.trigger('open').trigger('open.fndtn.offcanvas');
+ $off_canvas.addClass(class_name);
+ },
+
+ hide : function (class_name, $off_canvas) {
+ $off_canvas = $off_canvas || this.get_wrapper();
+ $off_canvas.trigger('close').trigger('close.fndtn.offcanvas');
+ $off_canvas.removeClass(class_name);
+ },
+
+ click_toggle_class : function (e, class_name) {
+ e.preventDefault();
+ var $off_canvas = this.get_wrapper(e);
+ this.toggle(class_name, $off_canvas);
+ },
+
+ click_remove_class : function (e, class_name) {
+ e.preventDefault();
+ var $off_canvas = this.get_wrapper(e);
+ this.hide(class_name, $off_canvas);
+ },
+
+ get_settings : function (e) {
+ var offcanvas = this.S(e.target).closest('[' + this.attr_name() + ']');
+ return offcanvas.data(this.attr_name(true) + '-init') || this.settings;
+ },
+
+ get_wrapper : function (e) {
+ var $off_canvas = this.S(e ? e.target : this.scope).closest('.off-canvas-wrap');
+
+ if ($off_canvas.length === 0) {
+ $off_canvas = this.S('.off-canvas-wrap');
+ }
+ return $off_canvas;
+ },
+
+ reflow : function () {}
+ };
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.orbit.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.orbit.js
new file mode 100644
index 00000000..fb03f3d9
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.orbit.js
@@ -0,0 +1,476 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ var noop = function () {};
+
+ var Orbit = function (el, settings) {
+ // Don't reinitialize plugin
+ if (el.hasClass(settings.slides_container_class)) {
+ return this;
+ }
+
+ var self = this,
+ container,
+ slides_container = el,
+ number_container,
+ bullets_container,
+ timer_container,
+ idx = 0,
+ animate,
+ timer,
+ locked = false,
+ adjust_height_after = false;
+
+ self.slides = function () {
+ return slides_container.children(settings.slide_selector);
+ };
+
+ self.slides().first().addClass(settings.active_slide_class);
+
+ self.update_slide_number = function (index) {
+ if (settings.slide_number) {
+ number_container.find('span:first').text(parseInt(index) + 1);
+ number_container.find('span:last').text(self.slides().length);
+ }
+ if (settings.bullets) {
+ bullets_container.children().removeClass(settings.bullets_active_class);
+ $(bullets_container.children().get(index)).addClass(settings.bullets_active_class);
+ }
+ };
+
+ self.update_active_link = function (index) {
+ var link = $('[data-orbit-link="' + self.slides().eq(index).attr('data-orbit-slide') + '"]');
+ link.siblings().removeClass(settings.bullets_active_class);
+ link.addClass(settings.bullets_active_class);
+ };
+
+ self.build_markup = function () {
+ slides_container.wrap('
');
+ container = slides_container.parent();
+ slides_container.addClass(settings.slides_container_class);
+
+ if (settings.stack_on_small) {
+ container.addClass(settings.stack_on_small_class);
+ }
+
+ if (settings.navigation_arrows) {
+ container.append($(' ').addClass(settings.prev_class));
+ container.append($(' ').addClass(settings.next_class));
+ }
+
+ if (settings.timer) {
+ timer_container = $('').addClass(settings.timer_container_class);
+ timer_container.append('
');
+ timer_container.append($('').addClass(settings.timer_progress_class));
+ timer_container.addClass(settings.timer_paused_class);
+ container.append(timer_container);
+ }
+
+ if (settings.slide_number) {
+ number_container = $('
').addClass(settings.slide_number_class);
+ number_container.append('
' + settings.slide_number_text + '
');
+ container.append(number_container);
+ }
+
+ if (settings.bullets) {
+ bullets_container = $('
').addClass(settings.bullets_container_class);
+ container.append(bullets_container);
+ bullets_container.wrap('
');
+ self.slides().each(function (idx, el) {
+ var bullet = $('').attr('data-orbit-slide', idx).on('click', self.link_bullet);;
+ bullets_container.append(bullet);
+ });
+ }
+
+ };
+
+ self._goto = function (next_idx, start_timer) {
+ // if (locked) {return false;}
+ if (next_idx === idx) {return false;}
+ if (typeof timer === 'object') {timer.restart();}
+ var slides = self.slides();
+
+ var dir = 'next';
+ locked = true;
+ if (next_idx < idx) {dir = 'prev';}
+ if (next_idx >= slides.length) {
+ if (!settings.circular) {
+ return false;
+ }
+ next_idx = 0;
+ } else if (next_idx < 0) {
+ if (!settings.circular) {
+ return false;
+ }
+ next_idx = slides.length - 1;
+ }
+
+ var current = $(slides.get(idx));
+ var next = $(slides.get(next_idx));
+
+ current.css('zIndex', 2);
+ current.removeClass(settings.active_slide_class);
+ next.css('zIndex', 4).addClass(settings.active_slide_class);
+
+ slides_container.trigger('before-slide-change.fndtn.orbit');
+ settings.before_slide_change();
+ self.update_active_link(next_idx);
+
+ var callback = function () {
+ var unlock = function () {
+ idx = next_idx;
+ locked = false;
+ if (start_timer === true) {timer = self.create_timer(); timer.start();}
+ self.update_slide_number(idx);
+ slides_container.trigger('after-slide-change.fndtn.orbit', [{slide_number : idx, total_slides : slides.length}]);
+ settings.after_slide_change(idx, slides.length);
+ };
+ if (slides_container.outerHeight() != next.outerHeight() && settings.variable_height) {
+ slides_container.animate({'height': next.outerHeight()}, 250, 'linear', unlock);
+ } else {
+ unlock();
+ }
+ };
+
+ if (slides.length === 1) {callback(); return false;}
+
+ var start_animation = function () {
+ if (dir === 'next') {animate.next(current, next, callback);}
+ if (dir === 'prev') {animate.prev(current, next, callback);}
+ };
+
+ if (next.outerHeight() > slides_container.outerHeight() && settings.variable_height) {
+ slides_container.animate({'height': next.outerHeight()}, 250, 'linear', start_animation);
+ } else {
+ start_animation();
+ }
+ };
+
+ self.next = function (e) {
+ e.stopImmediatePropagation();
+ e.preventDefault();
+ self._goto(idx + 1);
+ };
+
+ self.prev = function (e) {
+ e.stopImmediatePropagation();
+ e.preventDefault();
+ self._goto(idx - 1);
+ };
+
+ self.link_custom = function (e) {
+ e.preventDefault();
+ var link = $(this).attr('data-orbit-link');
+ if ((typeof link === 'string') && (link = $.trim(link)) != '') {
+ var slide = container.find('[data-orbit-slide=' + link + ']');
+ if (slide.index() != -1) {self._goto(slide.index());}
+ }
+ };
+
+ self.link_bullet = function (e) {
+ var index = $(this).attr('data-orbit-slide');
+ if ((typeof index === 'string') && (index = $.trim(index)) != '') {
+ if (isNaN(parseInt(index))) {
+ var slide = container.find('[data-orbit-slide=' + index + ']');
+ if (slide.index() != -1) {self._goto(slide.index() + 1);}
+ } else {
+ self._goto(parseInt(index));
+ }
+ }
+
+ }
+
+ self.timer_callback = function () {
+ self._goto(idx + 1, true);
+ }
+
+ self.compute_dimensions = function () {
+ var current = $(self.slides().get(idx));
+ var h = current.outerHeight();
+ if (!settings.variable_height) {
+ self.slides().each(function(){
+ if ($(this).outerHeight() > h) { h = $(this).outerHeight(); }
+ });
+ }
+ slides_container.height(h);
+ };
+
+ self.create_timer = function () {
+ var t = new Timer(
+ container.find('.' + settings.timer_container_class),
+ settings,
+ self.timer_callback
+ );
+ return t;
+ };
+
+ self.stop_timer = function () {
+ if (typeof timer === 'object') {
+ timer.stop();
+ }
+ };
+
+ self.toggle_timer = function () {
+ var t = container.find('.' + settings.timer_container_class);
+ if (t.hasClass(settings.timer_paused_class)) {
+ if (typeof timer === 'undefined') {timer = self.create_timer();}
+ timer.start();
+ } else {
+ if (typeof timer === 'object') {timer.stop();}
+ }
+ };
+
+ self.init = function () {
+ self.build_markup();
+ if (settings.timer) {
+ timer = self.create_timer();
+ Foundation.utils.image_loaded(this.slides().children('img'), timer.start);
+ }
+ animate = new FadeAnimation(settings, slides_container);
+ if (settings.animation === 'slide') {
+ animate = new SlideAnimation(settings, slides_container);
+ }
+
+ container.on('click', '.' + settings.next_class, self.next);
+ container.on('click', '.' + settings.prev_class, self.prev);
+
+ if (settings.next_on_click) {
+ container.on('click', '.' + settings.slides_container_class + ' [data-orbit-slide]', self.link_bullet);
+ }
+
+ container.on('click', self.toggle_timer);
+ if (settings.swipe) {
+ container.on('touchstart.fndtn.orbit', function (e) {
+ if (!e.touches) {e = e.originalEvent;}
+ var data = {
+ start_page_x : e.touches[0].pageX,
+ start_page_y : e.touches[0].pageY,
+ start_time : (new Date()).getTime(),
+ delta_x : 0,
+ is_scrolling : undefined
+ };
+ container.data('swipe-transition', data);
+ e.stopPropagation();
+ })
+ .on('touchmove.fndtn.orbit', function (e) {
+ if (!e.touches) {
+ e = e.originalEvent;
+ }
+ // Ignore pinch/zoom events
+ if (e.touches.length > 1 || e.scale && e.scale !== 1) {
+ return;
+ }
+
+ var data = container.data('swipe-transition');
+ if (typeof data === 'undefined') {data = {};}
+
+ data.delta_x = e.touches[0].pageX - data.start_page_x;
+
+ if ( typeof data.is_scrolling === 'undefined') {
+ data.is_scrolling = !!( data.is_scrolling || Math.abs(data.delta_x) < Math.abs(e.touches[0].pageY - data.start_page_y) );
+ }
+
+ if (!data.is_scrolling && !data.active) {
+ e.preventDefault();
+ var direction = (data.delta_x < 0) ? (idx + 1) : (idx - 1);
+ data.active = true;
+ self._goto(direction);
+ }
+ })
+ .on('touchend.fndtn.orbit', function (e) {
+ container.data('swipe-transition', {});
+ e.stopPropagation();
+ })
+ }
+ container.on('mouseenter.fndtn.orbit', function (e) {
+ if (settings.timer && settings.pause_on_hover) {
+ self.stop_timer();
+ }
+ })
+ .on('mouseleave.fndtn.orbit', function (e) {
+ if (settings.timer && settings.resume_on_mouseout) {
+ timer.start();
+ }
+ });
+
+ $(document).on('click', '[data-orbit-link]', self.link_custom);
+ $(window).on('load resize', self.compute_dimensions);
+ Foundation.utils.image_loaded(this.slides().children('img'), self.compute_dimensions);
+ Foundation.utils.image_loaded(this.slides().children('img'), function () {
+ container.prev('.' + settings.preloader_class).css('display', 'none');
+ self.update_slide_number(0);
+ self.update_active_link(0);
+ slides_container.trigger('ready.fndtn.orbit');
+ });
+ };
+
+ self.init();
+ };
+
+ var Timer = function (el, settings, callback) {
+ var self = this,
+ duration = settings.timer_speed,
+ progress = el.find('.' + settings.timer_progress_class),
+ start,
+ timeout,
+ left = -1;
+
+ this.update_progress = function (w) {
+ var new_progress = progress.clone();
+ new_progress.attr('style', '');
+ new_progress.css('width', w + '%');
+ progress.replaceWith(new_progress);
+ progress = new_progress;
+ };
+
+ this.restart = function () {
+ clearTimeout(timeout);
+ el.addClass(settings.timer_paused_class);
+ left = -1;
+ self.update_progress(0);
+ };
+
+ this.start = function () {
+ if (!el.hasClass(settings.timer_paused_class)) {return true;}
+ left = (left === -1) ? duration : left;
+ el.removeClass(settings.timer_paused_class);
+ start = new Date().getTime();
+ progress.animate({'width' : '100%'}, left, 'linear');
+ timeout = setTimeout(function () {
+ self.restart();
+ callback();
+ }, left);
+ el.trigger('timer-started.fndtn.orbit')
+ };
+
+ this.stop = function () {
+ if (el.hasClass(settings.timer_paused_class)) {return true;}
+ clearTimeout(timeout);
+ el.addClass(settings.timer_paused_class);
+ var end = new Date().getTime();
+ left = left - (end - start);
+ var w = 100 - ((left / duration) * 100);
+ self.update_progress(w);
+ el.trigger('timer-stopped.fndtn.orbit');
+ };
+ };
+
+ var SlideAnimation = function (settings, container) {
+ var duration = settings.animation_speed;
+ var is_rtl = ($('html[dir=rtl]').length === 1);
+ var margin = is_rtl ? 'marginRight' : 'marginLeft';
+ var animMargin = {};
+ animMargin[margin] = '0%';
+
+ this.next = function (current, next, callback) {
+ current.animate({marginLeft : '-100%'}, duration);
+ next.animate(animMargin, duration, function () {
+ current.css(margin, '100%');
+ callback();
+ });
+ };
+
+ this.prev = function (current, prev, callback) {
+ current.animate({marginLeft : '100%'}, duration);
+ prev.css(margin, '-100%');
+ prev.animate(animMargin, duration, function () {
+ current.css(margin, '100%');
+ callback();
+ });
+ };
+ };
+
+ var FadeAnimation = function (settings, container) {
+ var duration = settings.animation_speed;
+ var is_rtl = ($('html[dir=rtl]').length === 1);
+ var margin = is_rtl ? 'marginRight' : 'marginLeft';
+
+ this.next = function (current, next, callback) {
+ next.css({'margin' : '0%', 'opacity' : '0.01'});
+ next.animate({'opacity' :'1'}, duration, 'linear', function () {
+ current.css('margin', '100%');
+ callback();
+ });
+ };
+
+ this.prev = function (current, prev, callback) {
+ prev.css({'margin' : '0%', 'opacity' : '0.01'});
+ prev.animate({'opacity' : '1'}, duration, 'linear', function () {
+ current.css('margin', '100%');
+ callback();
+ });
+ };
+ };
+
+ Foundation.libs = Foundation.libs || {};
+
+ Foundation.libs.orbit = {
+ name : 'orbit',
+
+ version : '5.5.1',
+
+ settings : {
+ animation : 'slide',
+ timer_speed : 10000,
+ pause_on_hover : true,
+ resume_on_mouseout : false,
+ next_on_click : true,
+ animation_speed : 500,
+ stack_on_small : false,
+ navigation_arrows : true,
+ slide_number : true,
+ slide_number_text : 'of',
+ container_class : 'orbit-container',
+ stack_on_small_class : 'orbit-stack-on-small',
+ next_class : 'orbit-next',
+ prev_class : 'orbit-prev',
+ timer_container_class : 'orbit-timer',
+ timer_paused_class : 'paused',
+ timer_progress_class : 'orbit-progress',
+ slides_container_class : 'orbit-slides-container',
+ preloader_class : 'preloader',
+ slide_selector : '*',
+ bullets_container_class : 'orbit-bullets',
+ bullets_active_class : 'active',
+ slide_number_class : 'orbit-slide-number',
+ caption_class : 'orbit-caption',
+ active_slide_class : 'active',
+ orbit_transition_class : 'orbit-transitioning',
+ bullets : true,
+ circular : true,
+ timer : true,
+ variable_height : false,
+ swipe : true,
+ before_slide_change : noop,
+ after_slide_change : noop
+ },
+
+ init : function (scope, method, options) {
+ var self = this;
+ this.bindings(method, options);
+ },
+
+ events : function (instance) {
+ var orbit_instance = new Orbit(this.S(instance), this.S(instance).data('orbit-init'));
+ this.S(instance).data(this.name + '-instance', orbit_instance);
+ },
+
+ reflow : function () {
+ var self = this;
+
+ if (self.S(self.scope).is('[data-orbit]')) {
+ var $el = self.S(self.scope);
+ var instance = $el.data(self.name + '-instance');
+ instance.compute_dimensions();
+ } else {
+ self.S('[data-orbit]', self.scope).each(function (idx, el) {
+ var $el = self.S(el);
+ var opts = self.data_options($el);
+ var instance = $el.data(self.name + '-instance');
+ instance.compute_dimensions();
+ });
+ }
+ }
+ };
+
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.reveal.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.reveal.js
new file mode 100644
index 00000000..c4b95d76
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.reveal.js
@@ -0,0 +1,471 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.reveal = {
+ name : 'reveal',
+
+ version : '5.5.1',
+
+ locked : false,
+
+ settings : {
+ animation : 'fadeAndPop',
+ animation_speed : 250,
+ close_on_background_click : true,
+ close_on_esc : true,
+ dismiss_modal_class : 'close-reveal-modal',
+ multiple_opened : false,
+ bg_class : 'reveal-modal-bg',
+ root_element : 'body',
+ open : function(){},
+ opened : function(){},
+ close : function(){},
+ closed : function(){},
+ bg : $('.reveal-modal-bg'),
+ css : {
+ open : {
+ 'opacity' : 0,
+ 'visibility' : 'visible',
+ 'display' : 'block'
+ },
+ close : {
+ 'opacity' : 1,
+ 'visibility' : 'hidden',
+ 'display' : 'none'
+ }
+ }
+ },
+
+ init : function (scope, method, options) {
+ $.extend(true, this.settings, method, options);
+ this.bindings(method, options);
+ },
+
+ events : function (scope) {
+ var self = this,
+ S = self.S;
+
+ S(this.scope)
+ .off('.reveal')
+ .on('click.fndtn.reveal', '[' + this.add_namespace('data-reveal-id') + ']:not([disabled])', function (e) {
+ e.preventDefault();
+
+ if (!self.locked) {
+ var element = S(this),
+ ajax = element.data(self.data_attr('reveal-ajax'));
+
+ self.locked = true;
+
+ if (typeof ajax === 'undefined') {
+ self.open.call(self, element);
+ } else {
+ var url = ajax === true ? element.attr('href') : ajax;
+
+ self.open.call(self, element, {url : url});
+ }
+ }
+ });
+
+ S(document)
+ .on('click.fndtn.reveal', this.close_targets(), function (e) {
+ e.preventDefault();
+ if (!self.locked) {
+ var settings = S('[' + self.attr_name() + '].open').data(self.attr_name(true) + '-init') || self.settings,
+ bg_clicked = S(e.target)[0] === S('.' + settings.bg_class)[0];
+
+ if (bg_clicked) {
+ if (settings.close_on_background_click) {
+ e.stopPropagation();
+ } else {
+ return;
+ }
+ }
+
+ self.locked = true;
+ self.close.call(self, bg_clicked ? S('[' + self.attr_name() + '].open') : S(this).closest('[' + self.attr_name() + ']'));
+ }
+ });
+
+ if (S('[' + self.attr_name() + ']', this.scope).length > 0) {
+ S(this.scope)
+ // .off('.reveal')
+ .on('open.fndtn.reveal', this.settings.open)
+ .on('opened.fndtn.reveal', this.settings.opened)
+ .on('opened.fndtn.reveal', this.open_video)
+ .on('close.fndtn.reveal', this.settings.close)
+ .on('closed.fndtn.reveal', this.settings.closed)
+ .on('closed.fndtn.reveal', this.close_video);
+ } else {
+ S(this.scope)
+ // .off('.reveal')
+ .on('open.fndtn.reveal', '[' + self.attr_name() + ']', this.settings.open)
+ .on('opened.fndtn.reveal', '[' + self.attr_name() + ']', this.settings.opened)
+ .on('opened.fndtn.reveal', '[' + self.attr_name() + ']', this.open_video)
+ .on('close.fndtn.reveal', '[' + self.attr_name() + ']', this.settings.close)
+ .on('closed.fndtn.reveal', '[' + self.attr_name() + ']', this.settings.closed)
+ .on('closed.fndtn.reveal', '[' + self.attr_name() + ']', this.close_video);
+ }
+
+ return true;
+ },
+
+ // PATCH #3: turning on key up capture only when a reveal window is open
+ key_up_on : function (scope) {
+ var self = this;
+
+ // PATCH #1: fixing multiple keyup event trigger from single key press
+ self.S('body').off('keyup.fndtn.reveal').on('keyup.fndtn.reveal', function ( event ) {
+ var open_modal = self.S('[' + self.attr_name() + '].open'),
+ settings = open_modal.data(self.attr_name(true) + '-init') || self.settings ;
+ // PATCH #2: making sure that the close event can be called only while unlocked,
+ // so that multiple keyup.fndtn.reveal events don't prevent clean closing of the reveal window.
+ if ( settings && event.which === 27 && settings.close_on_esc && !self.locked) { // 27 is the keycode for the Escape key
+ self.close.call(self, open_modal);
+ }
+ });
+
+ return true;
+ },
+
+ // PATCH #3: turning on key up capture only when a reveal window is open
+ key_up_off : function (scope) {
+ this.S('body').off('keyup.fndtn.reveal');
+ return true;
+ },
+
+ open : function (target, ajax_settings) {
+ var self = this,
+ modal;
+
+ if (target) {
+ if (typeof target.selector !== 'undefined') {
+ // Find the named node; only use the first one found, since the rest of the code assumes there's only one node
+ modal = self.S('#' + target.data(self.data_attr('reveal-id'))).first();
+ } else {
+ modal = self.S(this.scope);
+
+ ajax_settings = target;
+ }
+ } else {
+ modal = self.S(this.scope);
+ }
+
+ var settings = modal.data(self.attr_name(true) + '-init');
+ settings = settings || this.settings;
+
+ if (modal.hasClass('open') && target.attr('data-reveal-id') == modal.attr('id')) {
+ return self.close(modal);
+ }
+
+ if (!modal.hasClass('open')) {
+ var open_modal = self.S('[' + self.attr_name() + '].open');
+
+ if (typeof modal.data('css-top') === 'undefined') {
+ modal.data('css-top', parseInt(modal.css('top'), 10))
+ .data('offset', this.cache_offset(modal));
+ }
+
+ this.key_up_on(modal); // PATCH #3: turning on key up capture only when a reveal window is open
+
+ modal.on('open.fndtn.reveal').trigger('open.fndtn.reveal');
+
+ if (open_modal.length < 1) {
+ this.toggle_bg(modal, true);
+ }
+
+ if (typeof ajax_settings === 'string') {
+ ajax_settings = {
+ url : ajax_settings
+ };
+ }
+
+ if (typeof ajax_settings === 'undefined' || !ajax_settings.url) {
+ if (open_modal.length > 0) {
+ if (settings.multiple_opened) {
+ this.to_back(open_modal);
+ } else {
+ this.hide(open_modal, settings.css.close);
+ }
+ }
+
+ this.show(modal, settings.css.open);
+ } else {
+ var old_success = typeof ajax_settings.success !== 'undefined' ? ajax_settings.success : null;
+
+ $.extend(ajax_settings, {
+ success : function (data, textStatus, jqXHR) {
+ if ( $.isFunction(old_success) ) {
+ var result = old_success(data, textStatus, jqXHR);
+ if (typeof result == 'string') {
+ data = result;
+ }
+ }
+
+ modal.html(data);
+ self.S(modal).foundation('section', 'reflow');
+ self.S(modal).children().foundation();
+
+ if (open_modal.length > 0) {
+ if (settings.multiple_opened) {
+ this.to_back(open_modal);
+ } else {
+ this.hide(open_modal, settings.css.close);
+ }
+ }
+ self.show(modal, settings.css.open);
+ }
+ });
+
+ $.ajax(ajax_settings);
+ }
+ }
+ self.S(window).trigger('resize');
+ },
+
+ close : function (modal) {
+ var modal = modal && modal.length ? modal : this.S(this.scope),
+ open_modals = this.S('[' + this.attr_name() + '].open'),
+ settings = modal.data(this.attr_name(true) + '-init') || this.settings;
+
+ if (open_modals.length > 0) {
+ this.locked = true;
+ this.key_up_off(modal); // PATCH #3: turning on key up capture only when a reveal window is open
+ modal.trigger('close').trigger('close.fndtn.reveal');
+
+ if ((settings.multiple_opened && open_modals.length === 1) || !settings.multiple_opened || modal.length > 1) {
+ this.toggle_bg(modal, false);
+ this.to_front(modal);
+ }
+
+ if (settings.multiple_opened) {
+ this.hide(modal, settings.css.close, settings);
+ this.to_front($($.makeArray(open_modals).reverse()[1]));
+ } else {
+ this.hide(open_modals, settings.css.close, settings);
+ }
+ }
+ },
+
+ close_targets : function () {
+ var base = '.' + this.settings.dismiss_modal_class;
+
+ if (this.settings.close_on_background_click) {
+ return base + ', .' + this.settings.bg_class;
+ }
+
+ return base;
+ },
+
+ toggle_bg : function (modal, state) {
+ if (this.S('.' + this.settings.bg_class).length === 0) {
+ this.settings.bg = $('
', {'class': this.settings.bg_class})
+ .appendTo('body').hide();
+ }
+
+ var visible = this.settings.bg.filter(':visible').length > 0;
+ if ( state != visible ) {
+ if ( state == undefined ? visible : !state ) {
+ this.hide(this.settings.bg);
+ } else {
+ this.show(this.settings.bg);
+ }
+ }
+ },
+
+ show : function (el, css) {
+ // is modal
+ if (css) {
+ var settings = el.data(this.attr_name(true) + '-init') || this.settings,
+ root_element = settings.root_element;
+
+ if (el.parent(root_element).length === 0) {
+ var placeholder = el.wrap('
').parent();
+
+ el.on('closed.fndtn.reveal.wrapped', function () {
+ el.detach().appendTo(placeholder);
+ el.unwrap().unbind('closed.fndtn.reveal.wrapped');
+ });
+
+ el.detach().appendTo(root_element);
+ }
+
+ var animData = getAnimationData(settings.animation);
+ if (!animData.animate) {
+ this.locked = false;
+ }
+ if (animData.pop) {
+ css.top = $(window).scrollTop() - el.data('offset') + 'px';
+ var end_css = {
+ top: $(window).scrollTop() + el.data('css-top') + 'px',
+ opacity: 1
+ };
+
+ return setTimeout(function () {
+ return el
+ .css(css)
+ .animate(end_css, settings.animation_speed, 'linear', function () {
+ this.locked = false;
+ el.trigger('opened').trigger('opened.fndtn.reveal');
+ }.bind(this))
+ .addClass('open');
+ }.bind(this), settings.animation_speed / 2);
+ }
+
+ if (animData.fade) {
+ css.top = $(window).scrollTop() + el.data('css-top') + 'px';
+ var end_css = {opacity: 1};
+
+ return setTimeout(function () {
+ return el
+ .css(css)
+ .animate(end_css, settings.animation_speed, 'linear', function () {
+ this.locked = false;
+ el.trigger('opened').trigger('opened.fndtn.reveal');
+ }.bind(this))
+ .addClass('open');
+ }.bind(this), settings.animation_speed / 2);
+ }
+
+ return el.css(css).show().css({opacity : 1}).addClass('open').trigger('opened').trigger('opened.fndtn.reveal');
+ }
+
+ var settings = this.settings;
+
+ // should we animate the background?
+ if (getAnimationData(settings.animation).fade) {
+ return el.fadeIn(settings.animation_speed / 2);
+ }
+
+ this.locked = false;
+
+ return el.show();
+ },
+
+ to_back : function(el) {
+ el.addClass('toback');
+ },
+
+ to_front : function(el) {
+ el.removeClass('toback');
+ },
+
+ hide : function (el, css) {
+ // is modal
+ if (css) {
+ var settings = el.data(this.attr_name(true) + '-init');
+ settings = settings || this.settings;
+
+ var animData = getAnimationData(settings.animation);
+ if (!animData.animate) {
+ this.locked = false;
+ }
+ if (animData.pop) {
+ var end_css = {
+ top: - $(window).scrollTop() - el.data('offset') + 'px',
+ opacity: 0
+ };
+
+ return setTimeout(function () {
+ return el
+ .animate(end_css, settings.animation_speed, 'linear', function () {
+ this.locked = false;
+ el.css(css).trigger('closed').trigger('closed.fndtn.reveal');
+ }.bind(this))
+ .removeClass('open');
+ }.bind(this), settings.animation_speed / 2);
+ }
+
+ if (animData.fade) {
+ var end_css = {opacity : 0};
+
+ return setTimeout(function () {
+ return el
+ .animate(end_css, settings.animation_speed, 'linear', function () {
+ this.locked = false;
+ el.css(css).trigger('closed').trigger('closed.fndtn.reveal');
+ }.bind(this))
+ .removeClass('open');
+ }.bind(this), settings.animation_speed / 2);
+ }
+
+ return el.hide().css(css).removeClass('open').trigger('closed').trigger('closed.fndtn.reveal');
+ }
+
+ var settings = this.settings;
+
+ // should we animate the background?
+ if (getAnimationData(settings.animation).fade) {
+ return el.fadeOut(settings.animation_speed / 2);
+ }
+
+ return el.hide();
+ },
+
+ close_video : function (e) {
+ var video = $('.flex-video', e.target),
+ iframe = $('iframe', video);
+
+ if (iframe.length > 0) {
+ iframe.attr('data-src', iframe[0].src);
+ iframe.attr('src', iframe.attr('src'));
+ video.hide();
+ }
+ },
+
+ open_video : function (e) {
+ var video = $('.flex-video', e.target),
+ iframe = video.find('iframe');
+
+ if (iframe.length > 0) {
+ var data_src = iframe.attr('data-src');
+ if (typeof data_src === 'string') {
+ iframe[0].src = iframe.attr('data-src');
+ } else {
+ var src = iframe[0].src;
+ iframe[0].src = undefined;
+ iframe[0].src = src;
+ }
+ video.show();
+ }
+ },
+
+ data_attr : function (str) {
+ if (this.namespace.length > 0) {
+ return this.namespace + '-' + str;
+ }
+
+ return str;
+ },
+
+ cache_offset : function (modal) {
+ var offset = modal.show().height() + parseInt(modal.css('top'), 10);
+
+ modal.hide();
+
+ return offset;
+ },
+
+ off : function () {
+ $(this.scope).off('.fndtn.reveal');
+ },
+
+ reflow : function () {}
+ };
+
+ /*
+ * getAnimationData('popAndFade') // {animate: true, pop: true, fade: true}
+ * getAnimationData('fade') // {animate: true, pop: false, fade: true}
+ * getAnimationData('pop') // {animate: true, pop: true, fade: false}
+ * getAnimationData('foo') // {animate: false, pop: false, fade: false}
+ * getAnimationData(null) // {animate: false, pop: false, fade: false}
+ */
+ function getAnimationData(str) {
+ var fade = /fade/i.test(str);
+ var pop = /pop/i.test(str);
+ return {
+ animate : fade || pop,
+ pop : pop,
+ fade : fade
+ };
+ }
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.slider.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.slider.js
new file mode 100644
index 00000000..4d069bc3
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.slider.js
@@ -0,0 +1,263 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.slider = {
+ name : 'slider',
+
+ version : '5.5.1',
+
+ settings : {
+ start : 0,
+ end : 100,
+ step : 1,
+ precision : null,
+ initial : null,
+ display_selector : '',
+ vertical : false,
+ trigger_input_change : false,
+ on_change : function () {}
+ },
+
+ cache : {},
+
+ init : function (scope, method, options) {
+ Foundation.inherit(this, 'throttle');
+ this.bindings(method, options);
+ this.reflow();
+ },
+
+ events : function () {
+ var self = this;
+
+ $(this.scope)
+ .off('.slider')
+ .on('mousedown.fndtn.slider touchstart.fndtn.slider pointerdown.fndtn.slider',
+ '[' + self.attr_name() + ']:not(.disabled, [disabled]) .range-slider-handle', function (e) {
+ if (!self.cache.active) {
+ e.preventDefault();
+ self.set_active_slider($(e.target));
+ }
+ })
+ .on('mousemove.fndtn.slider touchmove.fndtn.slider pointermove.fndtn.slider', function (e) {
+ if (!!self.cache.active) {
+ e.preventDefault();
+ if ($.data(self.cache.active[0], 'settings').vertical) {
+ var scroll_offset = 0;
+ if (!e.pageY) {
+ scroll_offset = window.scrollY;
+ }
+ self.calculate_position(self.cache.active, self.get_cursor_position(e, 'y') + scroll_offset);
+ } else {
+ self.calculate_position(self.cache.active, self.get_cursor_position(e, 'x'));
+ }
+ }
+ })
+ .on('mouseup.fndtn.slider touchend.fndtn.slider pointerup.fndtn.slider', function (e) {
+ self.remove_active_slider();
+ })
+ .on('change.fndtn.slider', function (e) {
+ self.settings.on_change();
+ });
+
+ self.S(window)
+ .on('resize.fndtn.slider', self.throttle(function (e) {
+ self.reflow();
+ }, 300));
+ },
+
+ get_cursor_position : function (e, xy) {
+ var pageXY = 'page' + xy.toUpperCase(),
+ clientXY = 'client' + xy.toUpperCase(),
+ position;
+
+ if (typeof e[pageXY] !== 'undefined') {
+ position = e[pageXY];
+ } else if (typeof e.originalEvent[clientXY] !== 'undefined') {
+ position = e.originalEvent[clientXY];
+ } else if (e.originalEvent.touches && e.originalEvent.touches[0] && typeof e.originalEvent.touches[0][clientXY] !== 'undefined') {
+ position = e.originalEvent.touches[0][clientXY];
+ } else if (e.currentPoint && typeof e.currentPoint[xy] !== 'undefined') {
+ position = e.currentPoint[xy];
+ }
+
+ return position;
+ },
+
+ set_active_slider : function ($handle) {
+ this.cache.active = $handle;
+ },
+
+ remove_active_slider : function () {
+ this.cache.active = null;
+ },
+
+ calculate_position : function ($handle, cursor_x) {
+ var self = this,
+ settings = $.data($handle[0], 'settings'),
+ handle_l = $.data($handle[0], 'handle_l'),
+ handle_o = $.data($handle[0], 'handle_o'),
+ bar_l = $.data($handle[0], 'bar_l'),
+ bar_o = $.data($handle[0], 'bar_o');
+
+ requestAnimationFrame(function () {
+ var pct;
+
+ if (Foundation.rtl && !settings.vertical) {
+ pct = self.limit_to(((bar_o + bar_l - cursor_x) / bar_l), 0, 1);
+ } else {
+ pct = self.limit_to(((cursor_x - bar_o) / bar_l), 0, 1);
+ }
+
+ pct = settings.vertical ? 1 - pct : pct;
+
+ var norm = self.normalized_value(pct, settings.start, settings.end, settings.step, settings.precision);
+
+ self.set_ui($handle, norm);
+ });
+ },
+
+ set_ui : function ($handle, value) {
+ var settings = $.data($handle[0], 'settings'),
+ handle_l = $.data($handle[0], 'handle_l'),
+ bar_l = $.data($handle[0], 'bar_l'),
+ norm_pct = this.normalized_percentage(value, settings.start, settings.end),
+ handle_offset = norm_pct * (bar_l - handle_l) - 1,
+ progress_bar_length = norm_pct * 100,
+ $handle_parent = $handle.parent(),
+ $hidden_inputs = $handle.parent().children('input[type=hidden]');
+
+ if (Foundation.rtl && !settings.vertical) {
+ handle_offset = -handle_offset;
+ }
+
+ handle_offset = settings.vertical ? -handle_offset + bar_l - handle_l + 1 : handle_offset;
+ this.set_translate($handle, handle_offset, settings.vertical);
+
+ if (settings.vertical) {
+ $handle.siblings('.range-slider-active-segment').css('height', progress_bar_length + '%');
+ } else {
+ $handle.siblings('.range-slider-active-segment').css('width', progress_bar_length + '%');
+ }
+
+ $handle_parent.attr(this.attr_name(), value).trigger('change').trigger('change.fndtn.slider');
+
+ $hidden_inputs.val(value);
+ if (settings.trigger_input_change) {
+ $hidden_inputs.trigger('change');
+ }
+
+ if (!$handle[0].hasAttribute('aria-valuemin')) {
+ $handle.attr({
+ 'aria-valuemin' : settings.start,
+ 'aria-valuemax' : settings.end
+ });
+ }
+ $handle.attr('aria-valuenow', value);
+
+ if (settings.display_selector != '') {
+ $(settings.display_selector).each(function () {
+ if (this.hasOwnProperty('value')) {
+ $(this).val(value);
+ } else {
+ $(this).text(value);
+ }
+ });
+ }
+
+ },
+
+ normalized_percentage : function (val, start, end) {
+ return Math.min(1, (val - start) / (end - start));
+ },
+
+ normalized_value : function (val, start, end, step, precision) {
+ var range = end - start,
+ point = val * range,
+ mod = (point - (point % step)) / step,
+ rem = point % step,
+ round = ( rem >= step * 0.5 ? step : 0);
+ return ((mod * step + round) + start).toFixed(precision);
+ },
+
+ set_translate : function (ele, offset, vertical) {
+ if (vertical) {
+ $(ele)
+ .css('-webkit-transform', 'translateY(' + offset + 'px)')
+ .css('-moz-transform', 'translateY(' + offset + 'px)')
+ .css('-ms-transform', 'translateY(' + offset + 'px)')
+ .css('-o-transform', 'translateY(' + offset + 'px)')
+ .css('transform', 'translateY(' + offset + 'px)');
+ } else {
+ $(ele)
+ .css('-webkit-transform', 'translateX(' + offset + 'px)')
+ .css('-moz-transform', 'translateX(' + offset + 'px)')
+ .css('-ms-transform', 'translateX(' + offset + 'px)')
+ .css('-o-transform', 'translateX(' + offset + 'px)')
+ .css('transform', 'translateX(' + offset + 'px)');
+ }
+ },
+
+ limit_to : function (val, min, max) {
+ return Math.min(Math.max(val, min), max);
+ },
+
+ initialize_settings : function (handle) {
+ var settings = $.extend({}, this.settings, this.data_options($(handle).parent())),
+ decimal_places_match_result;
+
+ if (settings.precision === null) {
+ decimal_places_match_result = ('' + settings.step).match(/\.([\d]*)/);
+ settings.precision = decimal_places_match_result && decimal_places_match_result[1] ? decimal_places_match_result[1].length : 0;
+ }
+
+ if (settings.vertical) {
+ $.data(handle, 'bar_o', $(handle).parent().offset().top);
+ $.data(handle, 'bar_l', $(handle).parent().outerHeight());
+ $.data(handle, 'handle_o', $(handle).offset().top);
+ $.data(handle, 'handle_l', $(handle).outerHeight());
+ } else {
+ $.data(handle, 'bar_o', $(handle).parent().offset().left);
+ $.data(handle, 'bar_l', $(handle).parent().outerWidth());
+ $.data(handle, 'handle_o', $(handle).offset().left);
+ $.data(handle, 'handle_l', $(handle).outerWidth());
+ }
+
+ $.data(handle, 'bar', $(handle).parent());
+ $.data(handle, 'settings', settings);
+ },
+
+ set_initial_position : function ($ele) {
+ var settings = $.data($ele.children('.range-slider-handle')[0], 'settings'),
+ initial = ((typeof settings.initial == 'number' && !isNaN(settings.initial)) ? settings.initial : Math.floor((settings.end - settings.start) * 0.5 / settings.step) * settings.step + settings.start),
+ $handle = $ele.children('.range-slider-handle');
+ this.set_ui($handle, initial);
+ },
+
+ set_value : function (value) {
+ var self = this;
+ $('[' + self.attr_name() + ']', this.scope).each(function () {
+ $(this).attr(self.attr_name(), value);
+ });
+ if (!!$(this.scope).attr(self.attr_name())) {
+ $(this.scope).attr(self.attr_name(), value);
+ }
+ self.reflow();
+ },
+
+ reflow : function () {
+ var self = this;
+ self.S('[' + this.attr_name() + ']').each(function () {
+ var handle = $(this).children('.range-slider-handle')[0],
+ val = $(this).attr(self.attr_name());
+ self.initialize_settings(handle);
+
+ if (val) {
+ self.set_ui($(handle), parseFloat(val));
+ } else {
+ self.set_initial_position($(this));
+ }
+ });
+ }
+ };
+
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.tab.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.tab.js
new file mode 100644
index 00000000..51daa252
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.tab.js
@@ -0,0 +1,237 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.tab = {
+ name : 'tab',
+
+ version : '5.5.1',
+
+ settings : {
+ active_class : 'active',
+ callback : function () {},
+ deep_linking : false,
+ scroll_to_content : true,
+ is_hover : false
+ },
+
+ default_tab_hashes : [],
+
+ init : function (scope, method, options) {
+ var self = this,
+ S = this.S;
+
+ this.bindings(method, options);
+
+ // store the initial href, which is used to allow correct behaviour of the
+ // browser back button when deep linking is turned on.
+ self.entry_location = window.location.href;
+
+ this.handle_location_hash_change();
+
+ // Store the default active tabs which will be referenced when the
+ // location hash is absent, as in the case of navigating the tabs and
+ // returning to the first viewing via the browser Back button.
+ S('[' + this.attr_name() + '] > .active > a', this.scope).each(function () {
+ self.default_tab_hashes.push(this.hash);
+ });
+ },
+
+ events : function () {
+ var self = this,
+ S = this.S;
+
+ var usual_tab_behavior = function (e) {
+ var settings = S(this).closest('[' + self.attr_name() + ']').data(self.attr_name(true) + '-init');
+ if (!settings.is_hover || Modernizr.touch) {
+ e.preventDefault();
+ e.stopPropagation();
+ self.toggle_active_tab(S(this).parent());
+ }
+ };
+
+ S(this.scope)
+ .off('.tab')
+ // Click event: tab title
+ .on('focus.fndtn.tab', '[' + this.attr_name() + '] > * > a', usual_tab_behavior )
+ .on('click.fndtn.tab', '[' + this.attr_name() + '] > * > a', usual_tab_behavior )
+ // Hover event: tab title
+ .on('mouseenter.fndtn.tab', '[' + this.attr_name() + '] > * > a', function (e) {
+ var settings = S(this).closest('[' + self.attr_name() + ']').data(self.attr_name(true) + '-init');
+ if (settings.is_hover) {
+ self.toggle_active_tab(S(this).parent());
+ }
+ });
+
+ // Location hash change event
+ S(window).on('hashchange.fndtn.tab', function (e) {
+ e.preventDefault();
+ self.handle_location_hash_change();
+ });
+ },
+
+ handle_location_hash_change : function () {
+
+ var self = this,
+ S = this.S;
+
+ S('[' + this.attr_name() + ']', this.scope).each(function () {
+ var settings = S(this).data(self.attr_name(true) + '-init');
+ if (settings.deep_linking) {
+ // Match the location hash to a label
+ var hash;
+ if (settings.scroll_to_content) {
+ hash = self.scope.location.hash;
+ } else {
+ // prefix the hash to prevent anchor scrolling
+ hash = self.scope.location.hash.replace('fndtn-', '');
+ }
+ if (hash != '') {
+ // Check whether the location hash references a tab content div or
+ // another element on the page (inside or outside the tab content div)
+ var hash_element = S(hash);
+ if (hash_element.hasClass('content') && hash_element.parent().hasClass('tabs-content')) {
+ // Tab content div
+ self.toggle_active_tab($('[' + self.attr_name() + '] > * > a[href=' + hash + ']').parent());
+ } else {
+ // Not the tab content div. If inside the tab content, find the
+ // containing tab and toggle it as active.
+ var hash_tab_container_id = hash_element.closest('.content').attr('id');
+ if (hash_tab_container_id != undefined) {
+ self.toggle_active_tab($('[' + self.attr_name() + '] > * > a[href=#' + hash_tab_container_id + ']').parent(), hash);
+ }
+ }
+ } else {
+ // Reference the default tab hashes which were initialized in the init function
+ for (var ind = 0; ind < self.default_tab_hashes.length; ind++) {
+ self.toggle_active_tab($('[' + self.attr_name() + '] > * > a[href=' + self.default_tab_hashes[ind] + ']').parent());
+ }
+ }
+ }
+ });
+ },
+
+ toggle_active_tab : function (tab, location_hash) {
+ var self = this,
+ S = self.S,
+ tabs = tab.closest('[' + this.attr_name() + ']'),
+ tab_link = tab.find('a'),
+ anchor = tab.children('a').first(),
+ target_hash = '#' + anchor.attr('href').split('#')[1],
+ target = S(target_hash),
+ siblings = tab.siblings(),
+ settings = tabs.data(this.attr_name(true) + '-init'),
+ interpret_keyup_action = function (e) {
+ // Light modification of Heydon Pickering's Practical ARIA Examples: http://heydonworks.com/practical_aria_examples/js/a11y.js
+
+ // define current, previous and next (possible) tabs
+
+ var $original = $(this);
+ var $prev = $(this).parents('li').prev().children('[role="tab"]');
+ var $next = $(this).parents('li').next().children('[role="tab"]');
+ var $target;
+
+ // find the direction (prev or next)
+
+ switch (e.keyCode) {
+ case 37:
+ $target = $prev;
+ break;
+ case 39:
+ $target = $next;
+ break;
+ default:
+ $target = false
+ break;
+ }
+
+ if ($target.length) {
+ $original.attr({
+ 'tabindex' : '-1',
+ 'aria-selected' : null
+ });
+ $target.attr({
+ 'tabindex' : '0',
+ 'aria-selected' : true
+ }).focus();
+ }
+
+ // Hide panels
+
+ $('[role="tabpanel"]')
+ .attr('aria-hidden', 'true');
+
+ // Show panel which corresponds to target
+
+ $('#' + $(document.activeElement).attr('href').substring(1))
+ .attr('aria-hidden', null);
+
+ },
+ go_to_hash = function(hash) {
+ // This function allows correct behaviour of the browser's back button when deep linking is enabled. Without it
+ // the user would get continually redirected to the default hash.
+ var is_entry_location = window.location.href === self.entry_location,
+ default_hash = settings.scroll_to_content ? self.default_tab_hashes[0] : is_entry_location ? window.location.hash :'fndtn-' + self.default_tab_hashes[0].replace('#', '')
+
+ if (!(is_entry_location && hash === default_hash)) {
+ window.location.hash = hash;
+ }
+ };
+
+ // allow usage of data-tab-content attribute instead of href
+ if (S(this).data(this.data_attr('tab-content'))) {
+ target_hash = '#' + S(this).data(this.data_attr('tab-content')).split('#')[1];
+ target = S(target_hash);
+ }
+
+ if (settings.deep_linking) {
+
+ if (settings.scroll_to_content) {
+
+ // retain current hash to scroll to content
+ go_to_hash(location_hash || target_hash);
+
+ if (location_hash == undefined || location_hash == target_hash) {
+ tab.parent()[0].scrollIntoView();
+ } else {
+ S(target_hash)[0].scrollIntoView();
+ }
+ } else {
+ // prefix the hashes so that the browser doesn't scroll down
+ if (location_hash != undefined) {
+ go_to_hash('fndtn-' + location_hash.replace('#', ''));
+ } else {
+ go_to_hash('fndtn-' + target_hash.replace('#', ''));
+ }
+ }
+ }
+
+ // WARNING: The activation and deactivation of the tab content must
+ // occur after the deep linking in order to properly refresh the browser
+ // window (notably in Chrome).
+ // Clean up multiple attr instances to done once
+ tab.addClass(settings.active_class).triggerHandler('opened');
+ tab_link.attr({'aria-selected' : 'true', tabindex : 0});
+ siblings.removeClass(settings.active_class)
+ siblings.find('a').attr({'aria-selected' : 'false', tabindex : -1});
+ target.siblings().removeClass(settings.active_class).attr({'aria-hidden' : 'true', tabindex : -1});
+ target.addClass(settings.active_class).attr('aria-hidden', 'false').removeAttr('tabindex');
+ settings.callback(tab);
+ target.triggerHandler('toggled', [tab]);
+ tabs.triggerHandler('toggled', [target]);
+
+ tab_link.off('keydown').on('keydown', interpret_keyup_action );
+ },
+
+ data_attr : function (str) {
+ if (this.namespace.length > 0) {
+ return this.namespace + '-' + str;
+ }
+
+ return str;
+ },
+
+ off : function () {},
+
+ reflow : function () {}
+ };
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.tooltip.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.tooltip.js
new file mode 100644
index 00000000..bb8faac6
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.tooltip.js
@@ -0,0 +1,307 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.tooltip = {
+ name : 'tooltip',
+
+ version : '5.5.1',
+
+ settings : {
+ additional_inheritable_classes : [],
+ tooltip_class : '.tooltip',
+ append_to : 'body',
+ touch_close_text : 'Tap To Close',
+ disable_for_touch : false,
+ hover_delay : 200,
+ show_on : 'all',
+ tip_template : function (selector, content) {
+ return '' + content + ' ';
+ }
+ },
+
+ cache : {},
+
+ init : function (scope, method, options) {
+ Foundation.inherit(this, 'random_str');
+ this.bindings(method, options);
+ },
+
+ should_show : function (target, tip) {
+ var settings = $.extend({}, this.settings, this.data_options(target));
+
+ if (settings.show_on === 'all') {
+ return true;
+ } else if (this.small() && settings.show_on === 'small') {
+ return true;
+ } else if (this.medium() && settings.show_on === 'medium') {
+ return true;
+ } else if (this.large() && settings.show_on === 'large') {
+ return true;
+ }
+ return false;
+ },
+
+ medium : function () {
+ return matchMedia(Foundation.media_queries['medium']).matches;
+ },
+
+ large : function () {
+ return matchMedia(Foundation.media_queries['large']).matches;
+ },
+
+ events : function (instance) {
+ var self = this,
+ S = self.S;
+
+ self.create(this.S(instance));
+
+ $(this.scope)
+ .off('.tooltip')
+ .on('mouseenter.fndtn.tooltip mouseleave.fndtn.tooltip touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip',
+ '[' + this.attr_name() + ']', function (e) {
+ var $this = S(this),
+ settings = $.extend({}, self.settings, self.data_options($this)),
+ is_touch = false;
+
+ if (Modernizr.touch && /touchstart|MSPointerDown/i.test(e.type) && S(e.target).is('a')) {
+ return false;
+ }
+
+ if (/mouse/i.test(e.type) && self.ie_touch(e)) {
+ return false;
+ }
+
+ if ($this.hasClass('open')) {
+ if (Modernizr.touch && /touchstart|MSPointerDown/i.test(e.type)) {
+ e.preventDefault();
+ }
+ self.hide($this);
+ } else {
+ if (settings.disable_for_touch && Modernizr.touch && /touchstart|MSPointerDown/i.test(e.type)) {
+ return;
+ } else if (!settings.disable_for_touch && Modernizr.touch && /touchstart|MSPointerDown/i.test(e.type)) {
+ e.preventDefault();
+ S(settings.tooltip_class + '.open').hide();
+ is_touch = true;
+ }
+
+ if (/enter|over/i.test(e.type)) {
+ this.timer = setTimeout(function () {
+ var tip = self.showTip($this);
+ }.bind(this), self.settings.hover_delay);
+ } else if (e.type === 'mouseout' || e.type === 'mouseleave') {
+ clearTimeout(this.timer);
+ self.hide($this);
+ } else {
+ self.showTip($this);
+ }
+ }
+ })
+ .on('mouseleave.fndtn.tooltip touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip', '[' + this.attr_name() + '].open', function (e) {
+ if (/mouse/i.test(e.type) && self.ie_touch(e)) {
+ return false;
+ }
+
+ if ($(this).data('tooltip-open-event-type') == 'touch' && e.type == 'mouseleave') {
+ return;
+ } else if ($(this).data('tooltip-open-event-type') == 'mouse' && /MSPointerDown|touchstart/i.test(e.type)) {
+ self.convert_to_touch($(this));
+ } else {
+ self.hide($(this));
+ }
+ })
+ .on('DOMNodeRemoved DOMAttrModified', '[' + this.attr_name() + ']:not(a)', function (e) {
+ self.hide(S(this));
+ });
+ },
+
+ ie_touch : function (e) {
+ // How do I distinguish between IE11 and Windows Phone 8?????
+ return false;
+ },
+
+ showTip : function ($target) {
+ var $tip = this.getTip($target);
+ if (this.should_show($target, $tip)) {
+ return this.show($target);
+ }
+ return;
+ },
+
+ getTip : function ($target) {
+ var selector = this.selector($target),
+ settings = $.extend({}, this.settings, this.data_options($target)),
+ tip = null;
+
+ if (selector) {
+ tip = this.S('span[data-selector="' + selector + '"]' + settings.tooltip_class);
+ }
+
+ return (typeof tip === 'object') ? tip : false;
+ },
+
+ selector : function ($target) {
+ var id = $target.attr('id'),
+ dataSelector = $target.attr(this.attr_name()) || $target.attr('data-selector');
+
+ if ((id && id.length < 1 || !id) && typeof dataSelector != 'string') {
+ dataSelector = this.random_str(6);
+ $target
+ .attr('data-selector', dataSelector)
+ .attr('aria-describedby', dataSelector);
+ }
+
+ return (id && id.length > 0) ? id : dataSelector;
+ },
+
+ create : function ($target) {
+ var self = this,
+ settings = $.extend({}, this.settings, this.data_options($target)),
+ tip_template = this.settings.tip_template;
+
+ if (typeof settings.tip_template === 'string' && window.hasOwnProperty(settings.tip_template)) {
+ tip_template = window[settings.tip_template];
+ }
+
+ var $tip = $(tip_template(this.selector($target), $('
').html($target.attr('title')).html())),
+ classes = this.inheritable_classes($target);
+
+ $tip.addClass(classes).appendTo(settings.append_to);
+
+ if (Modernizr.touch) {
+ $tip.append('' + settings.touch_close_text + ' ');
+ $tip.on('touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip', function (e) {
+ self.hide($target);
+ });
+ }
+
+ $target.removeAttr('title').attr('title', '');
+ },
+
+ reposition : function (target, tip, classes) {
+ var width, nub, nubHeight, nubWidth, column, objPos;
+
+ tip.css('visibility', 'hidden').show();
+
+ width = target.data('width');
+ nub = tip.children('.nub');
+ nubHeight = nub.outerHeight();
+ nubWidth = nub.outerHeight();
+
+ if (this.small()) {
+ tip.css({'width' : '100%'});
+ } else {
+ tip.css({'width' : (width) ? width : 'auto'});
+ }
+
+ objPos = function (obj, top, right, bottom, left, width) {
+ return obj.css({
+ 'top' : (top) ? top : 'auto',
+ 'bottom' : (bottom) ? bottom : 'auto',
+ 'left' : (left) ? left : 'auto',
+ 'right' : (right) ? right : 'auto'
+ }).end();
+ };
+
+ objPos(tip, (target.offset().top + target.outerHeight() + 10), 'auto', 'auto', target.offset().left);
+
+ if (this.small()) {
+ objPos(tip, (target.offset().top + target.outerHeight() + 10), 'auto', 'auto', 12.5, $(this.scope).width());
+ tip.addClass('tip-override');
+ objPos(nub, -nubHeight, 'auto', 'auto', target.offset().left);
+ } else {
+ var left = target.offset().left;
+ if (Foundation.rtl) {
+ nub.addClass('rtl');
+ left = target.offset().left + target.outerWidth() - tip.outerWidth();
+ }
+ objPos(tip, (target.offset().top + target.outerHeight() + 10), 'auto', 'auto', left);
+ tip.removeClass('tip-override');
+ if (classes && classes.indexOf('tip-top') > -1) {
+ if (Foundation.rtl) {
+ nub.addClass('rtl');
+ }
+ objPos(tip, (target.offset().top - tip.outerHeight()), 'auto', 'auto', left)
+ .removeClass('tip-override');
+ } else if (classes && classes.indexOf('tip-left') > -1) {
+ objPos(tip, (target.offset().top + (target.outerHeight() / 2) - (tip.outerHeight() / 2)), 'auto', 'auto', (target.offset().left - tip.outerWidth() - nubHeight))
+ .removeClass('tip-override');
+ nub.removeClass('rtl');
+ } else if (classes && classes.indexOf('tip-right') > -1) {
+ objPos(tip, (target.offset().top + (target.outerHeight() / 2) - (tip.outerHeight() / 2)), 'auto', 'auto', (target.offset().left + target.outerWidth() + nubHeight))
+ .removeClass('tip-override');
+ nub.removeClass('rtl');
+ }
+ }
+
+ tip.css('visibility', 'visible').hide();
+ },
+
+ small : function () {
+ return matchMedia(Foundation.media_queries.small).matches &&
+ !matchMedia(Foundation.media_queries.medium).matches;
+ },
+
+ inheritable_classes : function ($target) {
+ var settings = $.extend({}, this.settings, this.data_options($target)),
+ inheritables = ['tip-top', 'tip-left', 'tip-bottom', 'tip-right', 'radius', 'round'].concat(settings.additional_inheritable_classes),
+ classes = $target.attr('class'),
+ filtered = classes ? $.map(classes.split(' '), function (el, i) {
+ if ($.inArray(el, inheritables) !== -1) {
+ return el;
+ }
+ }).join(' ') : '';
+
+ return $.trim(filtered);
+ },
+
+ convert_to_touch : function ($target) {
+ var self = this,
+ $tip = self.getTip($target),
+ settings = $.extend({}, self.settings, self.data_options($target));
+
+ if ($tip.find('.tap-to-close').length === 0) {
+ $tip.append('' + settings.touch_close_text + ' ');
+ $tip.on('click.fndtn.tooltip.tapclose touchstart.fndtn.tooltip.tapclose MSPointerDown.fndtn.tooltip.tapclose', function (e) {
+ self.hide($target);
+ });
+ }
+
+ $target.data('tooltip-open-event-type', 'touch');
+ },
+
+ show : function ($target) {
+ var $tip = this.getTip($target);
+
+ if ($target.data('tooltip-open-event-type') == 'touch') {
+ this.convert_to_touch($target);
+ }
+
+ this.reposition($target, $tip, $target.attr('class'));
+ $target.addClass('open');
+ $tip.fadeIn(150);
+ },
+
+ hide : function ($target) {
+ var $tip = this.getTip($target);
+
+ $tip.fadeOut(150, function () {
+ $tip.find('.tap-to-close').remove();
+ $tip.off('click.fndtn.tooltip.tapclose MSPointerDown.fndtn.tapclose');
+ $target.removeClass('open');
+ });
+ },
+
+ off : function () {
+ var self = this;
+ this.S(this.scope).off('.fndtn.tooltip');
+ this.S(this.settings.tooltip_class).each(function (i) {
+ $('[' + self.attr_name() + ']').eq(i).attr('title', $(this).text());
+ }).remove();
+ },
+
+ reflow : function () {}
+ };
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.topbar.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.topbar.js
new file mode 100644
index 00000000..30e581dc
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/foundation/foundation.topbar.js
@@ -0,0 +1,452 @@
+;(function ($, window, document, undefined) {
+ 'use strict';
+
+ Foundation.libs.topbar = {
+ name : 'topbar',
+
+ version : '5.5.1',
+
+ settings : {
+ index : 0,
+ sticky_class : 'sticky',
+ custom_back_text : true,
+ back_text : 'Back',
+ mobile_show_parent_link : true,
+ is_hover : true,
+ scrolltop : true, // jump to top when sticky nav menu toggle is clicked
+ sticky_on : 'all'
+ },
+
+ init : function (section, method, options) {
+ Foundation.inherit(this, 'add_custom_rule register_media throttle');
+ var self = this;
+
+ self.register_media('topbar', 'foundation-mq-topbar');
+
+ this.bindings(method, options);
+
+ self.S('[' + this.attr_name() + ']', this.scope).each(function () {
+ var topbar = $(this),
+ settings = topbar.data(self.attr_name(true) + '-init'),
+ section = self.S('section, .top-bar-section', this);
+ topbar.data('index', 0);
+ var topbarContainer = topbar.parent();
+ if (topbarContainer.hasClass('fixed') || self.is_sticky(topbar, topbarContainer, settings) ) {
+ self.settings.sticky_class = settings.sticky_class;
+ self.settings.sticky_topbar = topbar;
+ topbar.data('height', topbarContainer.outerHeight());
+ topbar.data('stickyoffset', topbarContainer.offset().top);
+ } else {
+ topbar.data('height', topbar.outerHeight());
+ }
+
+ if (!settings.assembled) {
+ self.assemble(topbar);
+ }
+
+ if (settings.is_hover) {
+ self.S('.has-dropdown', topbar).addClass('not-click');
+ } else {
+ self.S('.has-dropdown', topbar).removeClass('not-click');
+ }
+
+ // Pad body when sticky (scrolled) or fixed.
+ self.add_custom_rule('.f-topbar-fixed { padding-top: ' + topbar.data('height') + 'px }');
+
+ if (topbarContainer.hasClass('fixed')) {
+ self.S('body').addClass('f-topbar-fixed');
+ }
+ });
+
+ },
+
+ is_sticky : function (topbar, topbarContainer, settings) {
+ var sticky = topbarContainer.hasClass(settings.sticky_class);
+ var smallMatch = matchMedia(Foundation.media_queries.small).matches;
+ var medMatch = matchMedia(Foundation.media_queries.medium).matches;
+ var lrgMatch = matchMedia(Foundation.media_queries.large).matches;
+
+ if (sticky && settings.sticky_on === 'all') {
+ return true;
+ }
+ if (sticky && this.small() && settings.sticky_on.indexOf('small') !== -1) {
+ if (smallMatch && !medMatch && !lrgMatch) { return true; }
+ }
+ if (sticky && this.medium() && settings.sticky_on.indexOf('medium') !== -1) {
+ if (smallMatch && medMatch && !lrgMatch) { return true; }
+ }
+ if (sticky && this.large() && settings.sticky_on.indexOf('large') !== -1) {
+ if (smallMatch && medMatch && lrgMatch) { return true; }
+ }
+
+ // fix for iOS browsers
+ if (sticky && navigator.userAgent.match(/(iPad|iPhone|iPod)/g)) {
+ return true;
+ }
+ return false;
+ },
+
+ toggle : function (toggleEl) {
+ var self = this,
+ topbar;
+
+ if (toggleEl) {
+ topbar = self.S(toggleEl).closest('[' + this.attr_name() + ']');
+ } else {
+ topbar = self.S('[' + this.attr_name() + ']');
+ }
+
+ var settings = topbar.data(this.attr_name(true) + '-init');
+
+ var section = self.S('section, .top-bar-section', topbar);
+
+ if (self.breakpoint()) {
+ if (!self.rtl) {
+ section.css({left : '0%'});
+ $('>.name', section).css({left : '100%'});
+ } else {
+ section.css({right : '0%'});
+ $('>.name', section).css({right : '100%'});
+ }
+
+ self.S('li.moved', section).removeClass('moved');
+ topbar.data('index', 0);
+
+ topbar
+ .toggleClass('expanded')
+ .css('height', '');
+ }
+
+ if (settings.scrolltop) {
+ if (!topbar.hasClass('expanded')) {
+ if (topbar.hasClass('fixed')) {
+ topbar.parent().addClass('fixed');
+ topbar.removeClass('fixed');
+ self.S('body').addClass('f-topbar-fixed');
+ }
+ } else if (topbar.parent().hasClass('fixed')) {
+ if (settings.scrolltop) {
+ topbar.parent().removeClass('fixed');
+ topbar.addClass('fixed');
+ self.S('body').removeClass('f-topbar-fixed');
+
+ window.scrollTo(0, 0);
+ } else {
+ topbar.parent().removeClass('expanded');
+ }
+ }
+ } else {
+ if (self.is_sticky(topbar, topbar.parent(), settings)) {
+ topbar.parent().addClass('fixed');
+ }
+
+ if (topbar.parent().hasClass('fixed')) {
+ if (!topbar.hasClass('expanded')) {
+ topbar.removeClass('fixed');
+ topbar.parent().removeClass('expanded');
+ self.update_sticky_positioning();
+ } else {
+ topbar.addClass('fixed');
+ topbar.parent().addClass('expanded');
+ self.S('body').addClass('f-topbar-fixed');
+ }
+ }
+ }
+ },
+
+ timer : null,
+
+ events : function (bar) {
+ var self = this,
+ S = this.S;
+
+ S(this.scope)
+ .off('.topbar')
+ .on('click.fndtn.topbar', '[' + this.attr_name() + '] .toggle-topbar', function (e) {
+ e.preventDefault();
+ self.toggle(this);
+ })
+ .on('click.fndtn.topbar', '.top-bar .top-bar-section li a[href^="#"],[' + this.attr_name() + '] .top-bar-section li a[href^="#"]', function (e) {
+ var li = $(this).closest('li');
+ if (self.breakpoint() && !li.hasClass('back') && !li.hasClass('has-dropdown')) {
+ self.toggle();
+ }
+ })
+ .on('click.fndtn.topbar', '[' + this.attr_name() + '] li.has-dropdown', function (e) {
+ var li = S(this),
+ target = S(e.target),
+ topbar = li.closest('[' + self.attr_name() + ']'),
+ settings = topbar.data(self.attr_name(true) + '-init');
+
+ if (target.data('revealId')) {
+ self.toggle();
+ return;
+ }
+
+ if (self.breakpoint()) {
+ return;
+ }
+
+ if (settings.is_hover && !Modernizr.touch) {
+ return;
+ }
+
+ e.stopImmediatePropagation();
+
+ if (li.hasClass('hover')) {
+ li
+ .removeClass('hover')
+ .find('li')
+ .removeClass('hover');
+
+ li.parents('li.hover')
+ .removeClass('hover');
+ } else {
+ li.addClass('hover');
+
+ $(li).siblings().removeClass('hover');
+
+ if (target[0].nodeName === 'A' && target.parent().hasClass('has-dropdown')) {
+ e.preventDefault();
+ }
+ }
+ })
+ .on('click.fndtn.topbar', '[' + this.attr_name() + '] .has-dropdown>a', function (e) {
+ if (self.breakpoint()) {
+
+ e.preventDefault();
+
+ var $this = S(this),
+ topbar = $this.closest('[' + self.attr_name() + ']'),
+ section = topbar.find('section, .top-bar-section'),
+ dropdownHeight = $this.next('.dropdown').outerHeight(),
+ $selectedLi = $this.closest('li');
+
+ topbar.data('index', topbar.data('index') + 1);
+ $selectedLi.addClass('moved');
+
+ if (!self.rtl) {
+ section.css({left : -(100 * topbar.data('index')) + '%'});
+ section.find('>.name').css({left : 100 * topbar.data('index') + '%'});
+ } else {
+ section.css({right : -(100 * topbar.data('index')) + '%'});
+ section.find('>.name').css({right : 100 * topbar.data('index') + '%'});
+ }
+
+ topbar.css('height', $this.siblings('ul').outerHeight(true) + topbar.data('height'));
+ }
+ });
+
+ S(window).off('.topbar').on('resize.fndtn.topbar', self.throttle(function () {
+ self.resize.call(self);
+ }, 50)).trigger('resize').trigger('resize.fndtn.topbar').load(function () {
+ // Ensure that the offset is calculated after all of the pages resources have loaded
+ S(this).trigger('resize.fndtn.topbar');
+ });
+
+ S('body').off('.topbar').on('click.fndtn.topbar', function (e) {
+ var parent = S(e.target).closest('li').closest('li.hover');
+
+ if (parent.length > 0) {
+ return;
+ }
+
+ S('[' + self.attr_name() + '] li.hover').removeClass('hover');
+ });
+
+ // Go up a level on Click
+ S(this.scope).on('click.fndtn.topbar', '[' + this.attr_name() + '] .has-dropdown .back', function (e) {
+ e.preventDefault();
+
+ var $this = S(this),
+ topbar = $this.closest('[' + self.attr_name() + ']'),
+ section = topbar.find('section, .top-bar-section'),
+ settings = topbar.data(self.attr_name(true) + '-init'),
+ $movedLi = $this.closest('li.moved'),
+ $previousLevelUl = $movedLi.parent();
+
+ topbar.data('index', topbar.data('index') - 1);
+
+ if (!self.rtl) {
+ section.css({left : -(100 * topbar.data('index')) + '%'});
+ section.find('>.name').css({left : 100 * topbar.data('index') + '%'});
+ } else {
+ section.css({right : -(100 * topbar.data('index')) + '%'});
+ section.find('>.name').css({right : 100 * topbar.data('index') + '%'});
+ }
+
+ if (topbar.data('index') === 0) {
+ topbar.css('height', '');
+ } else {
+ topbar.css('height', $previousLevelUl.outerHeight(true) + topbar.data('height'));
+ }
+
+ setTimeout(function () {
+ $movedLi.removeClass('moved');
+ }, 300);
+ });
+
+ // Show dropdown menus when their items are focused
+ S(this.scope).find('.dropdown a')
+ .focus(function () {
+ $(this).parents('.has-dropdown').addClass('hover');
+ })
+ .blur(function () {
+ $(this).parents('.has-dropdown').removeClass('hover');
+ });
+ },
+
+ resize : function () {
+ var self = this;
+ self.S('[' + this.attr_name() + ']').each(function () {
+ var topbar = self.S(this),
+ settings = topbar.data(self.attr_name(true) + '-init');
+
+ var stickyContainer = topbar.parent('.' + self.settings.sticky_class);
+ var stickyOffset;
+
+ if (!self.breakpoint()) {
+ var doToggle = topbar.hasClass('expanded');
+ topbar
+ .css('height', '')
+ .removeClass('expanded')
+ .find('li')
+ .removeClass('hover');
+
+ if (doToggle) {
+ self.toggle(topbar);
+ }
+ }
+
+ if (self.is_sticky(topbar, stickyContainer, settings)) {
+ if (stickyContainer.hasClass('fixed')) {
+ // Remove the fixed to allow for correct calculation of the offset.
+ stickyContainer.removeClass('fixed');
+
+ stickyOffset = stickyContainer.offset().top;
+ if (self.S(document.body).hasClass('f-topbar-fixed')) {
+ stickyOffset -= topbar.data('height');
+ }
+
+ topbar.data('stickyoffset', stickyOffset);
+ stickyContainer.addClass('fixed');
+ } else {
+ stickyOffset = stickyContainer.offset().top;
+ topbar.data('stickyoffset', stickyOffset);
+ }
+ }
+
+ });
+ },
+
+ breakpoint : function () {
+ return !matchMedia(Foundation.media_queries['topbar']).matches;
+ },
+
+ small : function () {
+ return matchMedia(Foundation.media_queries['small']).matches;
+ },
+
+ medium : function () {
+ return matchMedia(Foundation.media_queries['medium']).matches;
+ },
+
+ large : function () {
+ return matchMedia(Foundation.media_queries['large']).matches;
+ },
+
+ assemble : function (topbar) {
+ var self = this,
+ settings = topbar.data(this.attr_name(true) + '-init'),
+ section = self.S('section, .top-bar-section', topbar);
+
+ // Pull element out of the DOM for manipulation
+ section.detach();
+
+ self.S('.has-dropdown>a', section).each(function () {
+ var $link = self.S(this),
+ $dropdown = $link.siblings('.dropdown'),
+ url = $link.attr('href'),
+ $titleLi;
+
+ if (!$dropdown.find('.title.back').length) {
+
+ if (settings.mobile_show_parent_link == true && url) {
+ $titleLi = $(' ' + $link.html() +' ');
+ } else {
+ $titleLi = $(' ');
+ }
+
+ // Copy link to subnav
+ if (settings.custom_back_text == true) {
+ $('h5>a', $titleLi).html(settings.back_text);
+ } else {
+ $('h5>a', $titleLi).html('« ' + $link.html());
+ }
+ $dropdown.prepend($titleLi);
+ }
+ });
+
+ // Put element back in the DOM
+ section.appendTo(topbar);
+
+ // check for sticky
+ this.sticky();
+
+ this.assembled(topbar);
+ },
+
+ assembled : function (topbar) {
+ topbar.data(this.attr_name(true), $.extend({}, topbar.data(this.attr_name(true)), {assembled : true}));
+ },
+
+ height : function (ul) {
+ var total = 0,
+ self = this;
+
+ $('> li', ul).each(function () {
+ total += self.S(this).outerHeight(true);
+ });
+
+ return total;
+ },
+
+ sticky : function () {
+ var self = this;
+
+ this.S(window).on('scroll', function () {
+ self.update_sticky_positioning();
+ });
+ },
+
+ update_sticky_positioning : function () {
+ var klass = '.' + this.settings.sticky_class,
+ $window = this.S(window),
+ self = this;
+
+ if (self.settings.sticky_topbar && self.is_sticky(this.settings.sticky_topbar, this.settings.sticky_topbar.parent(), this.settings)) {
+ var distance = this.settings.sticky_topbar.data('stickyoffset');
+ if (!self.S(klass).hasClass('expanded')) {
+ if ($window.scrollTop() > (distance)) {
+ if (!self.S(klass).hasClass('fixed')) {
+ self.S(klass).addClass('fixed');
+ self.S('body').addClass('f-topbar-fixed');
+ }
+ } else if ($window.scrollTop() <= distance) {
+ if (self.S(klass).hasClass('fixed')) {
+ self.S(klass).removeClass('fixed');
+ self.S('body').removeClass('f-topbar-fixed');
+ }
+ }
+ }
+ }
+ },
+
+ off : function () {
+ this.S(this.scope).off('.fndtn.topbar');
+ this.S(window).off('.fndtn.topbar');
+ },
+
+ reflow : function () {}
+ };
+}(jQuery, window, window.document));
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/vendor/fastclick.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/vendor/fastclick.js
new file mode 100644
index 00000000..add01308
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/vendor/fastclick.js
@@ -0,0 +1,8 @@
+!function(){"use strict";/**
+ * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
+ *
+ * @codingstandard ftlabs-jsv2
+ * @copyright The Financial Times Limited [All Rights Reserved]
+ * @license MIT License (see LICENSE.txt)
+ */
+function a(b,d){function e(a,b){return function(){return a.apply(b,arguments)}}var f;if(d=d||{},this.trackingClick=!1,this.trackingClickStart=0,this.targetElement=null,this.touchStartX=0,this.touchStartY=0,this.lastTouchIdentifier=0,this.touchBoundary=d.touchBoundary||10,this.layer=b,this.tapDelay=d.tapDelay||200,this.tapTimeout=d.tapTimeout||700,!a.notNeeded(b)){for(var g=["onMouse","onClick","onTouchStart","onTouchMove","onTouchEnd","onTouchCancel"],h=this,i=0,j=g.length;j>i;i++)h[g[i]]=e(h[g[i]],h);c&&(b.addEventListener("mouseover",this.onMouse,!0),b.addEventListener("mousedown",this.onMouse,!0),b.addEventListener("mouseup",this.onMouse,!0)),b.addEventListener("click",this.onClick,!0),b.addEventListener("touchstart",this.onTouchStart,!1),b.addEventListener("touchmove",this.onTouchMove,!1),b.addEventListener("touchend",this.onTouchEnd,!1),b.addEventListener("touchcancel",this.onTouchCancel,!1),Event.prototype.stopImmediatePropagation||(b.removeEventListener=function(a,c,d){var e=Node.prototype.removeEventListener;"click"===a?e.call(b,a,c.hijacked||c,d):e.call(b,a,c,d)},b.addEventListener=function(a,c,d){var e=Node.prototype.addEventListener;"click"===a?e.call(b,a,c.hijacked||(c.hijacked=function(a){a.propagationStopped||c(a)}),d):e.call(b,a,c,d)}),"function"==typeof b.onclick&&(f=b.onclick,b.addEventListener("click",function(a){f(a)},!1),b.onclick=null)}}var b=navigator.userAgent.indexOf("Windows Phone")>=0,c=navigator.userAgent.indexOf("Android")>0&&!b,d=/iP(ad|hone|od)/.test(navigator.userAgent)&&!b,e=d&&/OS 4_\d(_\d)?/.test(navigator.userAgent),f=d&&/OS [6-7]_\d/.test(navigator.userAgent),g=navigator.userAgent.indexOf("BB10")>0;a.prototype.needsClick=function(a){switch(a.nodeName.toLowerCase()){case"button":case"select":case"textarea":if(a.disabled)return!0;break;case"input":if(d&&"file"===a.type||a.disabled)return!0;break;case"label":case"iframe":case"video":return!0}return/\bneedsclick\b/.test(a.className)},a.prototype.needsFocus=function(a){switch(a.nodeName.toLowerCase()){case"textarea":return!0;case"select":return!c;case"input":switch(a.type){case"button":case"checkbox":case"file":case"image":case"radio":case"submit":return!1}return!a.disabled&&!a.readOnly;default:return/\bneedsfocus\b/.test(a.className)}},a.prototype.sendClick=function(a,b){var c,d;document.activeElement&&document.activeElement!==a&&document.activeElement.blur(),d=b.changedTouches[0],c=document.createEvent("MouseEvents"),c.initMouseEvent(this.determineEventType(a),!0,!0,window,1,d.screenX,d.screenY,d.clientX,d.clientY,!1,!1,!1,!1,0,null),c.forwardedTouchEvent=!0,a.dispatchEvent(c)},a.prototype.determineEventType=function(a){return c&&"select"===a.tagName.toLowerCase()?"mousedown":"click"},a.prototype.focus=function(a){var b;d&&a.setSelectionRange&&0!==a.type.indexOf("date")&&"time"!==a.type&&"month"!==a.type?(b=a.value.length,a.setSelectionRange(b,b)):a.focus()},a.prototype.updateScrollParent=function(a){var b,c;if(b=a.fastClickScrollParent,!b||!b.contains(a)){c=a;do{if(c.scrollHeight>c.offsetHeight){b=c,a.fastClickScrollParent=c;break}c=c.parentElement}while(c)}b&&(b.fastClickLastScrollTop=b.scrollTop)},a.prototype.getTargetElementFromEventTarget=function(a){return a.nodeType===Node.TEXT_NODE?a.parentNode:a},a.prototype.onTouchStart=function(a){var b,c,f;if(a.targetTouches.length>1)return!0;if(b=this.getTargetElementFromEventTarget(a.target),c=a.targetTouches[0],d){if(f=window.getSelection(),f.rangeCount&&!f.isCollapsed)return!0;if(!e){if(c.identifier&&c.identifier===this.lastTouchIdentifier)return a.preventDefault(),!1;this.lastTouchIdentifier=c.identifier,this.updateScrollParent(b)}}return this.trackingClick=!0,this.trackingClickStart=a.timeStamp,this.targetElement=b,this.touchStartX=c.pageX,this.touchStartY=c.pageY,a.timeStamp-this.lastClickTimec||Math.abs(b.pageY-this.touchStartY)>c?!0:!1},a.prototype.onTouchMove=function(a){return this.trackingClick?((this.targetElement!==this.getTargetElementFromEventTarget(a.target)||this.touchHasMoved(a))&&(this.trackingClick=!1,this.targetElement=null),!0):!0},a.prototype.findControl=function(a){return void 0!==a.control?a.control:a.htmlFor?document.getElementById(a.htmlFor):a.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")},a.prototype.onTouchEnd=function(a){var b,g,h,i,j,k=this.targetElement;if(!this.trackingClick)return!0;if(a.timeStamp-this.lastClickTimethis.tapTimeout)return!0;if(this.cancelNextClick=!1,this.lastClickTime=a.timeStamp,g=this.trackingClickStart,this.trackingClick=!1,this.trackingClickStart=0,f&&(j=a.changedTouches[0],k=document.elementFromPoint(j.pageX-window.pageXOffset,j.pageY-window.pageYOffset)||k,k.fastClickScrollParent=this.targetElement.fastClickScrollParent),h=k.tagName.toLowerCase(),"label"===h){if(b=this.findControl(k)){if(this.focus(k),c)return!1;k=b}}else if(this.needsFocus(k))return a.timeStamp-g>100||d&&window.top!==window&&"input"===h?(this.targetElement=null,!1):(this.focus(k),this.sendClick(k,a),d&&"select"===h||(this.targetElement=null,a.preventDefault()),!1);return d&&!e&&(i=k.fastClickScrollParent,i&&i.fastClickLastScrollTop!==i.scrollTop)?!0:(this.needsClick(k)||(a.preventDefault(),this.sendClick(k,a)),!1)},a.prototype.onTouchCancel=function(){this.trackingClick=!1,this.targetElement=null},a.prototype.onMouse=function(a){return this.targetElement?a.forwardedTouchEvent?!0:a.cancelable&&(!this.needsClick(this.targetElement)||this.cancelNextClick)?(a.stopImmediatePropagation?a.stopImmediatePropagation():a.propagationStopped=!0,a.stopPropagation(),a.preventDefault(),!1):!0:!0},a.prototype.onClick=function(a){var b;return this.trackingClick?(this.targetElement=null,this.trackingClick=!1,!0):"submit"===a.target.type&&0===a.detail?!0:(b=this.onMouse(a),b||(this.targetElement=null),b)},a.prototype.destroy=function(){var a=this.layer;c&&(a.removeEventListener("mouseover",this.onMouse,!0),a.removeEventListener("mousedown",this.onMouse,!0),a.removeEventListener("mouseup",this.onMouse,!0)),a.removeEventListener("click",this.onClick,!0),a.removeEventListener("touchstart",this.onTouchStart,!1),a.removeEventListener("touchmove",this.onTouchMove,!1),a.removeEventListener("touchend",this.onTouchEnd,!1),a.removeEventListener("touchcancel",this.onTouchCancel,!1)},a.notNeeded=function(a){var b,d,e,f;if("undefined"==typeof window.ontouchstart)return!0;if(d=+(/Chrome\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1]){if(!c)return!0;if(b=document.querySelector("meta[name=viewport]")){if(-1!==b.content.indexOf("user-scalable=no"))return!0;if(d>31&&document.documentElement.scrollWidth<=window.outerWidth)return!0}}if(g&&(e=navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/),e[1]>=10&&e[2]>=3&&(b=document.querySelector("meta[name=viewport]")))){if(-1!==b.content.indexOf("user-scalable=no"))return!0;if(document.documentElement.scrollWidth<=window.outerWidth)return!0}return"none"===a.style.msTouchAction||"manipulation"===a.style.touchAction?!0:(f=+(/Firefox\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1],f>=27&&(b=document.querySelector("meta[name=viewport]"),b&&(-1!==b.content.indexOf("user-scalable=no")||document.documentElement.scrollWidth<=window.outerWidth))?!0:"none"===a.style.touchAction||"manipulation"===a.style.touchAction?!0:!1)},a.attach=function(b,c){return new a(b,c)},"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return a}):"undefined"!=typeof module&&module.exports?(module.exports=a.attach,module.exports.FastClick=a):window.FastClick=a}();
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/vendor/jquery.cookie.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/vendor/jquery.cookie.js
new file mode 100644
index 00000000..5be813ad
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/vendor/jquery.cookie.js
@@ -0,0 +1,8 @@
+/*!
+ * jQuery Cookie Plugin v1.4.1
+ * https://github.com/carhartl/jquery-cookie
+ *
+ * Copyright 2013 Klaus Hartl
+ * Released under the MIT license
+ */
+!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):jQuery)}(function(a){function b(a){return h.raw?a:encodeURIComponent(a)}function c(a){return h.raw?a:decodeURIComponent(a)}function d(a){return b(h.json?JSON.stringify(a):String(a))}function e(a){0===a.indexOf('"')&&(a=a.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return a=decodeURIComponent(a.replace(g," ")),h.json?JSON.parse(a):a}catch(b){}}function f(b,c){var d=h.raw?b:e(b);return a.isFunction(c)?c(d):d}var g=/\+/g,h=a.cookie=function(e,g,i){if(void 0!==g&&!a.isFunction(g)){if(i=a.extend({},h.defaults,i),"number"==typeof i.expires){var j=i.expires,k=i.expires=new Date;k.setTime(+k+864e5*j)}return document.cookie=[b(e),"=",d(g),i.expires?"; expires="+i.expires.toUTCString():"",i.path?"; path="+i.path:"",i.domain?"; domain="+i.domain:"",i.secure?"; secure":""].join("")}for(var l=e?void 0:{},m=document.cookie?document.cookie.split("; "):[],n=0,o=m.length;o>n;n++){var p=m[n].split("="),q=c(p.shift()),r=p.join("=");if(e&&e===q){l=f(r,g);break}e||void 0===(r=f(r))||(l[q]=r)}return l};h.defaults={},a.removeCookie=function(b,c){return void 0===a.cookie(b)?!1:(a.cookie(b,"",a.extend({},c,{expires:-1})),!a.cookie(b))}});
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/vendor/jquery.js b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/vendor/jquery.js
new file mode 100644
index 00000000..92b06d15
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/foundation/js/vendor/jquery.js
@@ -0,0 +1,26 @@
+/*!
+ * jQuery JavaScript Library v2.1.3
+ * http://jquery.com/
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ *
+ * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2014-12-18T15:11Z
+ */
+!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){function c(a){var b=a.length,c=_.type(a);return"function"===c||_.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}function d(a,b,c){if(_.isFunction(b))return _.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return _.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(hb.test(b))return _.filter(b,a,c);b=_.filter(b,a)}return _.grep(a,function(a){return U.call(b,a)>=0!==c})}function e(a,b){for(;(a=a[b])&&1!==a.nodeType;);return a}function f(a){var b=ob[a]={};return _.each(a.match(nb)||[],function(a,c){b[c]=!0}),b}function g(){Z.removeEventListener("DOMContentLoaded",g,!1),a.removeEventListener("load",g,!1),_.ready()}function h(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=_.expando+h.uid++}function i(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(ub,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:tb.test(c)?_.parseJSON(c):c}catch(e){}sb.set(a,b,c)}else c=void 0;return c}function j(){return!0}function k(){return!1}function l(){try{return Z.activeElement}catch(a){}}function m(a,b){return _.nodeName(a,"table")&&_.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function n(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function o(a){var b=Kb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function p(a,b){for(var c=0,d=a.length;d>c;c++)rb.set(a[c],"globalEval",!b||rb.get(b[c],"globalEval"))}function q(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(rb.hasData(a)&&(f=rb.access(a),g=rb.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)_.event.add(b,e,j[e][c])}sb.hasData(a)&&(h=sb.access(a),i=_.extend({},h),sb.set(b,i))}}function r(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&_.nodeName(a,b)?_.merge([a],c):c}function s(a,b){var c=b.nodeName.toLowerCase();"input"===c&&yb.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}function t(b,c){var d,e=_(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:_.css(e[0],"display");return e.detach(),f}function u(a){var b=Z,c=Ob[a];return c||(c=t(a,b),"none"!==c&&c||(Nb=(Nb||_("")).appendTo(b.documentElement),b=Nb[0].contentDocument,b.write(),b.close(),c=t(a,b),Nb.detach()),Ob[a]=c),c}function v(a,b,c){var d,e,f,g,h=a.style;return c=c||Rb(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||_.contains(a.ownerDocument,a)||(g=_.style(a,b)),Qb.test(g)&&Pb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function w(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}function x(a,b){if(b in a)return b;for(var c=b[0].toUpperCase()+b.slice(1),d=b,e=Xb.length;e--;)if(b=Xb[e]+c,b in a)return b;return d}function y(a,b,c){var d=Tb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function z(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=_.css(a,c+wb[f],!0,e)),d?("content"===c&&(g-=_.css(a,"padding"+wb[f],!0,e)),"margin"!==c&&(g-=_.css(a,"border"+wb[f]+"Width",!0,e))):(g+=_.css(a,"padding"+wb[f],!0,e),"padding"!==c&&(g+=_.css(a,"border"+wb[f]+"Width",!0,e)));return g}function A(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Rb(a),g="border-box"===_.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=v(a,b,f),(0>e||null==e)&&(e=a.style[b]),Qb.test(e))return e;d=g&&(Y.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+z(a,b,c||(g?"border":"content"),d,f)+"px"}function B(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=rb.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&xb(d)&&(f[g]=rb.access(d,"olddisplay",u(d.nodeName)))):(e=xb(d),"none"===c&&e||rb.set(d,"olddisplay",e?c:_.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function C(a,b,c,d,e){return new C.prototype.init(a,b,c,d,e)}function D(){return setTimeout(function(){Yb=void 0}),Yb=_.now()}function E(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=wb[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function F(a,b,c){for(var d,e=(cc[b]||[]).concat(cc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function G(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},n=a.style,o=a.nodeType&&xb(a),p=rb.get(a,"fxshow");c.queue||(h=_._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,_.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[n.overflow,n.overflowX,n.overflowY],j=_.css(a,"display"),k="none"===j?rb.get(a,"olddisplay")||u(a.nodeName):j,"inline"===k&&"none"===_.css(a,"float")&&(n.display="inline-block")),c.overflow&&(n.overflow="hidden",l.always(function(){n.overflow=c.overflow[0],n.overflowX=c.overflow[1],n.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],$b.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(o?"hide":"show")){if("show"!==e||!p||void 0===p[d])continue;o=!0}m[d]=p&&p[d]||_.style(a,d)}else j=void 0;if(_.isEmptyObject(m))"inline"===("none"===j?u(a.nodeName):j)&&(n.display=j);else{p?"hidden"in p&&(o=p.hidden):p=rb.access(a,"fxshow",{}),f&&(p.hidden=!o),o?_(a).show():l.done(function(){_(a).hide()}),l.done(function(){var b;rb.remove(a,"fxshow");for(b in m)_.style(a,b,m[b])});for(d in m)g=F(o?p[d]:0,d,l),d in p||(p[d]=g.start,o&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function H(a,b){var c,d,e,f,g;for(c in a)if(d=_.camelCase(c),e=b[d],f=a[c],_.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=_.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function I(a,b,c){var d,e,f=0,g=bc.length,h=_.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Yb||D(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:_.extend({},b),opts:_.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:Yb||D(),duration:c.duration,tweens:[],createTween:function(b,c){var d=_.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(H(k,j.opts.specialEasing);g>f;f++)if(d=bc[f].call(j,a,k,j.opts))return d;return _.map(k,F,j),_.isFunction(j.opts.start)&&j.opts.start.call(a,j),_.fx.timer(_.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function J(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(nb)||[];if(_.isFunction(c))for(;d=f[e++];)"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function K(a,b,c,d){function e(h){var i;return f[h]=!0,_.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||g||f[j]?g?!(i=j):void 0:(b.dataTypes.unshift(j),e(j),!1)}),i}var f={},g=a===tc;return e(b.dataTypes[0])||!f["*"]&&e("*")}function L(a,b){var c,d,e=_.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&_.extend(!0,a,d),a}function M(a,b,c){for(var d,e,f,g,h=a.contents,i=a.dataTypes;"*"===i[0];)i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function N(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];for(f=k.shift();f;)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}function O(a,b,c,d){var e;if(_.isArray(b))_.each(b,function(b,e){c||yc.test(a)?d(a,e):O(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==_.type(b))d(a,b);else for(e in b)O(a+"["+e+"]",b[e],c,d)}function P(a){return _.isWindow(a)?a:9===a.nodeType&&a.defaultView}var Q=[],R=Q.slice,S=Q.concat,T=Q.push,U=Q.indexOf,V={},W=V.toString,X=V.hasOwnProperty,Y={},Z=a.document,$="2.1.3",_=function(a,b){return new _.fn.init(a,b)},ab=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,bb=/^-ms-/,cb=/-([\da-z])/gi,db=function(a,b){return b.toUpperCase()};_.fn=_.prototype={jquery:$,constructor:_,selector:"",length:0,toArray:function(){return R.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:R.call(this)},pushStack:function(a){var b=_.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return _.each(this,a,b)},map:function(a){return this.pushStack(_.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(R.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:T,sort:Q.sort,splice:Q.splice},_.extend=_.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||_.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(_.isPlainObject(d)||(e=_.isArray(d)))?(e?(e=!1,f=c&&_.isArray(c)?c:[]):f=c&&_.isPlainObject(c)?c:{},g[b]=_.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},_.extend({expando:"jQuery"+($+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===_.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!_.isArray(a)&&a-parseFloat(a)+1>=0},isPlainObject:function(a){return"object"!==_.type(a)||a.nodeType||_.isWindow(a)?!1:a.constructor&&!X.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?V[W.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=_.trim(a),a&&(1===a.indexOf("use strict")?(b=Z.createElement("script"),b.text=a,Z.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(bb,"ms-").replace(cb,db)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,d){var e,f=0,g=a.length,h=c(a);if(d){if(h)for(;g>f&&(e=b.apply(a[f],d),e!==!1);f++);else for(f in a)if(e=b.apply(a[f],d),e===!1)break}else if(h)for(;g>f&&(e=b.call(a[f],f,a[f]),e!==!1);f++);else for(f in a)if(e=b.call(a[f],f,a[f]),e===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(ab,"")},makeArray:function(a,b){var d=b||[];return null!=a&&(c(Object(a))?_.merge(d,"string"==typeof a?[a]:a):T.call(d,a)),d},inArray:function(a,b,c){return null==b?-1:U.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,d){var e,f=0,g=a.length,h=c(a),i=[];if(h)for(;g>f;f++)e=b(a[f],f,d),null!=e&&i.push(e);else for(f in a)e=b(a[f],f,d),null!=e&&i.push(e);return S.apply([],i)},guid:1,proxy:function(a,b){var c,d,e;return"string"==typeof b&&(c=a[b],b=a,a=c),_.isFunction(a)?(d=R.call(arguments,2),e=function(){return a.apply(b||this,d.concat(R.call(arguments)))},e.guid=a.guid=a.guid||_.guid++,e):void 0},now:Date.now,support:Y}),_.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){V["[object "+b+"]"]=b.toLowerCase()});var eb=/*!
+ * Sizzle CSS Selector Engine v2.2.0-pre
+ * http://sizzlejs.com/
+ *
+ * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2014-12-16
+ */
+function(a){function b(a,b,c,d){var e,f,g,h,i,j,l,n,o,p;if((b?b.ownerDocument||b:O)!==G&&F(b),b=b||G,c=c||[],h=b.nodeType,"string"!=typeof a||!a||1!==h&&9!==h&&11!==h)return c;if(!d&&I){if(11!==h&&(e=sb.exec(a)))if(g=e[1]){if(9===h){if(f=b.getElementById(g),!f||!f.parentNode)return c;if(f.id===g)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(g))&&M(b,f)&&f.id===g)return c.push(f),c}else{if(e[2])return $.apply(c,b.getElementsByTagName(a)),c;if((g=e[3])&&v.getElementsByClassName)return $.apply(c,b.getElementsByClassName(g)),c}if(v.qsa&&(!J||!J.test(a))){if(n=l=N,o=b,p=1!==h&&a,1===h&&"object"!==b.nodeName.toLowerCase()){for(j=z(a),(l=b.getAttribute("id"))?n=l.replace(ub,"\\$&"):b.setAttribute("id",n),n="[id='"+n+"'] ",i=j.length;i--;)j[i]=n+m(j[i]);o=tb.test(a)&&k(b.parentNode)||b,p=j.join(",")}if(p)try{return $.apply(c,o.querySelectorAll(p)),c}catch(q){}finally{l||b.removeAttribute("id")}}}return B(a.replace(ib,"$1"),b,c,d)}function c(){function a(c,d){return b.push(c+" ")>w.cacheLength&&delete a[b.shift()],a[c+" "]=d}var b=[];return a}function d(a){return a[N]=!0,a}function e(a){var b=G.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function f(a,b){for(var c=a.split("|"),d=a.length;d--;)w.attrHandle[c[d]]=b}function g(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||V)-(~a.sourceIndex||V);if(d)return d;if(c)for(;c=c.nextSibling;)if(c===b)return-1;return a?1:-1}function h(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function i(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function j(a){return d(function(b){return b=+b,d(function(c,d){for(var e,f=a([],c.length,b),g=f.length;g--;)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function k(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}function l(){}function m(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function n(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=Q++;return b.first?function(b,c,f){for(;b=b[d];)if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[P,f];if(g){for(;b=b[d];)if((1===b.nodeType||e)&&a(b,c,g))return!0}else for(;b=b[d];)if(1===b.nodeType||e){if(i=b[N]||(b[N]={}),(h=i[d])&&h[0]===P&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function o(a){return a.length>1?function(b,c,d){for(var e=a.length;e--;)if(!a[e](b,c,d))return!1;return!0}:a[0]}function p(a,c,d){for(var e=0,f=c.length;f>e;e++)b(a,c[e],d);return d}function q(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function r(a,b,c,e,f,g){return e&&!e[N]&&(e=r(e)),f&&!f[N]&&(f=r(f,g)),d(function(d,g,h,i){var j,k,l,m=[],n=[],o=g.length,r=d||p(b||"*",h.nodeType?[h]:h,[]),s=!a||!d&&b?r:q(r,m,a,h,i),t=c?f||(d?a:o||e)?[]:g:s;if(c&&c(s,t,h,i),e)for(j=q(t,n),e(j,[],h,i),k=j.length;k--;)(l=j[k])&&(t[n[k]]=!(s[n[k]]=l));if(d){if(f||a){if(f){for(j=[],k=t.length;k--;)(l=t[k])&&j.push(s[k]=l);f(null,t=[],j,i)}for(k=t.length;k--;)(l=t[k])&&(j=f?ab(d,l):m[k])>-1&&(d[j]=!(g[j]=l))}}else t=q(t===g?t.splice(o,t.length):t),f?f(null,g,t,i):$.apply(g,t)})}function s(a){for(var b,c,d,e=a.length,f=w.relative[a[0].type],g=f||w.relative[" "],h=f?1:0,i=n(function(a){return a===b},g,!0),j=n(function(a){return ab(b,a)>-1},g,!0),k=[function(a,c,d){var e=!f&&(d||c!==C)||((b=c).nodeType?i(a,c,d):j(a,c,d));return b=null,e}];e>h;h++)if(c=w.relative[a[h].type])k=[n(o(k),c)];else{if(c=w.filter[a[h].type].apply(null,a[h].matches),c[N]){for(d=++h;e>d&&!w.relative[a[d].type];d++);return r(h>1&&o(k),h>1&&m(a.slice(0,h-1).concat({value:" "===a[h-2].type?"*":""})).replace(ib,"$1"),c,d>h&&s(a.slice(h,d)),e>d&&s(a=a.slice(d)),e>d&&m(a))}k.push(c)}return o(k)}function t(a,c){var e=c.length>0,f=a.length>0,g=function(d,g,h,i,j){var k,l,m,n=0,o="0",p=d&&[],r=[],s=C,t=d||f&&w.find.TAG("*",j),u=P+=null==s?1:Math.random()||.1,v=t.length;for(j&&(C=g!==G&&g);o!==v&&null!=(k=t[o]);o++){if(f&&k){for(l=0;m=a[l++];)if(m(k,g,h)){i.push(k);break}j&&(P=u)}e&&((k=!m&&k)&&n--,d&&p.push(k))}if(n+=o,e&&o!==n){for(l=0;m=c[l++];)m(p,r,g,h);if(d){if(n>0)for(;o--;)p[o]||r[o]||(r[o]=Y.call(i));r=q(r)}$.apply(i,r),j&&!d&&r.length>0&&n+c.length>1&&b.uniqueSort(i)}return j&&(P=u,C=s),p};return e?d(g):g}var u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N="sizzle"+1*new Date,O=a.document,P=0,Q=0,R=c(),S=c(),T=c(),U=function(a,b){return a===b&&(E=!0),0},V=1<<31,W={}.hasOwnProperty,X=[],Y=X.pop,Z=X.push,$=X.push,_=X.slice,ab=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},bb="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",cb="[\\x20\\t\\r\\n\\f]",db="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",eb=db.replace("w","w#"),fb="\\["+cb+"*("+db+")(?:"+cb+"*([*^$|!~]?=)"+cb+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+eb+"))|)"+cb+"*\\]",gb=":("+db+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+fb+")*)|.*)\\)|)",hb=new RegExp(cb+"+","g"),ib=new RegExp("^"+cb+"+|((?:^|[^\\\\])(?:\\\\.)*)"+cb+"+$","g"),jb=new RegExp("^"+cb+"*,"+cb+"*"),kb=new RegExp("^"+cb+"*([>+~]|"+cb+")"+cb+"*"),lb=new RegExp("="+cb+"*([^\\]'\"]*?)"+cb+"*\\]","g"),mb=new RegExp(gb),nb=new RegExp("^"+eb+"$"),ob={ID:new RegExp("^#("+db+")"),CLASS:new RegExp("^\\.("+db+")"),TAG:new RegExp("^("+db.replace("w","w*")+")"),ATTR:new RegExp("^"+fb),PSEUDO:new RegExp("^"+gb),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+cb+"*(even|odd|(([+-]|)(\\d*)n|)"+cb+"*(?:([+-]|)"+cb+"*(\\d+)|))"+cb+"*\\)|)","i"),bool:new RegExp("^(?:"+bb+")$","i"),needsContext:new RegExp("^"+cb+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+cb+"*((?:-\\d)?\\d*)"+cb+"*\\)|)(?=[^-]|$)","i")},pb=/^(?:input|select|textarea|button)$/i,qb=/^h\d$/i,rb=/^[^{]+\{\s*\[native \w/,sb=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,tb=/[+~]/,ub=/'|\\/g,vb=new RegExp("\\\\([\\da-f]{1,6}"+cb+"?|("+cb+")|.)","ig"),wb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},xb=function(){F()};try{$.apply(X=_.call(O.childNodes),O.childNodes),X[O.childNodes.length].nodeType}catch(yb){$={apply:X.length?function(a,b){Z.apply(a,_.call(b))}:function(a,b){for(var c=a.length,d=0;a[c++]=b[d++];);a.length=c-1}}}v=b.support={},y=b.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},F=b.setDocument=function(a){var b,c,d=a?a.ownerDocument||a:O;return d!==G&&9===d.nodeType&&d.documentElement?(G=d,H=d.documentElement,c=d.defaultView,c&&c!==c.top&&(c.addEventListener?c.addEventListener("unload",xb,!1):c.attachEvent&&c.attachEvent("onunload",xb)),I=!y(d),v.attributes=e(function(a){return a.className="i",!a.getAttribute("className")}),v.getElementsByTagName=e(function(a){return a.appendChild(d.createComment("")),!a.getElementsByTagName("*").length}),v.getElementsByClassName=rb.test(d.getElementsByClassName),v.getById=e(function(a){return H.appendChild(a).id=N,!d.getElementsByName||!d.getElementsByName(N).length}),v.getById?(w.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&I){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},w.filter.ID=function(a){var b=a.replace(vb,wb);return function(a){return a.getAttribute("id")===b}}):(delete w.find.ID,w.filter.ID=function(a){var b=a.replace(vb,wb);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),w.find.TAG=v.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):v.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){for(;c=f[e++];)1===c.nodeType&&d.push(c);return d}return f},w.find.CLASS=v.getElementsByClassName&&function(a,b){return I?b.getElementsByClassName(a):void 0},K=[],J=[],(v.qsa=rb.test(d.querySelectorAll))&&(e(function(a){H.appendChild(a).innerHTML=" ",a.querySelectorAll("[msallowcapture^='']").length&&J.push("[*^$]="+cb+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||J.push("\\["+cb+"*(?:value|"+bb+")"),a.querySelectorAll("[id~="+N+"-]").length||J.push("~="),a.querySelectorAll(":checked").length||J.push(":checked"),a.querySelectorAll("a#"+N+"+*").length||J.push(".#.+[+~]")}),e(function(a){var b=d.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&J.push("name"+cb+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||J.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),J.push(",.*:")})),(v.matchesSelector=rb.test(L=H.matches||H.webkitMatchesSelector||H.mozMatchesSelector||H.oMatchesSelector||H.msMatchesSelector))&&e(function(a){v.disconnectedMatch=L.call(a,"div"),L.call(a,"[s!='']:x"),K.push("!=",gb)}),J=J.length&&new RegExp(J.join("|")),K=K.length&&new RegExp(K.join("|")),b=rb.test(H.compareDocumentPosition),M=b||rb.test(H.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)for(;b=b.parentNode;)if(b===a)return!0;return!1},U=b?function(a,b){if(a===b)return E=!0,0;var c=!a.compareDocumentPosition-!b.compareDocumentPosition;return c?c:(c=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&c||!v.sortDetached&&b.compareDocumentPosition(a)===c?a===d||a.ownerDocument===O&&M(O,a)?-1:b===d||b.ownerDocument===O&&M(O,b)?1:D?ab(D,a)-ab(D,b):0:4&c?-1:1)}:function(a,b){if(a===b)return E=!0,0;var c,e=0,f=a.parentNode,h=b.parentNode,i=[a],j=[b];if(!f||!h)return a===d?-1:b===d?1:f?-1:h?1:D?ab(D,a)-ab(D,b):0;if(f===h)return g(a,b);for(c=a;c=c.parentNode;)i.unshift(c);for(c=b;c=c.parentNode;)j.unshift(c);for(;i[e]===j[e];)e++;return e?g(i[e],j[e]):i[e]===O?-1:j[e]===O?1:0},d):G},b.matches=function(a,c){return b(a,null,null,c)},b.matchesSelector=function(a,c){if((a.ownerDocument||a)!==G&&F(a),c=c.replace(lb,"='$1']"),!(!v.matchesSelector||!I||K&&K.test(c)||J&&J.test(c)))try{var d=L.call(a,c);if(d||v.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return b(c,G,null,[a]).length>0},b.contains=function(a,b){return(a.ownerDocument||a)!==G&&F(a),M(a,b)},b.attr=function(a,b){(a.ownerDocument||a)!==G&&F(a);var c=w.attrHandle[b.toLowerCase()],d=c&&W.call(w.attrHandle,b.toLowerCase())?c(a,b,!I):void 0;return void 0!==d?d:v.attributes||!I?a.getAttribute(b):(d=a.getAttributeNode(b))&&d.specified?d.value:null},b.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},b.uniqueSort=function(a){var b,c=[],d=0,e=0;if(E=!v.detectDuplicates,D=!v.sortStable&&a.slice(0),a.sort(U),E){for(;b=a[e++];)b===a[e]&&(d=c.push(e));for(;d--;)a.splice(c[d],1)}return D=null,a},x=b.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(1===e||9===e||11===e){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=x(a)}else if(3===e||4===e)return a.nodeValue}else for(;b=a[d++];)c+=x(b);return c},w=b.selectors={cacheLength:50,createPseudo:d,match:ob,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(vb,wb),a[3]=(a[3]||a[4]||a[5]||"").replace(vb,wb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||b.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&b.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return ob.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&mb.test(c)&&(b=z(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(vb,wb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=R[a+" "];return b||(b=new RegExp("(^|"+cb+")"+a+"("+cb+"|$)"))&&R(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,c,d){return function(e){var f=b.attr(e,a);return null==f?"!="===c:c?(f+="","="===c?f===d:"!="===c?f!==d:"^="===c?d&&0===f.indexOf(d):"*="===c?d&&f.indexOf(d)>-1:"$="===c?d&&f.slice(-d.length)===d:"~="===c?(" "+f.replace(hb," ")+" ").indexOf(d)>-1:"|="===c?f===d||f.slice(0,d.length+1)===d+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){for(;p;){for(l=b;l=l[p];)if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){for(k=q[N]||(q[N]={}),j=k[a]||[],n=j[0]===P&&j[1],m=j[0]===P&&j[2],l=n&&q.childNodes[n];l=++n&&l&&l[p]||(m=n=0)||o.pop();)if(1===l.nodeType&&++m&&l===b){k[a]=[P,n,m];break}}else if(s&&(j=(b[N]||(b[N]={}))[a])&&j[0]===P)m=j[1];else for(;(l=++n&&l&&l[p]||(m=n=0)||o.pop())&&((h?l.nodeName.toLowerCase()!==r:1!==l.nodeType)||!++m||(s&&((l[N]||(l[N]={}))[a]=[P,m]),l!==b)););return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,c){var e,f=w.pseudos[a]||w.setFilters[a.toLowerCase()]||b.error("unsupported pseudo: "+a);return f[N]?f(c):f.length>1?(e=[a,a,"",c],w.setFilters.hasOwnProperty(a.toLowerCase())?d(function(a,b){for(var d,e=f(a,c),g=e.length;g--;)d=ab(a,e[g]),a[d]=!(b[d]=e[g])}):function(a){return f(a,0,e)}):f}},pseudos:{not:d(function(a){var b=[],c=[],e=A(a.replace(ib,"$1"));return e[N]?d(function(a,b,c,d){for(var f,g=e(a,null,d,[]),h=a.length;h--;)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,d,f){return b[0]=a,e(b,null,f,c),b[0]=null,!c.pop()}}),has:d(function(a){return function(c){return b(a,c).length>0}}),contains:d(function(a){return a=a.replace(vb,wb),function(b){return(b.textContent||b.innerText||x(b)).indexOf(a)>-1}}),lang:d(function(a){return nb.test(a||"")||b.error("unsupported lang: "+a),a=a.replace(vb,wb).toLowerCase(),function(b){var c;do if(c=I?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===H},focus:function(a){return a===G.activeElement&&(!G.hasFocus||G.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!w.pseudos.empty(a)},header:function(a){return qb.test(a.nodeName)},input:function(a){return pb.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:j(function(){return[0]}),last:j(function(a,b){return[b-1]}),eq:j(function(a,b,c){return[0>c?c+b:c]}),even:j(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:j(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:j(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:j(function(a,b,c){for(var d=0>c?c+b:c;++d2&&"ID"===(g=f[0]).type&&v.getById&&9===b.nodeType&&I&&w.relative[f[1].type]){if(b=(w.find.ID(g.matches[0].replace(vb,wb),b)||[])[0],!b)return c;j&&(b=b.parentNode),a=a.slice(f.shift().value.length)}for(e=ob.needsContext.test(a)?0:f.length;e--&&(g=f[e],!w.relative[h=g.type]);)if((i=w.find[h])&&(d=i(g.matches[0].replace(vb,wb),tb.test(f[0].type)&&k(b.parentNode)||b))){if(f.splice(e,1),a=d.length&&m(f),!a)return $.apply(c,d),c;break}}return(j||A(a,l))(d,b,!I,c,tb.test(a)&&k(b.parentNode)||b),c},v.sortStable=N.split("").sort(U).join("")===N,v.detectDuplicates=!!E,F(),v.sortDetached=e(function(a){return 1&a.compareDocumentPosition(G.createElement("div"))}),e(function(a){return a.innerHTML=" ","#"===a.firstChild.getAttribute("href")})||f("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),v.attributes&&e(function(a){return a.innerHTML=" ",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||f("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),e(function(a){return null==a.getAttribute("disabled")})||f(bb,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),b}(a);_.find=eb,_.expr=eb.selectors,_.expr[":"]=_.expr.pseudos,_.unique=eb.uniqueSort,_.text=eb.getText,_.isXMLDoc=eb.isXML,_.contains=eb.contains;var fb=_.expr.match.needsContext,gb=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,hb=/^.[^:#\[\.,]*$/;_.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?_.find.matchesSelector(d,a)?[d]:[]:_.find.matches(a,_.grep(b,function(a){return 1===a.nodeType}))},_.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(_(a).filter(function(){for(b=0;c>b;b++)if(_.contains(e[b],this))return!0}));for(b=0;c>b;b++)_.find(a,e[b],d);return d=this.pushStack(c>1?_.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(d(this,a||[],!1))},not:function(a){return this.pushStack(d(this,a||[],!0))},is:function(a){return!!d(this,"string"==typeof a&&fb.test(a)?_(a):a||[],!1).length}});var ib,jb=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,kb=_.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:jb.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||ib).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof _?b[0]:b,_.merge(this,_.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:Z,!0)),gb.test(c[1])&&_.isPlainObject(b))for(c in b)_.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=Z.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=Z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):_.isFunction(a)?"undefined"!=typeof ib.ready?ib.ready(a):a(_):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),_.makeArray(a,this))};kb.prototype=_.fn,ib=_(Z);var lb=/^(?:parents|prev(?:Until|All))/,mb={children:!0,contents:!0,next:!0,prev:!0};_.extend({dir:function(a,b,c){for(var d=[],e=void 0!==c;(a=a[b])&&9!==a.nodeType;)if(1===a.nodeType){if(e&&_(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),_.fn.extend({has:function(a){var b=_(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(_.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=fb.test(a)||"string"!=typeof a?_(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&_.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?_.unique(f):f)},index:function(a){return a?"string"==typeof a?U.call(_(a),this[0]):U.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(_.unique(_.merge(this.get(),_(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}}),_.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return _.dir(a,"parentNode")},parentsUntil:function(a,b,c){return _.dir(a,"parentNode",c)},next:function(a){return e(a,"nextSibling")},prev:function(a){return e(a,"previousSibling")},nextAll:function(a){return _.dir(a,"nextSibling")},prevAll:function(a){return _.dir(a,"previousSibling")},nextUntil:function(a,b,c){return _.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return _.dir(a,"previousSibling",c)},siblings:function(a){return _.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return _.sibling(a.firstChild)},contents:function(a){return a.contentDocument||_.merge([],a.childNodes)}},function(a,b){_.fn[a]=function(c,d){var e=_.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=_.filter(d,e)),this.length>1&&(mb[a]||_.unique(e),lb.test(a)&&e.reverse()),this.pushStack(e)}});var nb=/\S+/g,ob={};_.Callbacks=function(a){a="string"==typeof a?ob[a]||f(a):_.extend({},a);var b,c,d,e,g,h,i=[],j=!a.once&&[],k=function(f){for(b=a.memory&&f,c=!0,h=e||0,e=0,g=i.length,d=!0;i&&g>h;h++)if(i[h].apply(f[0],f[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,i&&(j?j.length&&k(j.shift()):b?i=[]:l.disable())},l={add:function(){if(i){var c=i.length;!function f(b){_.each(b,function(b,c){var d=_.type(c);"function"===d?a.unique&&l.has(c)||i.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),d?g=i.length:b&&(e=c,k(b))}return this},remove:function(){return i&&_.each(arguments,function(a,b){for(var c;(c=_.inArray(b,i,c))>-1;)i.splice(c,1),d&&(g>=c&&g--,h>=c&&h--)}),this},has:function(a){return a?_.inArray(a,i)>-1:!(!i||!i.length)},empty:function(){return i=[],g=0,this},disable:function(){return i=j=b=void 0,this},disabled:function(){return!i},lock:function(){return j=void 0,b||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return!i||c&&!j||(b=b||[],b=[a,b.slice?b.slice():b],d?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!c}};return l},_.extend({Deferred:function(a){var b=[["resolve","done",_.Callbacks("once memory"),"resolved"],["reject","fail",_.Callbacks("once memory"),"rejected"],["notify","progress",_.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return _.Deferred(function(c){_.each(b,function(b,f){var g=_.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&_.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?_.extend(a,d):d}},e={};return d.pipe=d.then,_.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b,c,d,e=0,f=R.call(arguments),g=f.length,h=1!==g||a&&_.isFunction(a.promise)?g:0,i=1===h?a:_.Deferred(),j=function(a,c,d){return function(e){c[a]=this,d[a]=arguments.length>1?R.call(arguments):e,d===b?i.notifyWith(c,d):--h||i.resolveWith(c,d)}};if(g>1)for(b=new Array(g),c=new Array(g),d=new Array(g);g>e;e++)f[e]&&_.isFunction(f[e].promise)?f[e].promise().done(j(e,d,f)).fail(i.reject).progress(j(e,c,b)):--h;return h||i.resolveWith(d,f),i.promise()}});var pb;_.fn.ready=function(a){return _.ready.promise().done(a),this},_.extend({isReady:!1,readyWait:1,holdReady:function(a){a?_.readyWait++:_.ready(!0)},ready:function(a){(a===!0?--_.readyWait:_.isReady)||(_.isReady=!0,a!==!0&&--_.readyWait>0||(pb.resolveWith(Z,[_]),_.fn.triggerHandler&&(_(Z).triggerHandler("ready"),_(Z).off("ready"))))}}),_.ready.promise=function(b){return pb||(pb=_.Deferred(),"complete"===Z.readyState?setTimeout(_.ready):(Z.addEventListener("DOMContentLoaded",g,!1),a.addEventListener("load",g,!1))),pb.promise(b)},_.ready.promise();var qb=_.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===_.type(c)){e=!0;for(h in c)_.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,_.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(_(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};_.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType},h.uid=1,h.accepts=_.acceptData,h.prototype={key:function(a){if(!h.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=h.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,_.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(_.isEmptyObject(f))_.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,_.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{_.isArray(b)?d=b.concat(b.map(_.camelCase)):(e=_.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(nb)||[])),c=d.length;for(;c--;)delete g[d[c]]}},hasData:function(a){return!_.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var rb=new h,sb=new h,tb=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,ub=/([A-Z])/g;_.extend({hasData:function(a){return sb.hasData(a)||rb.hasData(a)},data:function(a,b,c){return sb.access(a,b,c)},removeData:function(a,b){sb.remove(a,b)},_data:function(a,b,c){return rb.access(a,b,c)},_removeData:function(a,b){rb.remove(a,b)}}),_.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=sb.get(f),1===f.nodeType&&!rb.get(f,"hasDataAttrs"))){for(c=g.length;c--;)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=_.camelCase(d.slice(5)),i(f,d,e[d])));rb.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){sb.set(this,a)}):qb(this,function(b){var c,d=_.camelCase(a);if(f&&void 0===b){if(c=sb.get(f,a),void 0!==c)return c;if(c=sb.get(f,d),void 0!==c)return c;if(c=i(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=sb.get(this,d);sb.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&sb.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){sb.remove(this,a)})}}),_.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=rb.get(a,b),c&&(!d||_.isArray(c)?d=rb.access(a,b,_.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=_.queue(a,b),d=c.length,e=c.shift(),f=_._queueHooks(a,b),g=function(){_.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return rb.get(a,c)||rb.access(a,c,{empty:_.Callbacks("once memory").add(function(){rb.remove(a,[b+"queue",c])})})}}),_.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthx",Y.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var zb="undefined";Y.focusinBubbles="onfocusin"in a;var Ab=/^key/,Bb=/^(?:mouse|pointer|contextmenu)|click/,Cb=/^(?:focusinfocus|focusoutblur)$/,Db=/^([^.]*)(?:\.(.+)|)$/;_.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=rb.get(a);if(q)for(c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=_.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return typeof _!==zb&&_.event.triggered!==b.type?_.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(nb)||[""],j=b.length;j--;)h=Db.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n&&(l=_.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=_.event.special[n]||{},k=_.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&_.expr.match.needsContext.test(e),namespace:o.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),_.event.global[n]=!0)},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=rb.hasData(a)&&rb.get(a);if(q&&(i=q.events)){for(b=(b||"").match(nb)||[""],j=b.length;j--;)if(h=Db.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){for(l=_.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;f--;)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||_.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)_.event.remove(a,n+b[j],c,d,!0);_.isEmptyObject(i)&&(delete q.handle,rb.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,j,k,l,m=[d||Z],n=X.call(b,"type")?b.type:b,o=X.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||Z,3!==d.nodeType&&8!==d.nodeType&&!Cb.test(n+_.event.triggered)&&(n.indexOf(".")>=0&&(o=n.split("."),n=o.shift(),o.sort()),j=n.indexOf(":")<0&&"on"+n,b=b[_.expando]?b:new _.Event(n,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=o.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:_.makeArray(c,[b]),l=_.event.special[n]||{},e||!l.trigger||l.trigger.apply(d,c)!==!1)){if(!e&&!l.noBubble&&!_.isWindow(d)){for(i=l.delegateType||n,Cb.test(i+n)||(g=g.parentNode);g;g=g.parentNode)m.push(g),h=g;
+h===(d.ownerDocument||Z)&&m.push(h.defaultView||h.parentWindow||a)}for(f=0;(g=m[f++])&&!b.isPropagationStopped();)b.type=f>1?i:l.bindType||n,k=(rb.get(g,"events")||{})[b.type]&&rb.get(g,"handle"),k&&k.apply(g,c),k=j&&g[j],k&&k.apply&&_.acceptData(g)&&(b.result=k.apply(g,c),b.result===!1&&b.preventDefault());return b.type=n,e||b.isDefaultPrevented()||l._default&&l._default.apply(m.pop(),c)!==!1||!_.acceptData(d)||j&&_.isFunction(d[n])&&!_.isWindow(d)&&(h=d[j],h&&(d[j]=null),_.event.triggered=n,d[n](),_.event.triggered=void 0,h&&(d[j]=h)),b.result}},dispatch:function(a){a=_.event.fix(a);var b,c,d,e,f,g=[],h=R.call(arguments),i=(rb.get(this,"events")||{})[a.type]||[],j=_.event.special[a.type]||{};if(h[0]=a,a.delegateTarget=this,!j.preDispatch||j.preDispatch.call(this,a)!==!1){for(g=_.event.handlers.call(this,a,i),b=0;(e=g[b++])&&!a.isPropagationStopped();)for(a.currentTarget=e.elem,c=0;(f=e.handlers[c++])&&!a.isImmediatePropagationStopped();)(!a.namespace_re||a.namespace_re.test(f.namespace))&&(a.handleObj=f,a.data=f.data,d=((_.event.special[f.origType]||{}).handle||f.handler).apply(e.elem,h),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()));return j.postDispatch&&j.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?_(e,this).index(i)>=0:_.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,Fb=/<([\w:]+)/,Gb=/<|?\w+;/,Hb=/<(?:script|style|link)/i,Ib=/checked\s*(?:[^=]|=\s*.checked.)/i,Jb=/^$|\/(?:java|ecma)script/i,Kb=/^true\/(.*)/,Lb=/^\s*\s*$/g,Mb={option:[1,""," "],thead:[1,""],col:[2,""],tr:[2,""],td:[3,""],_default:[0,"",""]};Mb.optgroup=Mb.option,Mb.tbody=Mb.tfoot=Mb.colgroup=Mb.caption=Mb.thead,Mb.th=Mb.td,_.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=_.contains(a.ownerDocument,a);if(!(Y.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||_.isXMLDoc(a)))for(g=r(h),f=r(a),d=0,e=f.length;e>d;d++)s(f[d],g[d]);if(b)if(c)for(f=f||r(a),g=g||r(h),d=0,e=f.length;e>d;d++)q(f[d],g[d]);else q(a,h);return g=r(h,"script"),g.length>0&&p(g,!i&&r(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,n=a.length;n>m;m++)if(e=a[m],e||0===e)if("object"===_.type(e))_.merge(l,e.nodeType?[e]:e);else if(Gb.test(e)){for(f=f||k.appendChild(b.createElement("div")),g=(Fb.exec(e)||["",""])[1].toLowerCase(),h=Mb[g]||Mb._default,f.innerHTML=h[1]+e.replace(Eb,"<$1>$2>")+h[2],j=h[0];j--;)f=f.lastChild;_.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));for(k.textContent="",m=0;e=l[m++];)if((!d||-1===_.inArray(e,d))&&(i=_.contains(e.ownerDocument,e),f=r(k.appendChild(e),"script"),i&&p(f),c))for(j=0;e=f[j++];)Jb.test(e.type||"")&&c.push(e);return k},cleanData:function(a){for(var b,c,d,e,f=_.event.special,g=0;void 0!==(c=a[g]);g++){if(_.acceptData(c)&&(e=c[rb.expando],e&&(b=rb.cache[e]))){if(b.events)for(d in b.events)f[d]?_.event.remove(c,d):_.removeEvent(c,d,b.handle);rb.cache[e]&&delete rb.cache[e]}delete sb.cache[c[sb.expando]]}}}),_.fn.extend({text:function(a){return qb(this,function(a){return void 0===a?_.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=m(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=m(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?_.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||_.cleanData(r(c)),c.parentNode&&(b&&_.contains(c.ownerDocument,c)&&p(r(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(_.cleanData(r(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return _.clone(this,a,b)})},html:function(a){return qb(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!Hb.test(a)&&!Mb[(Fb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Eb,"<$1>$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(_.cleanData(r(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,_.cleanData(r(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=S.apply([],a);var c,d,e,f,g,h,i=0,j=this.length,k=this,l=j-1,m=a[0],p=_.isFunction(m);if(p||j>1&&"string"==typeof m&&!Y.checkClone&&Ib.test(m))return this.each(function(c){var d=k.eq(c);p&&(a[0]=m.call(this,c,d.html())),d.domManip(a,b)});if(j&&(c=_.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(e=_.map(r(c,"script"),n),f=e.length;j>i;i++)g=c,i!==l&&(g=_.clone(g,!0,!0),f&&_.merge(e,r(g,"script"))),b.call(this[i],g,i);if(f)for(h=e[e.length-1].ownerDocument,_.map(e,o),i=0;f>i;i++)g=e[i],Jb.test(g.type||"")&&!rb.access(g,"globalEval")&&_.contains(h,g)&&(g.src?_._evalUrl&&_._evalUrl(g.src):_.globalEval(g.textContent.replace(Lb,"")))}return this}}),_.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){_.fn[a]=function(a){for(var c,d=[],e=_(a),f=e.length-1,g=0;f>=g;g++)c=g===f?this:this.clone(!0),_(e[g])[b](c),T.apply(d,c.get());return this.pushStack(d)}});var Nb,Ob={},Pb=/^margin/,Qb=new RegExp("^("+vb+")(?!px)[a-z%]+$","i"),Rb=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)};!function(){function b(){g.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",g.innerHTML="",e.appendChild(f);var b=a.getComputedStyle(g,null);c="1%"!==b.top,d="4px"===b.width,e.removeChild(f)}var c,d,e=Z.documentElement,f=Z.createElement("div"),g=Z.createElement("div");g.style&&(g.style.backgroundClip="content-box",g.cloneNode(!0).style.backgroundClip="",Y.clearCloneStyle="content-box"===g.style.backgroundClip,f.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute",f.appendChild(g),a.getComputedStyle&&_.extend(Y,{pixelPosition:function(){return b(),c},boxSizingReliable:function(){return null==d&&b(),d},reliableMarginRight:function(){var b,c=g.appendChild(Z.createElement("div"));return c.style.cssText=g.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",g.style.width="1px",e.appendChild(f),b=!parseFloat(a.getComputedStyle(c,null).marginRight),e.removeChild(f),g.removeChild(c),b}}))}(),_.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Sb=/^(none|table(?!-c[ea]).+)/,Tb=new RegExp("^("+vb+")(.*)$","i"),Ub=new RegExp("^([+-])=("+vb+")","i"),Vb={position:"absolute",visibility:"hidden",display:"block"},Wb={letterSpacing:"0",fontWeight:"400"},Xb=["Webkit","O","Moz","ms"];_.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=v(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=_.camelCase(b),i=a.style;return b=_.cssProps[h]||(_.cssProps[h]=x(i,h)),g=_.cssHooks[b]||_.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=Ub.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(_.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||_.cssNumber[h]||(c+="px"),Y.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=_.camelCase(b);return b=_.cssProps[h]||(_.cssProps[h]=x(a.style,h)),g=_.cssHooks[b]||_.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=v(a,b,d)),"normal"===e&&b in Wb&&(e=Wb[b]),""===c||c?(f=parseFloat(e),c===!0||_.isNumeric(f)?f||0:e):e}}),_.each(["height","width"],function(a,b){_.cssHooks[b]={get:function(a,c,d){return c?Sb.test(_.css(a,"display"))&&0===a.offsetWidth?_.swap(a,Vb,function(){return A(a,b,d)}):A(a,b,d):void 0},set:function(a,c,d){var e=d&&Rb(a);return y(a,c,d?z(a,b,d,"border-box"===_.css(a,"boxSizing",!1,e),e):0)}}}),_.cssHooks.marginRight=w(Y.reliableMarginRight,function(a,b){return b?_.swap(a,{display:"inline-block"},v,[a,"marginRight"]):void 0}),_.each({margin:"",padding:"",border:"Width"},function(a,b){_.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+wb[d]+b]=f[d]||f[d-2]||f[0];return e}},Pb.test(a)||(_.cssHooks[a+b].set=y)}),_.fn.extend({css:function(a,b){return qb(this,function(a,b,c){var d,e,f={},g=0;if(_.isArray(b)){for(d=Rb(a),e=b.length;e>g;g++)f[b[g]]=_.css(a,b[g],!1,d);return f}return void 0!==c?_.style(a,b,c):_.css(a,b)},a,b,arguments.length>1)},show:function(){return B(this,!0)},hide:function(){return B(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){xb(this)?_(this).show():_(this).hide()})}}),_.Tween=C,C.prototype={constructor:C,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(_.cssNumber[c]?"":"px")},cur:function(){var a=C.propHooks[this.prop];return a&&a.get?a.get(this):C.propHooks._default.get(this)},run:function(a){var b,c=C.propHooks[this.prop];return this.pos=b=this.options.duration?_.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):C.propHooks._default.set(this),this}},C.prototype.init.prototype=C.prototype,C.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=_.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){_.fx.step[a.prop]?_.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[_.cssProps[a.prop]]||_.cssHooks[a.prop])?_.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},C.propHooks.scrollTop=C.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},_.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},_.fx=C.prototype.init,_.fx.step={};var Yb,Zb,$b=/^(?:toggle|show|hide)$/,_b=new RegExp("^(?:([+-])=|)("+vb+")([a-z%]*)$","i"),ac=/queueHooks$/,bc=[G],cc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=_b.exec(b),f=e&&e[3]||(_.cssNumber[a]?"":"px"),g=(_.cssNumber[a]||"px"!==f&&+d)&&_b.exec(_.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,_.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};_.Animation=_.extend(I,{tweener:function(a,b){_.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],cc[c]=cc[c]||[],cc[c].unshift(b)},prefilter:function(a,b){b?bc.unshift(a):bc.push(a)}}),_.speed=function(a,b,c){var d=a&&"object"==typeof a?_.extend({},a):{complete:c||!c&&b||_.isFunction(a)&&a,duration:a,easing:c&&b||b&&!_.isFunction(b)&&b};return d.duration=_.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in _.fx.speeds?_.fx.speeds[d.duration]:_.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){_.isFunction(d.old)&&d.old.call(this),d.queue&&_.dequeue(this,d.queue)},d},_.fn.extend({fadeTo:function(a,b,c,d){return this.filter(xb).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=_.isEmptyObject(a),f=_.speed(b,c,d),g=function(){var b=I(this,_.extend({},a),f);(e||rb.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=_.timers,g=rb.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&ac.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&_.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=rb.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=_.timers,g=d?d.length:0;for(c.finish=!0,_.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),_.each(["toggle","show","hide"],function(a,b){var c=_.fn[b];_.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(E(b,!0),a,d,e)}}),_.each({slideDown:E("show"),slideUp:E("hide"),slideToggle:E("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){_.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),_.timers=[],_.fx.tick=function(){var a,b=0,c=_.timers;for(Yb=_.now();b1)},removeAttr:function(a){return this.each(function(){_.removeAttr(this,a)})}}),_.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===zb?_.prop(a,b,c):(1===f&&_.isXMLDoc(a)||(b=b.toLowerCase(),d=_.attrHooks[b]||(_.expr.match.bool.test(b)?ec:dc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=_.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void _.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(nb);if(f&&1===a.nodeType)for(;c=f[e++];)d=_.propFix[c]||c,_.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!Y.radioValue&&"radio"===b&&_.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),ec={set:function(a,b,c){return b===!1?_.removeAttr(a,c):a.setAttribute(c,c),c}},_.each(_.expr.match.bool.source.match(/\w+/g),function(a,b){var c=fc[b]||_.find.attr;fc[b]=function(a,b,d){var e,f;return d||(f=fc[b],fc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,fc[b]=f),e}});var gc=/^(?:input|select|textarea|button)$/i;_.fn.extend({prop:function(a,b){return qb(this,_.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[_.propFix[a]||a]})}}),_.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!_.isXMLDoc(a),f&&(b=_.propFix[b]||b,e=_.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){return a.hasAttribute("tabindex")||gc.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),Y.optSelected||(_.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),_.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){_.propFix[this.toLowerCase()]=this});var hc=/[\t\r\n\f]/g;_.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(_.isFunction(a))return this.each(function(b){_(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(nb)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(hc," "):" ")){for(f=0;e=b[f++];)d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=_.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(_.isFunction(a))return this.each(function(b){_(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(nb)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(hc," "):"")){for(f=0;e=b[f++];)for(;d.indexOf(" "+e+" ")>=0;)d=d.replace(" "+e+" "," ");g=a?_.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(_.isFunction(a)?function(c){_(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c)for(var b,d=0,e=_(this),f=a.match(nb)||[];b=f[d++];)e.hasClass(b)?e.removeClass(b):e.addClass(b);else(c===zb||"boolean"===c)&&(this.className&&rb.set(this,"__className__",this.className),this.className=this.className||a===!1?"":rb.get(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(hc," ").indexOf(b)>=0)return!0;return!1}});var ic=/\r/g;_.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=_.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,_(this).val()):a,null==e?e="":"number"==typeof e?e+="":_.isArray(e)&&(e=_.map(e,function(a){return null==a?"":a+""})),b=_.valHooks[this.type]||_.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=_.valHooks[e.type]||_.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(ic,""):null==c?"":c)}}}),_.extend({valHooks:{option:{get:function(a){var b=_.find.attr(a,"value");return null!=b?b:_.trim(_.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(Y.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&_.nodeName(c.parentNode,"optgroup"))){if(b=_(c).val(),f)return b;g.push(b)}return g},set:function(a,b){for(var c,d,e=a.options,f=_.makeArray(b),g=e.length;g--;)d=e[g],(d.selected=_.inArray(d.value,f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),_.each(["radio","checkbox"],function(){_.valHooks[this]={set:function(a,b){return _.isArray(b)?a.checked=_.inArray(_(a).val(),b)>=0:void 0}},Y.checkOn||(_.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),_.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){_.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),_.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var jc=_.now(),kc=/\?/;_.parseJSON=function(a){return JSON.parse(a+"")},_.parseXML=function(a){var b,c;if(!a||"string"!=typeof a)return null;try{c=new DOMParser,b=c.parseFromString(a,"text/xml")}catch(d){b=void 0}return(!b||b.getElementsByTagName("parsererror").length)&&_.error("Invalid XML: "+a),b};var lc=/#.*$/,mc=/([?&])_=[^&]*/,nc=/^(.*?):[ \t]*([^\r\n]*)$/gm,oc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,pc=/^(?:GET|HEAD)$/,qc=/^\/\//,rc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,sc={},tc={},uc="*/".concat("*"),vc=a.location.href,wc=rc.exec(vc.toLowerCase())||[];_.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:vc,type:"GET",isLocal:oc.test(wc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":uc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":_.parseJSON,"text xml":_.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?L(L(a,_.ajaxSettings),b):L(_.ajaxSettings,a)},ajaxPrefilter:J(sc),ajaxTransport:J(tc),ajax:function(a,b){function c(a,b,c,g){var i,k,r,s,u,w=b;2!==t&&(t=2,h&&clearTimeout(h),d=void 0,f=g||"",v.readyState=a>0?4:0,i=a>=200&&300>a||304===a,c&&(s=M(l,v,c)),s=N(l,s,v,i),i?(l.ifModified&&(u=v.getResponseHeader("Last-Modified"),u&&(_.lastModified[e]=u),u=v.getResponseHeader("etag"),u&&(_.etag[e]=u)),204===a||"HEAD"===l.type?w="nocontent":304===a?w="notmodified":(w=s.state,k=s.data,r=s.error,i=!r)):(r=w,(a||!w)&&(w="error",0>a&&(a=0))),v.status=a,v.statusText=(b||w)+"",i?o.resolveWith(m,[k,w,v]):o.rejectWith(m,[v,w,r]),v.statusCode(q),q=void 0,j&&n.trigger(i?"ajaxSuccess":"ajaxError",[v,l,i?k:r]),p.fireWith(m,[v,w]),j&&(n.trigger("ajaxComplete",[v,l]),--_.active||_.event.trigger("ajaxStop")))}"object"==typeof a&&(b=a,a=void 0),b=b||{};var d,e,f,g,h,i,j,k,l=_.ajaxSetup({},b),m=l.context||l,n=l.context&&(m.nodeType||m.jquery)?_(m):_.event,o=_.Deferred(),p=_.Callbacks("once memory"),q=l.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!g)for(g={};b=nc.exec(f);)g[b[1].toLowerCase()]=b[2];b=g[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(l.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return d&&d.abort(b),c(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,l.url=((a||l.url||vc)+"").replace(lc,"").replace(qc,wc[1]+"//"),l.type=b.method||b.type||l.method||l.type,l.dataTypes=_.trim(l.dataType||"*").toLowerCase().match(nb)||[""],null==l.crossDomain&&(i=rc.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]===wc[1]&&i[2]===wc[2]&&(i[3]||("http:"===i[1]?"80":"443"))===(wc[3]||("http:"===wc[1]?"80":"443")))),l.data&&l.processData&&"string"!=typeof l.data&&(l.data=_.param(l.data,l.traditional)),K(sc,l,b,v),2===t)return v;j=_.event&&l.global,j&&0===_.active++&&_.event.trigger("ajaxStart"),l.type=l.type.toUpperCase(),l.hasContent=!pc.test(l.type),e=l.url,l.hasContent||(l.data&&(e=l.url+=(kc.test(e)?"&":"?")+l.data,delete l.data),l.cache===!1&&(l.url=mc.test(e)?e.replace(mc,"$1_="+jc++):e+(kc.test(e)?"&":"?")+"_="+jc++)),l.ifModified&&(_.lastModified[e]&&v.setRequestHeader("If-Modified-Since",_.lastModified[e]),_.etag[e]&&v.setRequestHeader("If-None-Match",_.etag[e])),(l.data&&l.hasContent&&l.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",l.contentType),v.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+("*"!==l.dataTypes[0]?", "+uc+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)v.setRequestHeader(k,l.headers[k]);if(l.beforeSend&&(l.beforeSend.call(m,v,l)===!1||2===t))return v.abort();u="abort";for(k in{success:1,error:1,complete:1})v[k](l[k]);if(d=K(tc,l,b,v)){v.readyState=1,j&&n.trigger("ajaxSend",[v,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){v.abort("timeout")},l.timeout));try{t=1,d.send(r,c)}catch(w){if(!(2>t))throw w;c(-1,w)}}else c(-1,"No Transport");return v},getJSON:function(a,b,c){return _.get(a,b,c,"json")},getScript:function(a,b){return _.get(a,void 0,b,"script")}}),_.each(["get","post"],function(a,b){_[b]=function(a,c,d,e){return _.isFunction(c)&&(e=e||d,d=c,c=void 0),_.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),_._evalUrl=function(a){return _.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},_.fn.extend({wrapAll:function(a){var b;return _.isFunction(a)?this.each(function(b){_(this).wrapAll(a.call(this,b))}):(this[0]&&(b=_(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){for(var a=this;a.firstElementChild;)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return this.each(_.isFunction(a)?function(b){_(this).wrapInner(a.call(this,b))}:function(){var b=_(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=_.isFunction(a);return this.each(function(c){_(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){_.nodeName(this,"body")||_(this).replaceWith(this.childNodes)}).end()}}),_.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0},_.expr.filters.visible=function(a){return!_.expr.filters.hidden(a)};var xc=/%20/g,yc=/\[\]$/,zc=/\r?\n/g,Ac=/^(?:submit|button|image|reset|file)$/i,Bc=/^(?:input|select|textarea|keygen)/i;_.param=function(a,b){var c,d=[],e=function(a,b){b=_.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=_.ajaxSettings&&_.ajaxSettings.traditional),_.isArray(a)||a.jquery&&!_.isPlainObject(a))_.each(a,function(){e(this.name,this.value)});else for(c in a)O(c,a[c],b,e);
+return d.join("&").replace(xc,"+")},_.fn.extend({serialize:function(){return _.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=_.prop(this,"elements");return a?_.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!_(this).is(":disabled")&&Bc.test(this.nodeName)&&!Ac.test(a)&&(this.checked||!yb.test(a))}).map(function(a,b){var c=_(this).val();return null==c?null:_.isArray(c)?_.map(c,function(a){return{name:b.name,value:a.replace(zc,"\r\n")}}):{name:b.name,value:c.replace(zc,"\r\n")}}).get()}}),_.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Cc=0,Dc={},Ec={0:200,1223:204},Fc=_.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Dc)Dc[a]()}),Y.cors=!!Fc&&"withCredentials"in Fc,Y.ajax=Fc=!!Fc,_.ajaxTransport(function(a){var b;return Y.cors||Fc&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Cc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)f.setRequestHeader(e,c[e]);b=function(a){return function(){b&&(delete Dc[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Ec[f.status]||f.status,f.statusText,"string"==typeof f.responseText?{text:f.responseText}:void 0,f.getAllResponseHeaders()))}},f.onload=b(),f.onerror=b("error"),b=Dc[g]=b("abort");try{f.send(a.hasContent&&a.data||null)}catch(h){if(b)throw h}},abort:function(){b&&b()}}:void 0}),_.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return _.globalEval(a),a}}}),_.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),_.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(d,e){b=_("
+ ```
+
+ - For [ExtJs](http://www.sencha.com/) v1.8+
+
+ ``` html
+
+ ```
+
+ - For [jQuery](http://jquery.com/) v1.3+
+
+ ``` html
+
+ ```
+
+ - For [Mootools](http://mootools.net/) v1.3+
+
+ ``` html
+
+ ```
+
+ - For [Right.js](http://rightjs.org/) v2.2+
+
+ ``` html
+
+ ```
+
+ - For [Zepto](http://zeptojs.com/) v0.5+
+
+ ``` html
+
+ ```
+
+ - For everything else
+
+ ``` html
+
+ ```
+
+> Note: If you want to only support HTML5 Browsers and not HTML4 Browsers (so no hash fallback support) then just change the `/html4+html5/` part in the urls to just `/html5/`. See [Why supporting HTML4 browsers could be either good or bad based on my app's use cases](https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling)
+
+
+## Get Updates
+
+- For Commit RSS/Atom Updates:
+ - You can subscribe via the [GitHub Commit Atom Feed](http://feeds.feedburner.com/historyjs)
+- For GitHub News Feed Updates:
+ - You can click the "watch" button up the top right of History.js's [GitHub Project Page](https://github.com/browserstate/history.js)
+
+
+## Get Support
+
+- History.js is maintained by people like you. If you find a bug, report it to the [GitHub Issue Tracker](https://github.com/browserstate/history.js/issues). If you've fixed a bug submit a [Pull Request](https://github.com/browserstate/history.js/pulls) and add your fork to the [Network Wiki Page](https://github.com/browserstate/history.js/wiki/Network).
+
+- If you would like paid support and trainings, or have job offers, then refer to the [Network Wiki Page](https://github.com/browserstate/history.js/wiki/Network). If you are qualified with History.js, then be sure to add your details to that page too.
+
+- If your company uses History.js on your projects, and would like to see it grow and prosper (better documentation, bugfixes, upgrades, maintenance, etc.) and would love to become a corporate sponsor then do email sponsor@bevry.me
+
+- If you would like free support for History.js, then [post your question](http://stackoverflow.com/questions/ask) on [Stackoverflow](http://stackoverflow.com/about) and be sure to use the `history.js` tag when asking your question.
+
+- If you've created a website that uses History.js, or know of one, be sure to add it to the [Showcase Wiki Page](https://github.com/browserstate/history.js/wiki/Showcase).
+
+- If you'd love to +1 or like this project, then be sure to tweet about it and click the "watch" button up the top of its [Project Page](https://github.com/browserstate/history.js).
+
+- For anything else, refer to the [History.js GitHub Wiki Site](https://github.com/browserstate/history.js/wiki).
+
+Thanks! every bit of help really does make a difference!
+
+
+## Browsers: Tested and Working In
+
+### HTML5 Browsers
+
+- Firefox 4+
+- Chrome 8+
+- Opera 11.5+
+- Safari 5.0+
+- Safari iOS 4.3+
+
+### HTML4 Browsers
+
+- IE 6, 7, 8, 9, (10)
+- Firefox 3
+- Opera 10, 11.0
+- Safari 4
+- Safari iOS 4.2, 4.1, 4.0, 3.2
+
+
+## Exposed API
+
+### Functions
+
+#### States
+- `History.pushState(data,title,url)` Pushes a new state to the browser; `data` can be null or an object, `title` can be null or a string, `url` must be a string
+- `History.replaceState(data,title,url)` Replaces the existing state with a new state to the browser; `data` can be null or an object, `title` can be null or a string, `url` must be a string
+- `History.getState()` Gets the current state of the browser, returns an object with `data`, `title` and `url`
+- `History.getStateByIndex` Gets a state by the index
+- `History.getCurrentIndex` Gets the current index
+- `History.getHash()` Gets the current hash of the browser
+
+#### Adapter
+- `History.Adapter.bind(element,event,callback)` A framework independent event binder, you may either use this or your framework's native event binder.
+- `History.Adapter.trigger(element,event)` A framework independent event trigger, you may either use this or your framework's native event trigger.
+- `History.Adapter.onDomLoad(callback)` A framework independent onDomLoad binder, you may either use this or your framework's native onDomLoad binder.
+
+#### Navigation
+- `History.back()` Go back once through the history (same as hitting the browser's back button)
+- `History.forward()` Go forward once through the history (same as hitting the browser's forward button)
+- `History.go(X)` If X is negative go back through history X times, if X is positive go forwards through history X times
+
+#### Debug
+- `History.log(...)` Logs messages to the console, the log element, and fallbacks to alert if neither of those two exist
+- `History.debug(...)` Same as `History.log` but only runs if `History.debug.enable === true`
+
+
+
+### Options
+
+- `History.options.hashChangeInterval` How long should the interval be before hashchange checks
+- `History.options.safariPollInterval` How long should the interval be before safari poll checks
+- `History.options.doubleCheckInterval` How long should the interval be before we perform a double check
+- `History.options.disableSuid` Force History not to append suid
+- `History.options.storeInterval` How long should we wait between store calls
+- `History.options.busyDelay` How long should we wait between busy events
+- `History.options.debug` If true will enable debug messages to be logged
+- `History.options.initialTitle` What is the title of the initial state
+- `History.options.html4Mode` If true, will force HTMl4 mode (hashtags)
+- `History.options.delayInit` Want to override default options and call init manually.
+
+### Events
+
+- `window.onstatechange` Fired when the state of the page changes (does not include hash changes)
+- `window.onanchorchange` Fired when the anchor of the page changes (does not include state hashes)
+
+
+## Known Issues
+- Opera 11 fails to create history entries when under stressful loads (events fire perfectly, just the history events fail) - there is nothing we can do about this
+- Mercury iOS fails to apply url changes (hashes and HTML5 History API states) - there is nothing we can do about this
+
+
+## Notes on Compatibility
+
+- History.js **solves** the following browser bugs:
+ - HTML5 Browsers
+ - Chrome 8 sometimes does not contain the correct state data when traversing back to the initial state
+ - Safari 5, Safari iOS 4 and Firefox 3 and 4 do not fire the `onhashchange` event when the page is loaded with a hash
+ - Safari 5 and Safari iOS 4 do not fire the `onpopstate` event when the hash has changed unlike the other browsers
+ - Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call / [bug report](https://bugs.webkit.org/show_bug.cgi?id=56249)
+ - Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions / [bug report](https://bugs.webkit.org/show_bug.cgi?id=42940)
+ - Google Chrome 8,9,10 and Firefox 4 prior to the RC will always fire `onpopstate` once the page has loaded / [change recommendation](http://hacks.mozilla.org/2011/03/history-api-changes-in-firefox-4/)
+ - Safari iOS 4.0, 4.1, 4.2 have a working HTML5 History API - although the actual back buttons of the browsers do not work, therefore we treat them as HTML4 browsers
+ - None of the HTML5 browsers actually utilise the `title` argument to the `pushState` and `replaceState` calls
+ - HTML4 Browsers
+ - Old browsers like MSIE 6,7 and Firefox 2 do not have a `onhashchange` event
+ - MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ - Non-Opera HTML4 browsers sometimes do not apply the hash when the hash is not `urlencoded`
+ - All Browsers
+ - State data and titles do not persist once the site is left and then returned (includes page refreshes)
+ - State titles are never applied to the `document.title`
+- ReplaceState functionality is emulated in HTML4 browsers by discarding the replaced state, so when the discarded state is accessed it is skipped using the appropriate `History.back()` / `History.forward()` call
+- Data persistance and synchronisation works like so: Every second or so, the SUIDs and URLs of the states will synchronise between the store and the local session. When a new session opens a familiar state (via the SUID or the URL) and it is not found locally then it will attempt to load the last known stored state with that information.
+- URLs will be unescaped to the maximum, so for instance the URL `?key=a%20b%252c` will become `?key=a b c`. This is to ensure consistency between browser url encodings.
+- Changing the hash of the page causes `onpopstate` to fire (this is expected/standard functionality). To ensure correct compatibility between HTML5 and HTML4 browsers the following events have been created:
+ - `window.onstatechange`: this is the same as the `onpopstate` event except it does not fire for traditional anchors
+ - `window.onanchorchange`: this is the same as the `onhashchange` event except it does not fire for states
+
+
+## History
+
+You can discover the history inside the [History.md](https://github.com/browserstate/history.js/blob/master/History.md#files) file
+
+
+## License
+
+Licensed under the [New BSD License](http://opensource.org/licenses/BSD-3-Clause)
+ Copyright © 2011+ [Benjamin Arthur Lupton](http://balupton.com)
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/bower.json b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/bower.json
new file mode 100644
index 00000000..fbe41338
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/bower.json
@@ -0,0 +1,4 @@
+{
+ "name": "history.js",
+ "version": "1.8.0"
+}
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/buildr-uncompressed.coffee b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/buildr-uncompressed.coffee
new file mode 100644
index 00000000..99cc0f40
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/buildr-uncompressed.coffee
@@ -0,0 +1,372 @@
+# Requires
+buildr = require 'buildr'
+util = require 'util'
+
+# Options
+options =
+ watch: false
+ compress: false
+
+# Configs
+configs =
+ standard:
+ # Options
+ name: 'standard'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Checking
+ checkScripts: true
+ jshintOptions:
+ browser: true
+ laxbreak: true
+ boss: true
+ undef: true
+ onevar: true
+ strict: true
+ noarg: true
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ other: [
+
+ # -----------------------------
+ # Dojo Toolkit
+
+ {
+ # Options
+ name: 'html4+html5+dojo'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.dojo.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html4+html5/dojo.history.js'
+ }
+ {
+ # Options
+ name: 'html5+dojo'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.dojo.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html5/dojo.history.js'
+ }
+
+ # -----------------------------
+ # ExtJS
+
+ {
+ # Options
+ name: 'html4+html5+extjs'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.extjs.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html4+html5/extjs.history.js'
+ }
+ {
+ # Options
+ name: 'html5+extjs'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.extjs.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html5/extjs.history.js'
+ }
+
+ # -----------------------------
+ # JQUERY
+
+ {
+ # Options
+ name: 'html4+html5+jquery'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.jquery.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html4+html5/jquery.history.js'
+ }
+ {
+ # Options
+ name: 'html5+jquery'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.jquery.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html5/jquery.history.js'
+ }
+
+
+ # -----------------------------
+ # MOOTOOLS
+
+ {
+ # Options
+ name: 'html4+html5+mootools'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.mootools.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html4+html5/mootools.history.js'
+ }
+ {
+ # Options
+ name: 'html5+mootools'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.mootools.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html5/mootools.history.js'
+ }
+
+
+ # -----------------------------
+ # NATIVE
+
+ {
+ # Options
+ name: 'html4+html5+native'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.native.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html4+html5/native.history.js'
+ }
+ {
+ # Options
+ name: 'html5+native'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.native.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html5/native.history.js'
+ }
+
+
+ # -----------------------------
+ # RIGHT.JS
+
+ {
+ # Options
+ name: 'html4+html5+right'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.right.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html4+html5/right.history.js'
+ }
+ {
+ # Options
+ name: 'html5+right'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.right.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html5/right.history.js'
+ }
+
+
+ # -----------------------------
+ # ZEPTO
+
+ {
+ # Options
+ name: 'html4+html5+zepto'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.zepto.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html4+html5/zepto.history.js'
+ }
+ {
+ # Options
+ name: 'html5+zepto'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.zepto.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled-uncompressed/html5/zepto.history.js'
+ }
+ ]
+
+# Standard
+standardConfig = configs.standard
+standardConfig.successHandler = ->
+ for config in configs.other
+ buildrInstance = buildr.createInstance config
+ buildrInstance.process()
+
+# Process
+standardBuildr = buildr.createInstance configs.standard
+standardBuildr.process()
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/buildr.coffee b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/buildr.coffee
new file mode 100644
index 00000000..08da95c9
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/buildr.coffee
@@ -0,0 +1,373 @@
+# Requires
+buildr = require 'buildr'
+util = require 'util'
+
+# Options
+options =
+ watch: false
+ compress: true
+
+# Configs
+configs =
+ standard:
+ # Options
+ name: 'standard'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+ outPath: __dirname+'/scripts/compressed'
+
+ # Checking
+ checkScripts: true
+ jshintOptions:
+ browser: true
+ laxbreak: true
+ boss: true
+ undef: true
+ onevar: true
+ strict: true
+ noarg: true
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ other: [
+
+ # -----------------------------
+ # Dojo Toolkit
+
+ {
+ # Options
+ name: 'html4+html5+dojo'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.dojo.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html4+html5/dojo.history.js'
+ }
+ {
+ # Options
+ name: 'html5+dojo'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.dojo.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html5/dojo.history.js'
+ }
+
+ # -----------------------------
+ # ExtJS
+
+ {
+ # Options
+ name: 'html4+html5+extjs'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.extjs.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html4+html5/extjs.history.js'
+ }
+ {
+ # Options
+ name: 'html5+extjs'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.extjs.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html5/extjs.history.js'
+ }
+
+ # -----------------------------
+ # JQUERY
+
+ {
+ # Options
+ name: 'html4+html5+jquery'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.jquery.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html4+html5/jquery.history.js'
+ }
+ {
+ # Options
+ name: 'html5+jquery'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.jquery.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html5/jquery.history.js'
+ }
+
+
+ # -----------------------------
+ # MOOTOOLS
+
+ {
+ # Options
+ name: 'html4+html5+mootools'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.mootools.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html4+html5/mootools.history.js'
+ }
+ {
+ # Options
+ name: 'html5+mootools'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.mootools.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html5/mootools.history.js'
+ }
+
+
+ # -----------------------------
+ # NATIVE
+
+ {
+ # Options
+ name: 'html4+html5+native'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.native.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html4+html5/native.history.js'
+ }
+ {
+ # Options
+ name: 'html5+native'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.native.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html5/native.history.js'
+ }
+
+
+ # -----------------------------
+ # RIGHT.JS
+
+ {
+ # Options
+ name: 'html4+html5+right'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.right.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html4+html5/right.history.js'
+ }
+ {
+ # Options
+ name: 'html5+right'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.right.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html5/right.history.js'
+ }
+
+
+ # -----------------------------
+ # ZEPTO
+
+ {
+ # Options
+ name: 'html4+html5+zepto'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'json2.js'
+ 'history.adapter.zepto.js'
+ 'history.html4.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html4+html5/zepto.history.js'
+ }
+ {
+ # Options
+ name: 'html5+zepto'
+ watch: options.watch
+
+ # Paths
+ srcPath: __dirname+'/scripts/uncompressed'
+
+ # Compression (without outPath only the generated bundle files are compressed)
+ compressScripts: options.compress # Array or true or false
+
+ # Order
+ scriptsOrder: [
+ 'history.adapter.zepto.js'
+ 'history.js'
+ ]
+
+ # Bundling
+ bundleScriptPath: __dirname+'/scripts/bundled/html5/zepto.history.js'
+ }
+ ]
+
+# Standard
+standardConfig = configs.standard
+standardConfig.successHandler = ->
+ for config in configs.other
+ buildrInstance = buildr.createInstance config
+ buildrInstance.process()
+
+# Process
+standardBuildr = buildr.createInstance configs.standard
+standardBuildr.process()
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/component.json b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/component.json
new file mode 100644
index 00000000..fbe41338
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/component.json
@@ -0,0 +1,4 @@
+{
+ "name": "history.js",
+ "version": "1.8.0"
+}
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/bcherry-orig.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/bcherry-orig.html
new file mode 100644
index 00000000..43672f49
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/bcherry-orig.html
@@ -0,0 +1,58 @@
+
+
+
+
+
+
+ WebKit is Dropping HTML5 "popstate" Events
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ There's a bug in the HTML5 "popstate" event, as implemented in WebKit (Safari and Chrome). View this page in one of those browsers. Your browser has had history entries added from #0 to #19 (you should start at #19). Hitting back/forward will navigate through these. On each URL, the large number above should reflect the hash value. If you hit back/forward quickly, you'll notice that your number gets out of sync with the URL. This is because WebKit is dropping popstate events (they are not firing). It seems to happen when outbound network requests are in progress when the user navigates in their browser happens. In this case, your browser is downloading an image that takes 1s to serve on every popstate, so you'll have to wait 1s between backs/forwards to have the feature work correctly. You could also cause constant network traffic by putting an image download in a setInterval, in which case your popstate events will never fire. This implementation simulates an AJAX application that makes a network request when you navigate between URLs using pushState/popstate. View the source for more info.
+ This was filed as Bug 42940 with WebKit on July 24, 2010. The Firefox 4 beta does not have this bug, which is good news.
+ This is put together by Ben Cherry . Ben is a front-end engineer at Twitter , and you can follow him at @bcherry .
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/bcherry.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/bcherry.html
new file mode 100644
index 00000000..309f4d44
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/bcherry.html
@@ -0,0 +1,62 @@
+
+
+
+
+
+
+ WebKit is Dropping HTML5 "popstate" Events
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ There's a bug in the HTML5 "popstate" event, as implemented in WebKit (Safari and Chrome). View this page in one of those browsers. Your browser has had history entries added from #0 to #19 (you should start at #19). Hitting back/forward will navigate through these. On each URL, the large number above should reflect the hash value. If you hit back/forward quickly, you'll notice that your number gets out of sync with the URL. This is because WebKit is dropping popstate events (they are not firing). It seems to happen when outbound network requests are in progress when the user navigates in their browser happens. In this case, your browser is downloading an image that takes 1s to serve on every popstate, so you'll have to wait 1s between backs/forwards to have the feature work correctly. You could also cause constant network traffic by putting an image download in a setInterval, in which case your popstate events will never fire. This implementation simulates an AJAX application that makes a network request when you navigate between URLs using pushState/popstate. View the source for more info.
+ This was filed as Bug 42940 with WebKit on July 24, 2010. The Firefox 4 beta does not have this bug, which is good news.
+ This is put together by Ben Cherry . Ben is a front-end engineer at Twitter , and you can follow him at @bcherry .
+ This bug was fixed in History.js by Benjamin Lupton . Benjamin is a freelance web 2.0 consultant, and you can follow him at @balupton .
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/chrome.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/chrome.html
new file mode 100644
index 00000000..a2791a31
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/chrome.html
@@ -0,0 +1,37 @@
+
+
+ Chrome History API Data Artifact
+
+
+ This demo demonstrates an issue with Google Chrome versions 8-10 (possibly 11) where if you push a state with data, then do history.back to the initial state, the event.state will contain the pushed states data instead of being null.
+ Note: The issue requires a clean history list, as such this should always be opened in a new tab/window where there are no prior history items.
+ Reported by Benjamin Lupton author of History.js
+ bug
+ reset
+
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/index.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/index.html
new file mode 100644
index 00000000..7e538b5c
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/index.html
@@ -0,0 +1,84 @@
+
+
+
+
+
+
+ History.js
+
+
+
+
+
+
+
+
+
+
+
+
History.js
+
History.js gracefully supports the HTML5 History/State APIs (pushState, replaceState, onPopState) in all browsers. Including continued support for data, titles, replaceState. Supports jQuery , MooTools and Prototype . For HTML5 browsers this means that you can modify the URL directly, without needing to use hashes anymore. For HTML4 browsers it will revert back to using the old onhashchange functionality.
+
+
+
+
+
+
Click through the buttons in order and you'll get the results demonstrated in the README.md file.
+
+
+
+
+
+
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/native-auto.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/native-auto.html
new file mode 100644
index 00000000..1ea10ffa
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/native-auto.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/native.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/native.html
new file mode 100644
index 00000000..010f89a0
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/native.html
@@ -0,0 +1,62 @@
+
+
+ HTML5 History API Demo
+
+
+
+
+
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/navigator.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/navigator.html
new file mode 100644
index 00000000..f9b15844
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/navigator.html
@@ -0,0 +1,23 @@
+
+
+
+
+
+ Navigator Output
+
+
+
+
+
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/safari.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/safari.html
new file mode 100644
index 00000000..5da17755
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/safari.html
@@ -0,0 +1,61 @@
+
+
+ Safari Hash ReplaceState History Traversal Bug
+
+
+ This demo demonstrates an issue with Safari 5.0.4 (6533.20.27) handing of hashes and replace state. When a hash is set, and then replaced using replaceState the history list are then broken, when traversing back the hash does not change.
+ Note: The issue requires a clean history list, as such this should always be opened in a new tab/window where there are no prior history items.
+ Reported by Benjamin Lupton author of History.js
+ bug
+ workaround
+ reset
+
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/unicode.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/unicode.html
new file mode 100644
index 00000000..e34e562f
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/demo/unicode.html
@@ -0,0 +1,79 @@
+
+
+
+
+
+
+ History.js
+
+
+
+
+
+
+
+
+
+
+
+
History.js
+
History.js gracefully supports unicode.
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/license.txt b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/license.txt
new file mode 100644
index 00000000..647bfd26
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/license.txt
@@ -0,0 +1,10 @@
+Copyright (c) 2011, Benjamin Arthur Lupton
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+ • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+ • Neither the name of Benjamin Arthur Lupton nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/package.json b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/package.json
new file mode 100644
index 00000000..cc6f23d0
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/package.json
@@ -0,0 +1,67 @@
+{
+ "name": "history.js",
+ "version": "1.8.0",
+ "description": "History.js gracefully supports the HTML5 History/State APIs (pushState, replaceState, onPopState) in all browsers. Including continued support for data, titles, replaceState. Supports jQuery, MooTools and Prototype. For HTML5 browsers this means that you can modify the URL directly, without needing to use hashes anymore. For HTML4 browsers it will revert back to using the old onhashchange functionality.",
+ "homepage": "https://github.com/browserstate/history.js",
+ "keywords": [
+ "javascript",
+ "html5 history api",
+ "hashchange",
+ "popstate",
+ "pushstate",
+ "replacestate",
+ "hashes",
+ "hashbang"
+ ],
+ "author": {
+ "name": "Benjamin Lupton",
+ "email": "b@lupton.cc",
+ "web": "http://balupton.com"
+ },
+ "maintainers": [
+ {
+ "name": "Benjamin Lupton",
+ "email": "b@lupton.cc",
+ "web": "http://balupton.com"
+ },
+ {
+ "name": "Andreas Bernhard",
+ "email": "andreas@bernhard.im",
+ "web": "http://www.bs-infosys.com"
+ }
+ ],
+ "contributors": [
+ {
+ "name": "Benjamin Lupton",
+ "email": "b@lupton.cc",
+ "web": "http://balupton.com"
+ },
+ {
+ "name": "Andreas Bernhard",
+ "email": "andreas@bernhard.im",
+ "web": "http://www.bs-infosys.com"
+ }
+ ],
+ "bugs": {
+ "web": "https://github.com/browserstate/history.js/issues"
+ },
+ "licenses": [
+ {
+ "type": "New-BSD",
+ "url": "http://creativecommons.org/licenses/BSD/"
+ }
+ ],
+ "repository": {
+ "type": "git",
+ "url": "http://github.com/browserstate/history.js.git"
+ },
+ "dependencies": {
+ "buildr": "0.8.x"
+ },
+ "engines": {
+ },
+ "directories": {
+ "out": "./scripts/compressed",
+ "src": "./scripts/uncompressed"
+ }
+}
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/dojo.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/dojo.history.js
new file mode 100644
index 00000000..6b8b1d66
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/dojo.history.js
@@ -0,0 +1,3335 @@
+/*
+ json2.js
+ 2012-10-08
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ See http://www.JSON.org/js.html
+
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
+ This file creates a global JSON object containing two methods: stringify
+ and parse.
+
+ JSON.stringify(value, replacer, space)
+ value any JavaScript value, usually an object or array.
+
+ replacer an optional parameter that determines how object
+ values are stringified for objects. It can be a
+ function or an array of strings.
+
+ space an optional parameter that specifies the indentation
+ of nested structures. If it is omitted, the text will
+ be packed without extra whitespace. If it is a number,
+ it will specify the number of spaces to indent at each
+ level. If it is a string (such as '\t' or ' '),
+ it contains the characters used to indent at each level.
+
+ This method produces a JSON text from a JavaScript value.
+
+ When an object value is found, if the object contains a toJSON
+ method, its toJSON method will be called and the result will be
+ stringified. A toJSON method does not serialize: it returns the
+ value represented by the name/value pair that should be serialized,
+ or undefined if nothing should be serialized. The toJSON method
+ will be passed the key associated with the value, and this will be
+ bound to the value
+
+ For example, this would serialize Dates as ISO strings.
+
+ Date.prototype.toJSON = function (key) {
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ return this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z';
+ };
+
+ You can provide an optional replacer method. It will be passed the
+ key and value of each member, with this bound to the containing
+ object. The value that is returned from your method will be
+ serialized. If your method returns undefined, then the member will
+ be excluded from the serialization.
+
+ If the replacer parameter is an array of strings, then it will be
+ used to select the members to be serialized. It filters the results
+ such that only members with keys listed in the replacer array are
+ stringified.
+
+ Values that do not have JSON representations, such as undefined or
+ functions, will not be serialized. Such values in objects will be
+ dropped; in arrays they will be replaced with null. You can use
+ a replacer function to replace those with JSON values.
+ JSON.stringify(undefined) returns undefined.
+
+ The optional space parameter produces a stringification of the
+ value that is filled with line breaks and indentation to make it
+ easier to read.
+
+ If the space parameter is a non-empty string, then that string will
+ be used for indentation. If the space parameter is a number, then
+ the indentation will be that many spaces.
+
+ Example:
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
+ // text is '["e",{"pluribus":"unum"}]'
+
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+ text = JSON.stringify([new Date()], function (key, value) {
+ return this[key] instanceof Date ?
+ 'Date(' + this[key] + ')' : value;
+ });
+ // text is '["Date(---current time---)"]'
+
+
+ JSON.parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = JSON.parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
+ }
+ }
+ return value;
+ });
+
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+ var d;
+ if (typeof value === 'string' &&
+ value.slice(0, 5) === 'Date(' &&
+ value.slice(-1) === ')') {
+ d = new Date(value.slice(5, -1));
+ if (d) {
+ return d;
+ }
+ }
+ return value;
+ });
+
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+*/
+
+/*jslint evil: true, regexp: true */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
+ test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.
+
+if (typeof JSON !== 'object') {
+ JSON = {};
+}
+
+(function () {
+ 'use strict';
+
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ if (typeof Date.prototype.toJSON !== 'function') {
+
+ Date.prototype.toJSON = function (key) {
+
+ return isFinite(this.valueOf())
+ ? this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z'
+ : null;
+ };
+
+ String.prototype.toJSON =
+ Number.prototype.toJSON =
+ Boolean.prototype.toJSON = function (key) {
+ return this.valueOf();
+ };
+ }
+
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ gap,
+ indent,
+ meta = { // table of character substitutions
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ rep;
+
+
+ function quote(string) {
+
+// If the string contains no control characters, no quote characters, and no
+// backslash characters, then we can safely slap some quotes around it.
+// Otherwise we must also replace the offending characters with safe escape
+// sequences.
+
+ escapable.lastIndex = 0;
+ return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
+ var c = meta[a];
+ return typeof c === 'string'
+ ? c
+ : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"' : '"' + string + '"';
+ }
+
+
+ function str(key, holder) {
+
+// Produce a string from holder[key].
+
+ var i, // The loop counter.
+ k, // The member key.
+ v, // The member value.
+ length,
+ mind = gap,
+ partial,
+ value = holder[key];
+
+// If the value has a toJSON method, call it to obtain a replacement value.
+
+ if (value && typeof value === 'object' &&
+ typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+
+// If we were called with a replacer function, then call the replacer to
+// obtain a replacement value.
+
+ if (typeof rep === 'function') {
+ value = rep.call(holder, key, value);
+ }
+
+// What happens next depends on the value's type.
+
+ switch (typeof value) {
+ case 'string':
+ return quote(value);
+
+ case 'number':
+
+// JSON numbers must be finite. Encode non-finite numbers as null.
+
+ return isFinite(value) ? String(value) : 'null';
+
+ case 'boolean':
+ case 'null':
+
+// If the value is a boolean or null, convert it to a string. Note:
+// typeof null does not produce 'null'. The case is included here in
+// the remote chance that this gets fixed someday.
+
+ return String(value);
+
+// If the type is 'object', we might be dealing with an object or an array or
+// null.
+
+ case 'object':
+
+// Due to a specification blunder in ECMAScript, typeof null is 'object',
+// so watch out for that case.
+
+ if (!value) {
+ return 'null';
+ }
+
+// Make an array to hold the partial results of stringifying this object value.
+
+ gap += indent;
+ partial = [];
+
+// Is the value an array?
+
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+// The value is an array. Stringify every element. Use null as a placeholder
+// for non-JSON values.
+
+ length = value.length;
+ for (i = 0; i < length; i += 1) {
+ partial[i] = str(i, value) || 'null';
+ }
+
+// Join all of the elements together, separated with commas, and wrap them in
+// brackets.
+
+ v = partial.length === 0
+ ? '[]'
+ : gap
+ ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
+ : '[' + partial.join(',') + ']';
+ gap = mind;
+ return v;
+ }
+
+// If the replacer is an array, use it to select the members to be stringified.
+
+ if (rep && typeof rep === 'object') {
+ length = rep.length;
+ for (i = 0; i < length; i += 1) {
+ if (typeof rep[i] === 'string') {
+ k = rep[i];
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ } else {
+
+// Otherwise, iterate through all of the keys in the object.
+
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ }
+
+// Join all of the member texts together, separated with commas,
+// and wrap them in braces.
+
+ v = partial.length === 0
+ ? '{}'
+ : gap
+ ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
+ : '{' + partial.join(',') + '}';
+ gap = mind;
+ return v;
+ }
+ }
+
+// If the JSON object does not yet have a stringify method, give it one.
+
+ if (typeof JSON.stringify !== 'function') {
+ JSON.stringify = function (value, replacer, space) {
+
+// The stringify method takes a value and an optional replacer, and an optional
+// space parameter, and returns a JSON text. The replacer can be a function
+// that can replace values, or an array of strings that will select the keys.
+// A default replacer method can be provided. Use of the space parameter can
+// produce text that is more easily readable.
+
+ var i;
+ gap = '';
+ indent = '';
+
+// If the space parameter is a number, make an indent string containing that
+// many spaces.
+
+ if (typeof space === 'number') {
+ for (i = 0; i < space; i += 1) {
+ indent += ' ';
+ }
+
+// If the space parameter is a string, it will be used as the indent string.
+
+ } else if (typeof space === 'string') {
+ indent = space;
+ }
+
+// If there is a replacer, it must be a function or an array.
+// Otherwise, throw an error.
+
+ rep = replacer;
+ if (replacer && typeof replacer !== 'function' &&
+ (typeof replacer !== 'object' ||
+ typeof replacer.length !== 'number')) {
+ throw new Error('JSON.stringify');
+ }
+
+// Make a fake root object containing our value under the key of ''.
+// Return the result of stringifying the value.
+
+ return str('', {'': value});
+ };
+ }
+
+
+// If the JSON object does not yet have a parse method, give it one.
+
+ if (typeof JSON.parse !== 'function') {
+ JSON.parse = function (text, reviver) {
+
+// The parse method takes a text and an optional reviver function, and returns
+// a JavaScript value if the text is a valid JSON text.
+
+ var j;
+
+ function walk(holder, key) {
+
+// The walk method is used to recursively walk the resulting structure so
+// that modifications can be made.
+
+ var k, v, value = holder[key];
+ if (value && typeof value === 'object') {
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = walk(value, k);
+ if (v !== undefined) {
+ value[k] = v;
+ } else {
+ delete value[k];
+ }
+ }
+ }
+ }
+ return reviver.call(holder, key, value);
+ }
+
+
+// Parsing happens in four stages. In the first stage, we replace certain
+// Unicode characters with escape sequences. JavaScript handles many characters
+// incorrectly, either silently deleting them, or treating them as line endings.
+
+ text = String(text);
+ cx.lastIndex = 0;
+ if (cx.test(text)) {
+ text = text.replace(cx, function (a) {
+ return '\\u' +
+ ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ });
+ }
+
+// In the second stage, we run the text against regular expressions that look
+// for non-JSON patterns. We are especially concerned with '()' and 'new'
+// because they can cause invocation, and '=' because it can cause mutation.
+// But just to be safe, we want to reject all unexpected forms.
+
+// We split the second stage into 4 regexp operations in order to work around
+// crippling inefficiencies in IE's and Safari's regexp engines. First we
+// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
+// replace all simple value tokens with ']' characters. Third, we delete all
+// open brackets that follow a colon or comma or that begin the text. Finally,
+// we look to see that the remaining characters are only whitespace or ']' or
+// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
+
+ if (/^[\],:{}\s]*$/
+ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
+
+// In the third stage we use the eval function to compile the text into a
+// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
+// in JavaScript: it can begin a block or an object literal. We wrap the text
+// in parens to eliminate the ambiguity.
+
+ j = eval('(' + text + ')');
+
+// In the optional fourth stage, we recursively walk the new structure, passing
+// each name/value pair to a reviver function for possible transformation.
+
+ return typeof reviver === 'function'
+ ? walk({'': j}, '')
+ : j;
+ }
+
+// If the text is not JSON parseable, then a SyntaxError is thrown.
+
+ throw new SyntaxError('JSON.parse');
+ };
+ }
+}());/**
+ * History.js Dojo Adapter
+ *
+ * Essentially the same as the native adapter but uses dojo/ready for the dom load callback.
+ *
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var History = window.History = window.History||{},
+ require = window.require;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.handlers[uid][eventName] = Array
+ */
+ handlers: {},
+
+ /**
+ * History.Adapter._uid
+ * The current element unique identifier
+ */
+ _uid: 1,
+
+ /**
+ * History.Adapter.uid(element)
+ * @param {Element} element
+ * @return {String} uid
+ */
+ uid: function(element){
+ return element._uid || (element._uid = History.Adapter._uid++);
+ },
+
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element} element
+ * @param {String} eventName - custom and standard events
+ * @param {Function} callback
+ * @return
+ */
+ bind: function(element,eventName,callback){
+ // Prepare
+ var uid = History.Adapter.uid(element);
+
+ // Apply Listener
+ History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
+ History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
+ History.Adapter.handlers[uid][eventName].push(callback);
+
+ // Bind Global Listener
+ element['on'+eventName] = (function(element,eventName){
+ return function(event){
+ History.Adapter.trigger(element,eventName,event);
+ };
+ })(element,eventName);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element} element
+ * @param {String} eventName - custom and standard events
+ * @param {Object} event - a object of event data
+ * @return
+ */
+ trigger: function(element,eventName,event){
+ // Prepare
+ event = event || {};
+ var uid = History.Adapter.uid(element),
+ i,n;
+
+ // Apply Listener
+ History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
+ History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
+
+ // Fire Listeners
+ for ( i=0,n=History.Adapter.handlers[uid][eventName].length; i
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ document = window.document, // Make sure we are using the correct document
+ setTimeout = window.setTimeout||setTimeout,
+ clearTimeout = window.clearTimeout||clearTimeout,
+ setInterval = window.setInterval||setInterval,
+ History = window.History = window.History||{}; // Public History Object
+
+ // Check Existence
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ throw new Error('History.js HTML4 Support has already been loaded...');
+ }
+
+
+ // ========================================================================
+ // Initialise HTML4 Support
+
+ // Initialise HTML4 Support
+ History.initHtml4 = function(){
+ // Initialise
+ if ( typeof History.initHtml4.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initHtml4.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Properties
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = true;
+
+
+ // ====================================================================
+ // Hash Storage
+
+ /**
+ * History.savedHashes
+ * Store the hashes in an array
+ */
+ History.savedHashes = [];
+
+ /**
+ * History.isLastHash(newHash)
+ * Checks if the hash is the last hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.isLastHash = function(newHash){
+ // Prepare
+ var oldHash = History.getHashByIndex(),
+ isLast;
+
+ // Check
+ isLast = newHash === oldHash;
+
+ // Return isLast
+ return isLast;
+ };
+
+ /**
+ * History.isHashEqual(newHash, oldHash)
+ * Checks to see if two hashes are functionally equal
+ * @param {string} newHash
+ * @param {string} oldHash
+ * @return {boolean} true
+ */
+ History.isHashEqual = function(newHash, oldHash){
+ newHash = encodeURIComponent(newHash).replace(/%25/g, "%");
+ oldHash = encodeURIComponent(oldHash).replace(/%25/g, "%");
+ return newHash === oldHash;
+ };
+
+ /**
+ * History.saveHash(newHash)
+ * Push a Hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.saveHash = function(newHash){
+ // Check Hash
+ if ( History.isLastHash(newHash) ) {
+ return false;
+ }
+
+ // Push the Hash
+ History.savedHashes.push(newHash);
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getHashByIndex()
+ * Gets a hash by the index
+ * @param {integer} index
+ * @return {string}
+ */
+ History.getHashByIndex = function(index){
+ // Prepare
+ var hash = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ hash = History.savedHashes[History.savedHashes.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ hash = History.savedHashes[History.savedHashes.length+index];
+ }
+ else {
+ // Get from the beginning
+ hash = History.savedHashes[index];
+ }
+
+ // Return hash
+ return hash;
+ };
+
+
+ // ====================================================================
+ // Discarded States
+
+ /**
+ * History.discardedHashes
+ * A hashed array of discarded hashes
+ */
+ History.discardedHashes = {};
+
+ /**
+ * History.discardedStates
+ * A hashed array of discarded states
+ */
+ History.discardedStates = {};
+
+ /**
+ * History.discardState(State)
+ * Discards the state by ignoring it through History
+ * @param {object} State
+ * @return {true}
+ */
+ History.discardState = function(discardedState,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Prepare
+ var discardedStateHash = History.getHashByState(discardedState),
+ discardObject;
+
+ // Create Discard Object
+ discardObject = {
+ 'discardedState': discardedState,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to DiscardedStates
+ History.discardedStates[discardedStateHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardHash(hash)
+ * Discards the hash by ignoring it through History
+ * @param {string} hash
+ * @return {true}
+ */
+ History.discardHash = function(discardedHash,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Create Discard Object
+ var discardObject = {
+ 'discardedHash': discardedHash,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to discardedHash
+ History.discardedHashes[discardedHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardedState(State)
+ * Checks to see if the state is discarded
+ * @param {object} State
+ * @return {bool}
+ */
+ History.discardedState = function(State){
+ // Prepare
+ var StateHash = History.getHashByState(State),
+ discarded;
+
+ // Check
+ discarded = History.discardedStates[StateHash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.discardedHash(hash)
+ * Checks to see if the state is discarded
+ * @param {string} State
+ * @return {bool}
+ */
+ History.discardedHash = function(hash){
+ // Check
+ var discarded = History.discardedHashes[hash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.recycleState(State)
+ * Allows a discarded state to be used again
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.recycleState = function(State){
+ //History.debug('History.recycleState', arguments);
+ // Prepare
+ var StateHash = History.getHashByState(State);
+
+ // Remove from DiscardedStates
+ if ( History.discardedState(State) ) {
+ delete History.discardedStates[StateHash];
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ====================================================================
+ // HTML4 HashChange Support
+
+ if ( History.emulated.hashChange ) {
+ /*
+ * We must emulate the HTML4 HashChange Support by manually checking for hash changes
+ */
+
+ /**
+ * History.hashChangeInit()
+ * Init the HashChange Emulation
+ */
+ History.hashChangeInit = function(){
+ // Define our Checker Function
+ History.checkerFunction = null;
+
+ // Define some variables that will help in our checker function
+ var lastDocumentHash = '',
+ iframeId, iframe,
+ lastIframeHash, checkerRunning,
+ startedWithHash = Boolean(History.getHash());
+
+ // Handle depending on the browser
+ if ( History.isInternetExplorer() ) {
+ // IE6 and IE7
+ // We need to use an iframe to emulate the back and forward buttons
+
+ // Create iFrame
+ iframeId = 'historyjs-iframe';
+ iframe = document.createElement('iframe');
+
+ // Adjust iFarme
+ // IE 6 requires iframe to have a src on HTTPS pages, otherwise it will throw a
+ // "This page contains both secure and nonsecure items" warning.
+ iframe.setAttribute('id', iframeId);
+ iframe.setAttribute('src', '#');
+ iframe.style.display = 'none';
+
+ // Append iFrame
+ document.body.appendChild(iframe);
+
+ // Create initial history entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Define some variables that will help in our checker function
+ lastIframeHash = '';
+ checkerRunning = false;
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Check Running
+ if ( checkerRunning ) {
+ return false;
+ }
+
+ // Update Running
+ checkerRunning = true;
+
+ // Fetch
+ var
+ documentHash = History.getHash(),
+ iframeHash = History.getHash(iframe.contentWindow.document);
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Create a history entry in the iframe
+ if ( iframeHash !== documentHash ) {
+ //History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);
+
+ // Equalise
+ lastIframeHash = iframeHash = documentHash;
+
+ // Create History Entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Update the iframe's hash
+ iframe.contentWindow.document.location.hash = History.escapeHash(documentHash);
+ }
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // The iFrame Hash has changed (back button caused)
+ else if ( iframeHash !== lastIframeHash ) {
+ //History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);
+
+ // Equalise
+ lastIframeHash = iframeHash;
+
+ // If there is no iframe hash that means we're at the original
+ // iframe state.
+ // And if there was a hash on the original request, the original
+ // iframe state was replaced instantly, so skip this state and take
+ // the user back to where they came from.
+ if (startedWithHash && iframeHash === '') {
+ History.back();
+ }
+ else {
+ // Update the Hash
+ History.setHash(iframeHash,false);
+ }
+ }
+
+ // Reset Running
+ checkerRunning = false;
+
+ // Return true
+ return true;
+ };
+ }
+ else {
+ // We are not IE
+ // Firefox 1 or 2, Opera
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Prepare
+ var documentHash = History.getHash()||'';
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // Return true
+ return true;
+ };
+ }
+
+ // Apply the checker function
+ History.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));
+
+ // Done
+ return true;
+ }; // History.hashChangeInit
+
+ // Bind hashChangeInit
+ History.Adapter.onDomLoad(History.hashChangeInit);
+
+ } // History.emulated.hashChange
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * We must emulate the HTML5 State Management by using HTML4 HashChange
+ */
+
+ /**
+ * History.onHashChange(event)
+ * Trigger HTML5's window.onpopstate via HTML4 HashChange Support
+ */
+ History.onHashChange = function(event){
+ //History.debug('History.onHashChange', arguments);
+
+ // Prepare
+ var currentUrl = ((event && event.newURL) || History.getLocationHref()),
+ currentHash = History.getHashByUrl(currentUrl),
+ currentState = null,
+ currentStateHash = null,
+ currentStateHashExits = null,
+ discardObject;
+
+ // Check if we are the same state
+ if ( History.isLastHash(currentHash) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onHashChange: no change');
+ History.busy(false);
+ return false;
+ }
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Store our location for use in detecting back/forward direction
+ History.saveHash(currentHash);
+
+ // Expand Hash
+ if ( currentHash && History.isTraditionalAnchor(currentHash) ) {
+ //History.debug('History.onHashChange: traditional anchor', currentHash);
+ // Traditional Anchor Hash
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ return false;
+ }
+
+ // Create State
+ currentState = History.extractState(History.getFullUrl(currentHash||History.getLocationHref()),true);
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(currentState) ) {
+ //History.debug('History.onHashChange: no change');
+ // There has been no change (just the page's hash has finally propagated)
+ History.busy(false);
+ return false;
+ }
+
+ // Create the state Hash
+ currentStateHash = History.getHashByState(currentState);
+
+ // Check if we are DiscardedState
+ discardObject = History.discardedState(currentState);
+ if ( discardObject ) {
+ // Ignore this state as it has been discarded and go back to the state before it
+ if ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {
+ // We are going backwards
+ //History.debug('History.onHashChange: go backwards');
+ History.back(false);
+ } else {
+ // We are going forwards
+ //History.debug('History.onHashChange: go forwards');
+ History.forward(false);
+ }
+ return false;
+ }
+
+ // Push the new HTML5 State
+ //History.debug('History.onHashChange: success hashchange');
+ History.pushState(currentState.data,currentState.title,encodeURI(currentState.url),false);
+
+ // End onHashChange closure
+ return true;
+ };
+ History.Adapter.bind(window,'hashchange',History.onHashChange);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Object
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ html4Hash = History.getHash(),
+ wasExpected = History.expectedStateId == newState.id;
+
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Check if we are the same State
+ if ( newStateHash === oldStateHash ) {
+ //History.debug('History.pushState: no change', newStateHash);
+ History.busy(false);
+ return false;
+ }
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ if(!wasExpected)
+ History.Adapter.trigger(window,'statechange');
+
+ // Update HTML4 Hash
+ if ( !History.isHashEqual(newStateHash, html4Hash) && !History.isHashEqual(newStateHash, History.getShortUrl(History.getLocationHref())) ) {
+ History.setHash(newStateHash,false);
+ }
+
+ History.busy(false);
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Objects
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ previousState = History.getStateByIndex(-2);
+
+ // Discard Old State
+ History.discardState(oldState,newState,previousState);
+
+ // If the url hasn't changed, just store and save the state
+ // and fire a statechange event to be consistent with the
+ // html 5 api
+ if ( newStateHash === oldStateHash ) {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ //History.debug('History.pushState: trigger popstate');
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+ }
+ else {
+ // Alias to PushState
+ History.pushState(newState.data,newState.title,newState.url,false);
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // History.emulated.pushState
+
+
+
+ // ====================================================================
+ // Initialise
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /**
+ * Ensure initial state is handled correctly
+ */
+ if ( History.getHash() && !History.emulated.hashChange ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+
+ } // History.emulated.pushState
+
+ }; // History.initHtml4
+
+ // Try to Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/extjs.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/extjs.history.js
new file mode 100644
index 00000000..ed2ac9fe
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/extjs.history.js
@@ -0,0 +1,3305 @@
+/*
+ json2.js
+ 2012-10-08
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ See http://www.JSON.org/js.html
+
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
+ This file creates a global JSON object containing two methods: stringify
+ and parse.
+
+ JSON.stringify(value, replacer, space)
+ value any JavaScript value, usually an object or array.
+
+ replacer an optional parameter that determines how object
+ values are stringified for objects. It can be a
+ function or an array of strings.
+
+ space an optional parameter that specifies the indentation
+ of nested structures. If it is omitted, the text will
+ be packed without extra whitespace. If it is a number,
+ it will specify the number of spaces to indent at each
+ level. If it is a string (such as '\t' or ' '),
+ it contains the characters used to indent at each level.
+
+ This method produces a JSON text from a JavaScript value.
+
+ When an object value is found, if the object contains a toJSON
+ method, its toJSON method will be called and the result will be
+ stringified. A toJSON method does not serialize: it returns the
+ value represented by the name/value pair that should be serialized,
+ or undefined if nothing should be serialized. The toJSON method
+ will be passed the key associated with the value, and this will be
+ bound to the value
+
+ For example, this would serialize Dates as ISO strings.
+
+ Date.prototype.toJSON = function (key) {
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ return this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z';
+ };
+
+ You can provide an optional replacer method. It will be passed the
+ key and value of each member, with this bound to the containing
+ object. The value that is returned from your method will be
+ serialized. If your method returns undefined, then the member will
+ be excluded from the serialization.
+
+ If the replacer parameter is an array of strings, then it will be
+ used to select the members to be serialized. It filters the results
+ such that only members with keys listed in the replacer array are
+ stringified.
+
+ Values that do not have JSON representations, such as undefined or
+ functions, will not be serialized. Such values in objects will be
+ dropped; in arrays they will be replaced with null. You can use
+ a replacer function to replace those with JSON values.
+ JSON.stringify(undefined) returns undefined.
+
+ The optional space parameter produces a stringification of the
+ value that is filled with line breaks and indentation to make it
+ easier to read.
+
+ If the space parameter is a non-empty string, then that string will
+ be used for indentation. If the space parameter is a number, then
+ the indentation will be that many spaces.
+
+ Example:
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
+ // text is '["e",{"pluribus":"unum"}]'
+
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+ text = JSON.stringify([new Date()], function (key, value) {
+ return this[key] instanceof Date ?
+ 'Date(' + this[key] + ')' : value;
+ });
+ // text is '["Date(---current time---)"]'
+
+
+ JSON.parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = JSON.parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
+ }
+ }
+ return value;
+ });
+
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+ var d;
+ if (typeof value === 'string' &&
+ value.slice(0, 5) === 'Date(' &&
+ value.slice(-1) === ')') {
+ d = new Date(value.slice(5, -1));
+ if (d) {
+ return d;
+ }
+ }
+ return value;
+ });
+
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+*/
+
+/*jslint evil: true, regexp: true */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
+ test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.
+
+if (typeof JSON !== 'object') {
+ JSON = {};
+}
+
+(function () {
+ 'use strict';
+
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ if (typeof Date.prototype.toJSON !== 'function') {
+
+ Date.prototype.toJSON = function (key) {
+
+ return isFinite(this.valueOf())
+ ? this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z'
+ : null;
+ };
+
+ String.prototype.toJSON =
+ Number.prototype.toJSON =
+ Boolean.prototype.toJSON = function (key) {
+ return this.valueOf();
+ };
+ }
+
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ gap,
+ indent,
+ meta = { // table of character substitutions
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ rep;
+
+
+ function quote(string) {
+
+// If the string contains no control characters, no quote characters, and no
+// backslash characters, then we can safely slap some quotes around it.
+// Otherwise we must also replace the offending characters with safe escape
+// sequences.
+
+ escapable.lastIndex = 0;
+ return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
+ var c = meta[a];
+ return typeof c === 'string'
+ ? c
+ : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"' : '"' + string + '"';
+ }
+
+
+ function str(key, holder) {
+
+// Produce a string from holder[key].
+
+ var i, // The loop counter.
+ k, // The member key.
+ v, // The member value.
+ length,
+ mind = gap,
+ partial,
+ value = holder[key];
+
+// If the value has a toJSON method, call it to obtain a replacement value.
+
+ if (value && typeof value === 'object' &&
+ typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+
+// If we were called with a replacer function, then call the replacer to
+// obtain a replacement value.
+
+ if (typeof rep === 'function') {
+ value = rep.call(holder, key, value);
+ }
+
+// What happens next depends on the value's type.
+
+ switch (typeof value) {
+ case 'string':
+ return quote(value);
+
+ case 'number':
+
+// JSON numbers must be finite. Encode non-finite numbers as null.
+
+ return isFinite(value) ? String(value) : 'null';
+
+ case 'boolean':
+ case 'null':
+
+// If the value is a boolean or null, convert it to a string. Note:
+// typeof null does not produce 'null'. The case is included here in
+// the remote chance that this gets fixed someday.
+
+ return String(value);
+
+// If the type is 'object', we might be dealing with an object or an array or
+// null.
+
+ case 'object':
+
+// Due to a specification blunder in ECMAScript, typeof null is 'object',
+// so watch out for that case.
+
+ if (!value) {
+ return 'null';
+ }
+
+// Make an array to hold the partial results of stringifying this object value.
+
+ gap += indent;
+ partial = [];
+
+// Is the value an array?
+
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+// The value is an array. Stringify every element. Use null as a placeholder
+// for non-JSON values.
+
+ length = value.length;
+ for (i = 0; i < length; i += 1) {
+ partial[i] = str(i, value) || 'null';
+ }
+
+// Join all of the elements together, separated with commas, and wrap them in
+// brackets.
+
+ v = partial.length === 0
+ ? '[]'
+ : gap
+ ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
+ : '[' + partial.join(',') + ']';
+ gap = mind;
+ return v;
+ }
+
+// If the replacer is an array, use it to select the members to be stringified.
+
+ if (rep && typeof rep === 'object') {
+ length = rep.length;
+ for (i = 0; i < length; i += 1) {
+ if (typeof rep[i] === 'string') {
+ k = rep[i];
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ } else {
+
+// Otherwise, iterate through all of the keys in the object.
+
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ }
+
+// Join all of the member texts together, separated with commas,
+// and wrap them in braces.
+
+ v = partial.length === 0
+ ? '{}'
+ : gap
+ ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
+ : '{' + partial.join(',') + '}';
+ gap = mind;
+ return v;
+ }
+ }
+
+// If the JSON object does not yet have a stringify method, give it one.
+
+ if (typeof JSON.stringify !== 'function') {
+ JSON.stringify = function (value, replacer, space) {
+
+// The stringify method takes a value and an optional replacer, and an optional
+// space parameter, and returns a JSON text. The replacer can be a function
+// that can replace values, or an array of strings that will select the keys.
+// A default replacer method can be provided. Use of the space parameter can
+// produce text that is more easily readable.
+
+ var i;
+ gap = '';
+ indent = '';
+
+// If the space parameter is a number, make an indent string containing that
+// many spaces.
+
+ if (typeof space === 'number') {
+ for (i = 0; i < space; i += 1) {
+ indent += ' ';
+ }
+
+// If the space parameter is a string, it will be used as the indent string.
+
+ } else if (typeof space === 'string') {
+ indent = space;
+ }
+
+// If there is a replacer, it must be a function or an array.
+// Otherwise, throw an error.
+
+ rep = replacer;
+ if (replacer && typeof replacer !== 'function' &&
+ (typeof replacer !== 'object' ||
+ typeof replacer.length !== 'number')) {
+ throw new Error('JSON.stringify');
+ }
+
+// Make a fake root object containing our value under the key of ''.
+// Return the result of stringifying the value.
+
+ return str('', {'': value});
+ };
+ }
+
+
+// If the JSON object does not yet have a parse method, give it one.
+
+ if (typeof JSON.parse !== 'function') {
+ JSON.parse = function (text, reviver) {
+
+// The parse method takes a text and an optional reviver function, and returns
+// a JavaScript value if the text is a valid JSON text.
+
+ var j;
+
+ function walk(holder, key) {
+
+// The walk method is used to recursively walk the resulting structure so
+// that modifications can be made.
+
+ var k, v, value = holder[key];
+ if (value && typeof value === 'object') {
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = walk(value, k);
+ if (v !== undefined) {
+ value[k] = v;
+ } else {
+ delete value[k];
+ }
+ }
+ }
+ }
+ return reviver.call(holder, key, value);
+ }
+
+
+// Parsing happens in four stages. In the first stage, we replace certain
+// Unicode characters with escape sequences. JavaScript handles many characters
+// incorrectly, either silently deleting them, or treating them as line endings.
+
+ text = String(text);
+ cx.lastIndex = 0;
+ if (cx.test(text)) {
+ text = text.replace(cx, function (a) {
+ return '\\u' +
+ ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ });
+ }
+
+// In the second stage, we run the text against regular expressions that look
+// for non-JSON patterns. We are especially concerned with '()' and 'new'
+// because they can cause invocation, and '=' because it can cause mutation.
+// But just to be safe, we want to reject all unexpected forms.
+
+// We split the second stage into 4 regexp operations in order to work around
+// crippling inefficiencies in IE's and Safari's regexp engines. First we
+// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
+// replace all simple value tokens with ']' characters. Third, we delete all
+// open brackets that follow a colon or comma or that begin the text. Finally,
+// we look to see that the remaining characters are only whitespace or ']' or
+// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
+
+ if (/^[\],:{}\s]*$/
+ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
+
+// In the third stage we use the eval function to compile the text into a
+// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
+// in JavaScript: it can begin a block or an object literal. We wrap the text
+// in parens to eliminate the ambiguity.
+
+ j = eval('(' + text + ')');
+
+// In the optional fourth stage, we recursively walk the new structure, passing
+// each name/value pair to a reviver function for possible transformation.
+
+ return typeof reviver === 'function'
+ ? walk({'': j}, '')
+ : j;
+ }
+
+// If the text is not JSON parseable, then a SyntaxError is thrown.
+
+ throw new SyntaxError('JSON.parse');
+ };
+ }
+}());/**
+ * History.js ExtJS Adapter
+ * @author Sean Adkinson
+ * @copyright 2012 Sean Adkinson
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ Ext = window.Ext;
+
+ window.JSON = {
+ stringify: Ext.JSON.encode,
+ parse: Ext.JSON.decode
+ };
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ observables: {},
+
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {function} callback
+ * @param {Object} scope
+ * @return {void}
+ */
+ bind: function(element,eventName,callback,scope){
+ Ext.EventManager.addListener(element, eventName, callback, scope);
+
+ //bind an observable to the element that will let us "trigger" events on it
+ var id = Ext.id(element, 'history-'), observable = this.observables[id];
+ if (!observable) {
+ observable = Ext.create('Ext.util.Observable');
+ this.observables[id] = observable;
+ }
+ observable.on(eventName, callback, scope);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return {void}
+ */
+ trigger: function(element,eventName,extra){
+ var id = Ext.id(element, 'history-'), observable = this.observables[id];
+ if (observable) {
+ observable.fireEvent(eventName, extra);
+ }
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {string} key - key for the event data to extract
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return {mixed}
+ */
+ extractEventData: function(key,event,extra){
+ var result = (event && event.browserEvent && event.browserEvent[key]) || (extra && extra[key]) || undefined;
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {function} callback
+ * @return {void}
+ */
+ onDomLoad: function(callback) {
+ Ext.onReady(callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);/**
+ * History.js HTML4 Support
+ * Depends on the HTML5 Support
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ document = window.document, // Make sure we are using the correct document
+ setTimeout = window.setTimeout||setTimeout,
+ clearTimeout = window.clearTimeout||clearTimeout,
+ setInterval = window.setInterval||setInterval,
+ History = window.History = window.History||{}; // Public History Object
+
+ // Check Existence
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ throw new Error('History.js HTML4 Support has already been loaded...');
+ }
+
+
+ // ========================================================================
+ // Initialise HTML4 Support
+
+ // Initialise HTML4 Support
+ History.initHtml4 = function(){
+ // Initialise
+ if ( typeof History.initHtml4.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initHtml4.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Properties
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = true;
+
+
+ // ====================================================================
+ // Hash Storage
+
+ /**
+ * History.savedHashes
+ * Store the hashes in an array
+ */
+ History.savedHashes = [];
+
+ /**
+ * History.isLastHash(newHash)
+ * Checks if the hash is the last hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.isLastHash = function(newHash){
+ // Prepare
+ var oldHash = History.getHashByIndex(),
+ isLast;
+
+ // Check
+ isLast = newHash === oldHash;
+
+ // Return isLast
+ return isLast;
+ };
+
+ /**
+ * History.isHashEqual(newHash, oldHash)
+ * Checks to see if two hashes are functionally equal
+ * @param {string} newHash
+ * @param {string} oldHash
+ * @return {boolean} true
+ */
+ History.isHashEqual = function(newHash, oldHash){
+ newHash = encodeURIComponent(newHash).replace(/%25/g, "%");
+ oldHash = encodeURIComponent(oldHash).replace(/%25/g, "%");
+ return newHash === oldHash;
+ };
+
+ /**
+ * History.saveHash(newHash)
+ * Push a Hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.saveHash = function(newHash){
+ // Check Hash
+ if ( History.isLastHash(newHash) ) {
+ return false;
+ }
+
+ // Push the Hash
+ History.savedHashes.push(newHash);
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getHashByIndex()
+ * Gets a hash by the index
+ * @param {integer} index
+ * @return {string}
+ */
+ History.getHashByIndex = function(index){
+ // Prepare
+ var hash = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ hash = History.savedHashes[History.savedHashes.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ hash = History.savedHashes[History.savedHashes.length+index];
+ }
+ else {
+ // Get from the beginning
+ hash = History.savedHashes[index];
+ }
+
+ // Return hash
+ return hash;
+ };
+
+
+ // ====================================================================
+ // Discarded States
+
+ /**
+ * History.discardedHashes
+ * A hashed array of discarded hashes
+ */
+ History.discardedHashes = {};
+
+ /**
+ * History.discardedStates
+ * A hashed array of discarded states
+ */
+ History.discardedStates = {};
+
+ /**
+ * History.discardState(State)
+ * Discards the state by ignoring it through History
+ * @param {object} State
+ * @return {true}
+ */
+ History.discardState = function(discardedState,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Prepare
+ var discardedStateHash = History.getHashByState(discardedState),
+ discardObject;
+
+ // Create Discard Object
+ discardObject = {
+ 'discardedState': discardedState,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to DiscardedStates
+ History.discardedStates[discardedStateHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardHash(hash)
+ * Discards the hash by ignoring it through History
+ * @param {string} hash
+ * @return {true}
+ */
+ History.discardHash = function(discardedHash,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Create Discard Object
+ var discardObject = {
+ 'discardedHash': discardedHash,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to discardedHash
+ History.discardedHashes[discardedHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardedState(State)
+ * Checks to see if the state is discarded
+ * @param {object} State
+ * @return {bool}
+ */
+ History.discardedState = function(State){
+ // Prepare
+ var StateHash = History.getHashByState(State),
+ discarded;
+
+ // Check
+ discarded = History.discardedStates[StateHash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.discardedHash(hash)
+ * Checks to see if the state is discarded
+ * @param {string} State
+ * @return {bool}
+ */
+ History.discardedHash = function(hash){
+ // Check
+ var discarded = History.discardedHashes[hash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.recycleState(State)
+ * Allows a discarded state to be used again
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.recycleState = function(State){
+ //History.debug('History.recycleState', arguments);
+ // Prepare
+ var StateHash = History.getHashByState(State);
+
+ // Remove from DiscardedStates
+ if ( History.discardedState(State) ) {
+ delete History.discardedStates[StateHash];
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ====================================================================
+ // HTML4 HashChange Support
+
+ if ( History.emulated.hashChange ) {
+ /*
+ * We must emulate the HTML4 HashChange Support by manually checking for hash changes
+ */
+
+ /**
+ * History.hashChangeInit()
+ * Init the HashChange Emulation
+ */
+ History.hashChangeInit = function(){
+ // Define our Checker Function
+ History.checkerFunction = null;
+
+ // Define some variables that will help in our checker function
+ var lastDocumentHash = '',
+ iframeId, iframe,
+ lastIframeHash, checkerRunning,
+ startedWithHash = Boolean(History.getHash());
+
+ // Handle depending on the browser
+ if ( History.isInternetExplorer() ) {
+ // IE6 and IE7
+ // We need to use an iframe to emulate the back and forward buttons
+
+ // Create iFrame
+ iframeId = 'historyjs-iframe';
+ iframe = document.createElement('iframe');
+
+ // Adjust iFarme
+ // IE 6 requires iframe to have a src on HTTPS pages, otherwise it will throw a
+ // "This page contains both secure and nonsecure items" warning.
+ iframe.setAttribute('id', iframeId);
+ iframe.setAttribute('src', '#');
+ iframe.style.display = 'none';
+
+ // Append iFrame
+ document.body.appendChild(iframe);
+
+ // Create initial history entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Define some variables that will help in our checker function
+ lastIframeHash = '';
+ checkerRunning = false;
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Check Running
+ if ( checkerRunning ) {
+ return false;
+ }
+
+ // Update Running
+ checkerRunning = true;
+
+ // Fetch
+ var
+ documentHash = History.getHash(),
+ iframeHash = History.getHash(iframe.contentWindow.document);
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Create a history entry in the iframe
+ if ( iframeHash !== documentHash ) {
+ //History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);
+
+ // Equalise
+ lastIframeHash = iframeHash = documentHash;
+
+ // Create History Entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Update the iframe's hash
+ iframe.contentWindow.document.location.hash = History.escapeHash(documentHash);
+ }
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // The iFrame Hash has changed (back button caused)
+ else if ( iframeHash !== lastIframeHash ) {
+ //History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);
+
+ // Equalise
+ lastIframeHash = iframeHash;
+
+ // If there is no iframe hash that means we're at the original
+ // iframe state.
+ // And if there was a hash on the original request, the original
+ // iframe state was replaced instantly, so skip this state and take
+ // the user back to where they came from.
+ if (startedWithHash && iframeHash === '') {
+ History.back();
+ }
+ else {
+ // Update the Hash
+ History.setHash(iframeHash,false);
+ }
+ }
+
+ // Reset Running
+ checkerRunning = false;
+
+ // Return true
+ return true;
+ };
+ }
+ else {
+ // We are not IE
+ // Firefox 1 or 2, Opera
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Prepare
+ var documentHash = History.getHash()||'';
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // Return true
+ return true;
+ };
+ }
+
+ // Apply the checker function
+ History.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));
+
+ // Done
+ return true;
+ }; // History.hashChangeInit
+
+ // Bind hashChangeInit
+ History.Adapter.onDomLoad(History.hashChangeInit);
+
+ } // History.emulated.hashChange
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * We must emulate the HTML5 State Management by using HTML4 HashChange
+ */
+
+ /**
+ * History.onHashChange(event)
+ * Trigger HTML5's window.onpopstate via HTML4 HashChange Support
+ */
+ History.onHashChange = function(event){
+ //History.debug('History.onHashChange', arguments);
+
+ // Prepare
+ var currentUrl = ((event && event.newURL) || History.getLocationHref()),
+ currentHash = History.getHashByUrl(currentUrl),
+ currentState = null,
+ currentStateHash = null,
+ currentStateHashExits = null,
+ discardObject;
+
+ // Check if we are the same state
+ if ( History.isLastHash(currentHash) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onHashChange: no change');
+ History.busy(false);
+ return false;
+ }
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Store our location for use in detecting back/forward direction
+ History.saveHash(currentHash);
+
+ // Expand Hash
+ if ( currentHash && History.isTraditionalAnchor(currentHash) ) {
+ //History.debug('History.onHashChange: traditional anchor', currentHash);
+ // Traditional Anchor Hash
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ return false;
+ }
+
+ // Create State
+ currentState = History.extractState(History.getFullUrl(currentHash||History.getLocationHref()),true);
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(currentState) ) {
+ //History.debug('History.onHashChange: no change');
+ // There has been no change (just the page's hash has finally propagated)
+ History.busy(false);
+ return false;
+ }
+
+ // Create the state Hash
+ currentStateHash = History.getHashByState(currentState);
+
+ // Check if we are DiscardedState
+ discardObject = History.discardedState(currentState);
+ if ( discardObject ) {
+ // Ignore this state as it has been discarded and go back to the state before it
+ if ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {
+ // We are going backwards
+ //History.debug('History.onHashChange: go backwards');
+ History.back(false);
+ } else {
+ // We are going forwards
+ //History.debug('History.onHashChange: go forwards');
+ History.forward(false);
+ }
+ return false;
+ }
+
+ // Push the new HTML5 State
+ //History.debug('History.onHashChange: success hashchange');
+ History.pushState(currentState.data,currentState.title,encodeURI(currentState.url),false);
+
+ // End onHashChange closure
+ return true;
+ };
+ History.Adapter.bind(window,'hashchange',History.onHashChange);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Object
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ html4Hash = History.getHash(),
+ wasExpected = History.expectedStateId == newState.id;
+
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Check if we are the same State
+ if ( newStateHash === oldStateHash ) {
+ //History.debug('History.pushState: no change', newStateHash);
+ History.busy(false);
+ return false;
+ }
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ if(!wasExpected)
+ History.Adapter.trigger(window,'statechange');
+
+ // Update HTML4 Hash
+ if ( !History.isHashEqual(newStateHash, html4Hash) && !History.isHashEqual(newStateHash, History.getShortUrl(History.getLocationHref())) ) {
+ History.setHash(newStateHash,false);
+ }
+
+ History.busy(false);
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Objects
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ previousState = History.getStateByIndex(-2);
+
+ // Discard Old State
+ History.discardState(oldState,newState,previousState);
+
+ // If the url hasn't changed, just store and save the state
+ // and fire a statechange event to be consistent with the
+ // html 5 api
+ if ( newStateHash === oldStateHash ) {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ //History.debug('History.pushState: trigger popstate');
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+ }
+ else {
+ // Alias to PushState
+ History.pushState(newState.data,newState.title,newState.url,false);
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // History.emulated.pushState
+
+
+
+ // ====================================================================
+ // Initialise
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /**
+ * Ensure initial state is handled correctly
+ */
+ if ( History.getHash() && !History.emulated.hashChange ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+
+ } // History.emulated.pushState
+
+ }; // History.initHtml4
+
+ // Try to Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/jquery.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/jquery.history.js
new file mode 100644
index 00000000..dc47ce7c
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/jquery.history.js
@@ -0,0 +1,3291 @@
+/*
+ json2.js
+ 2012-10-08
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ See http://www.JSON.org/js.html
+
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
+ This file creates a global JSON object containing two methods: stringify
+ and parse.
+
+ JSON.stringify(value, replacer, space)
+ value any JavaScript value, usually an object or array.
+
+ replacer an optional parameter that determines how object
+ values are stringified for objects. It can be a
+ function or an array of strings.
+
+ space an optional parameter that specifies the indentation
+ of nested structures. If it is omitted, the text will
+ be packed without extra whitespace. If it is a number,
+ it will specify the number of spaces to indent at each
+ level. If it is a string (such as '\t' or ' '),
+ it contains the characters used to indent at each level.
+
+ This method produces a JSON text from a JavaScript value.
+
+ When an object value is found, if the object contains a toJSON
+ method, its toJSON method will be called and the result will be
+ stringified. A toJSON method does not serialize: it returns the
+ value represented by the name/value pair that should be serialized,
+ or undefined if nothing should be serialized. The toJSON method
+ will be passed the key associated with the value, and this will be
+ bound to the value
+
+ For example, this would serialize Dates as ISO strings.
+
+ Date.prototype.toJSON = function (key) {
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ return this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z';
+ };
+
+ You can provide an optional replacer method. It will be passed the
+ key and value of each member, with this bound to the containing
+ object. The value that is returned from your method will be
+ serialized. If your method returns undefined, then the member will
+ be excluded from the serialization.
+
+ If the replacer parameter is an array of strings, then it will be
+ used to select the members to be serialized. It filters the results
+ such that only members with keys listed in the replacer array are
+ stringified.
+
+ Values that do not have JSON representations, such as undefined or
+ functions, will not be serialized. Such values in objects will be
+ dropped; in arrays they will be replaced with null. You can use
+ a replacer function to replace those with JSON values.
+ JSON.stringify(undefined) returns undefined.
+
+ The optional space parameter produces a stringification of the
+ value that is filled with line breaks and indentation to make it
+ easier to read.
+
+ If the space parameter is a non-empty string, then that string will
+ be used for indentation. If the space parameter is a number, then
+ the indentation will be that many spaces.
+
+ Example:
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
+ // text is '["e",{"pluribus":"unum"}]'
+
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+ text = JSON.stringify([new Date()], function (key, value) {
+ return this[key] instanceof Date ?
+ 'Date(' + this[key] + ')' : value;
+ });
+ // text is '["Date(---current time---)"]'
+
+
+ JSON.parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = JSON.parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
+ }
+ }
+ return value;
+ });
+
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+ var d;
+ if (typeof value === 'string' &&
+ value.slice(0, 5) === 'Date(' &&
+ value.slice(-1) === ')') {
+ d = new Date(value.slice(5, -1));
+ if (d) {
+ return d;
+ }
+ }
+ return value;
+ });
+
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+*/
+
+/*jslint evil: true, regexp: true */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
+ test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.
+
+if (typeof JSON !== 'object') {
+ JSON = {};
+}
+
+(function () {
+ 'use strict';
+
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ if (typeof Date.prototype.toJSON !== 'function') {
+
+ Date.prototype.toJSON = function (key) {
+
+ return isFinite(this.valueOf())
+ ? this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z'
+ : null;
+ };
+
+ String.prototype.toJSON =
+ Number.prototype.toJSON =
+ Boolean.prototype.toJSON = function (key) {
+ return this.valueOf();
+ };
+ }
+
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ gap,
+ indent,
+ meta = { // table of character substitutions
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ rep;
+
+
+ function quote(string) {
+
+// If the string contains no control characters, no quote characters, and no
+// backslash characters, then we can safely slap some quotes around it.
+// Otherwise we must also replace the offending characters with safe escape
+// sequences.
+
+ escapable.lastIndex = 0;
+ return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
+ var c = meta[a];
+ return typeof c === 'string'
+ ? c
+ : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"' : '"' + string + '"';
+ }
+
+
+ function str(key, holder) {
+
+// Produce a string from holder[key].
+
+ var i, // The loop counter.
+ k, // The member key.
+ v, // The member value.
+ length,
+ mind = gap,
+ partial,
+ value = holder[key];
+
+// If the value has a toJSON method, call it to obtain a replacement value.
+
+ if (value && typeof value === 'object' &&
+ typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+
+// If we were called with a replacer function, then call the replacer to
+// obtain a replacement value.
+
+ if (typeof rep === 'function') {
+ value = rep.call(holder, key, value);
+ }
+
+// What happens next depends on the value's type.
+
+ switch (typeof value) {
+ case 'string':
+ return quote(value);
+
+ case 'number':
+
+// JSON numbers must be finite. Encode non-finite numbers as null.
+
+ return isFinite(value) ? String(value) : 'null';
+
+ case 'boolean':
+ case 'null':
+
+// If the value is a boolean or null, convert it to a string. Note:
+// typeof null does not produce 'null'. The case is included here in
+// the remote chance that this gets fixed someday.
+
+ return String(value);
+
+// If the type is 'object', we might be dealing with an object or an array or
+// null.
+
+ case 'object':
+
+// Due to a specification blunder in ECMAScript, typeof null is 'object',
+// so watch out for that case.
+
+ if (!value) {
+ return 'null';
+ }
+
+// Make an array to hold the partial results of stringifying this object value.
+
+ gap += indent;
+ partial = [];
+
+// Is the value an array?
+
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+// The value is an array. Stringify every element. Use null as a placeholder
+// for non-JSON values.
+
+ length = value.length;
+ for (i = 0; i < length; i += 1) {
+ partial[i] = str(i, value) || 'null';
+ }
+
+// Join all of the elements together, separated with commas, and wrap them in
+// brackets.
+
+ v = partial.length === 0
+ ? '[]'
+ : gap
+ ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
+ : '[' + partial.join(',') + ']';
+ gap = mind;
+ return v;
+ }
+
+// If the replacer is an array, use it to select the members to be stringified.
+
+ if (rep && typeof rep === 'object') {
+ length = rep.length;
+ for (i = 0; i < length; i += 1) {
+ if (typeof rep[i] === 'string') {
+ k = rep[i];
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ } else {
+
+// Otherwise, iterate through all of the keys in the object.
+
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ }
+
+// Join all of the member texts together, separated with commas,
+// and wrap them in braces.
+
+ v = partial.length === 0
+ ? '{}'
+ : gap
+ ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
+ : '{' + partial.join(',') + '}';
+ gap = mind;
+ return v;
+ }
+ }
+
+// If the JSON object does not yet have a stringify method, give it one.
+
+ if (typeof JSON.stringify !== 'function') {
+ JSON.stringify = function (value, replacer, space) {
+
+// The stringify method takes a value and an optional replacer, and an optional
+// space parameter, and returns a JSON text. The replacer can be a function
+// that can replace values, or an array of strings that will select the keys.
+// A default replacer method can be provided. Use of the space parameter can
+// produce text that is more easily readable.
+
+ var i;
+ gap = '';
+ indent = '';
+
+// If the space parameter is a number, make an indent string containing that
+// many spaces.
+
+ if (typeof space === 'number') {
+ for (i = 0; i < space; i += 1) {
+ indent += ' ';
+ }
+
+// If the space parameter is a string, it will be used as the indent string.
+
+ } else if (typeof space === 'string') {
+ indent = space;
+ }
+
+// If there is a replacer, it must be a function or an array.
+// Otherwise, throw an error.
+
+ rep = replacer;
+ if (replacer && typeof replacer !== 'function' &&
+ (typeof replacer !== 'object' ||
+ typeof replacer.length !== 'number')) {
+ throw new Error('JSON.stringify');
+ }
+
+// Make a fake root object containing our value under the key of ''.
+// Return the result of stringifying the value.
+
+ return str('', {'': value});
+ };
+ }
+
+
+// If the JSON object does not yet have a parse method, give it one.
+
+ if (typeof JSON.parse !== 'function') {
+ JSON.parse = function (text, reviver) {
+
+// The parse method takes a text and an optional reviver function, and returns
+// a JavaScript value if the text is a valid JSON text.
+
+ var j;
+
+ function walk(holder, key) {
+
+// The walk method is used to recursively walk the resulting structure so
+// that modifications can be made.
+
+ var k, v, value = holder[key];
+ if (value && typeof value === 'object') {
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = walk(value, k);
+ if (v !== undefined) {
+ value[k] = v;
+ } else {
+ delete value[k];
+ }
+ }
+ }
+ }
+ return reviver.call(holder, key, value);
+ }
+
+
+// Parsing happens in four stages. In the first stage, we replace certain
+// Unicode characters with escape sequences. JavaScript handles many characters
+// incorrectly, either silently deleting them, or treating them as line endings.
+
+ text = String(text);
+ cx.lastIndex = 0;
+ if (cx.test(text)) {
+ text = text.replace(cx, function (a) {
+ return '\\u' +
+ ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ });
+ }
+
+// In the second stage, we run the text against regular expressions that look
+// for non-JSON patterns. We are especially concerned with '()' and 'new'
+// because they can cause invocation, and '=' because it can cause mutation.
+// But just to be safe, we want to reject all unexpected forms.
+
+// We split the second stage into 4 regexp operations in order to work around
+// crippling inefficiencies in IE's and Safari's regexp engines. First we
+// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
+// replace all simple value tokens with ']' characters. Third, we delete all
+// open brackets that follow a colon or comma or that begin the text. Finally,
+// we look to see that the remaining characters are only whitespace or ']' or
+// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
+
+ if (/^[\],:{}\s]*$/
+ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
+
+// In the third stage we use the eval function to compile the text into a
+// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
+// in JavaScript: it can begin a block or an object literal. We wrap the text
+// in parens to eliminate the ambiguity.
+
+ j = eval('(' + text + ')');
+
+// In the optional fourth stage, we recursively walk the new structure, passing
+// each name/value pair to a reviver function for possible transformation.
+
+ return typeof reviver === 'function'
+ ? walk({'': j}, '')
+ : j;
+ }
+
+// If the text is not JSON parseable, then a SyntaxError is thrown.
+
+ throw new SyntaxError('JSON.parse');
+ };
+ }
+}());/**
+ * History.js jQuery Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ jQuery = window.jQuery;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {function} callback
+ * @return {void}
+ */
+ bind: function(el,event,callback){
+ jQuery(el).bind(event,callback);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return {void}
+ */
+ trigger: function(el,event,extra){
+ jQuery(el).trigger(event,extra);
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {string} key - key for the event data to extract
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return {mixed}
+ */
+ extractEventData: function(key,event,extra){
+ // jQuery Native then jQuery Custom
+ var result = (event && event.originalEvent && event.originalEvent[key]) || (extra && extra[key]) || undefined;
+
+ // Return
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {function} callback
+ * @return {void}
+ */
+ onDomLoad: function(callback) {
+ jQuery(callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+
+/**
+ * History.js HTML4 Support
+ * Depends on the HTML5 Support
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ document = window.document, // Make sure we are using the correct document
+ setTimeout = window.setTimeout||setTimeout,
+ clearTimeout = window.clearTimeout||clearTimeout,
+ setInterval = window.setInterval||setInterval,
+ History = window.History = window.History||{}; // Public History Object
+
+ // Check Existence
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ throw new Error('History.js HTML4 Support has already been loaded...');
+ }
+
+
+ // ========================================================================
+ // Initialise HTML4 Support
+
+ // Initialise HTML4 Support
+ History.initHtml4 = function(){
+ // Initialise
+ if ( typeof History.initHtml4.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initHtml4.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Properties
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = true;
+
+
+ // ====================================================================
+ // Hash Storage
+
+ /**
+ * History.savedHashes
+ * Store the hashes in an array
+ */
+ History.savedHashes = [];
+
+ /**
+ * History.isLastHash(newHash)
+ * Checks if the hash is the last hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.isLastHash = function(newHash){
+ // Prepare
+ var oldHash = History.getHashByIndex(),
+ isLast;
+
+ // Check
+ isLast = newHash === oldHash;
+
+ // Return isLast
+ return isLast;
+ };
+
+ /**
+ * History.isHashEqual(newHash, oldHash)
+ * Checks to see if two hashes are functionally equal
+ * @param {string} newHash
+ * @param {string} oldHash
+ * @return {boolean} true
+ */
+ History.isHashEqual = function(newHash, oldHash){
+ newHash = encodeURIComponent(newHash).replace(/%25/g, "%");
+ oldHash = encodeURIComponent(oldHash).replace(/%25/g, "%");
+ return newHash === oldHash;
+ };
+
+ /**
+ * History.saveHash(newHash)
+ * Push a Hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.saveHash = function(newHash){
+ // Check Hash
+ if ( History.isLastHash(newHash) ) {
+ return false;
+ }
+
+ // Push the Hash
+ History.savedHashes.push(newHash);
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getHashByIndex()
+ * Gets a hash by the index
+ * @param {integer} index
+ * @return {string}
+ */
+ History.getHashByIndex = function(index){
+ // Prepare
+ var hash = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ hash = History.savedHashes[History.savedHashes.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ hash = History.savedHashes[History.savedHashes.length+index];
+ }
+ else {
+ // Get from the beginning
+ hash = History.savedHashes[index];
+ }
+
+ // Return hash
+ return hash;
+ };
+
+
+ // ====================================================================
+ // Discarded States
+
+ /**
+ * History.discardedHashes
+ * A hashed array of discarded hashes
+ */
+ History.discardedHashes = {};
+
+ /**
+ * History.discardedStates
+ * A hashed array of discarded states
+ */
+ History.discardedStates = {};
+
+ /**
+ * History.discardState(State)
+ * Discards the state by ignoring it through History
+ * @param {object} State
+ * @return {true}
+ */
+ History.discardState = function(discardedState,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Prepare
+ var discardedStateHash = History.getHashByState(discardedState),
+ discardObject;
+
+ // Create Discard Object
+ discardObject = {
+ 'discardedState': discardedState,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to DiscardedStates
+ History.discardedStates[discardedStateHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardHash(hash)
+ * Discards the hash by ignoring it through History
+ * @param {string} hash
+ * @return {true}
+ */
+ History.discardHash = function(discardedHash,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Create Discard Object
+ var discardObject = {
+ 'discardedHash': discardedHash,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to discardedHash
+ History.discardedHashes[discardedHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardedState(State)
+ * Checks to see if the state is discarded
+ * @param {object} State
+ * @return {bool}
+ */
+ History.discardedState = function(State){
+ // Prepare
+ var StateHash = History.getHashByState(State),
+ discarded;
+
+ // Check
+ discarded = History.discardedStates[StateHash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.discardedHash(hash)
+ * Checks to see if the state is discarded
+ * @param {string} State
+ * @return {bool}
+ */
+ History.discardedHash = function(hash){
+ // Check
+ var discarded = History.discardedHashes[hash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.recycleState(State)
+ * Allows a discarded state to be used again
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.recycleState = function(State){
+ //History.debug('History.recycleState', arguments);
+ // Prepare
+ var StateHash = History.getHashByState(State);
+
+ // Remove from DiscardedStates
+ if ( History.discardedState(State) ) {
+ delete History.discardedStates[StateHash];
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ====================================================================
+ // HTML4 HashChange Support
+
+ if ( History.emulated.hashChange ) {
+ /*
+ * We must emulate the HTML4 HashChange Support by manually checking for hash changes
+ */
+
+ /**
+ * History.hashChangeInit()
+ * Init the HashChange Emulation
+ */
+ History.hashChangeInit = function(){
+ // Define our Checker Function
+ History.checkerFunction = null;
+
+ // Define some variables that will help in our checker function
+ var lastDocumentHash = '',
+ iframeId, iframe,
+ lastIframeHash, checkerRunning,
+ startedWithHash = Boolean(History.getHash());
+
+ // Handle depending on the browser
+ if ( History.isInternetExplorer() ) {
+ // IE6 and IE7
+ // We need to use an iframe to emulate the back and forward buttons
+
+ // Create iFrame
+ iframeId = 'historyjs-iframe';
+ iframe = document.createElement('iframe');
+
+ // Adjust iFarme
+ // IE 6 requires iframe to have a src on HTTPS pages, otherwise it will throw a
+ // "This page contains both secure and nonsecure items" warning.
+ iframe.setAttribute('id', iframeId);
+ iframe.setAttribute('src', '#');
+ iframe.style.display = 'none';
+
+ // Append iFrame
+ document.body.appendChild(iframe);
+
+ // Create initial history entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Define some variables that will help in our checker function
+ lastIframeHash = '';
+ checkerRunning = false;
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Check Running
+ if ( checkerRunning ) {
+ return false;
+ }
+
+ // Update Running
+ checkerRunning = true;
+
+ // Fetch
+ var
+ documentHash = History.getHash(),
+ iframeHash = History.getHash(iframe.contentWindow.document);
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Create a history entry in the iframe
+ if ( iframeHash !== documentHash ) {
+ //History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);
+
+ // Equalise
+ lastIframeHash = iframeHash = documentHash;
+
+ // Create History Entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Update the iframe's hash
+ iframe.contentWindow.document.location.hash = History.escapeHash(documentHash);
+ }
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // The iFrame Hash has changed (back button caused)
+ else if ( iframeHash !== lastIframeHash ) {
+ //History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);
+
+ // Equalise
+ lastIframeHash = iframeHash;
+
+ // If there is no iframe hash that means we're at the original
+ // iframe state.
+ // And if there was a hash on the original request, the original
+ // iframe state was replaced instantly, so skip this state and take
+ // the user back to where they came from.
+ if (startedWithHash && iframeHash === '') {
+ History.back();
+ }
+ else {
+ // Update the Hash
+ History.setHash(iframeHash,false);
+ }
+ }
+
+ // Reset Running
+ checkerRunning = false;
+
+ // Return true
+ return true;
+ };
+ }
+ else {
+ // We are not IE
+ // Firefox 1 or 2, Opera
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Prepare
+ var documentHash = History.getHash()||'';
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // Return true
+ return true;
+ };
+ }
+
+ // Apply the checker function
+ History.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));
+
+ // Done
+ return true;
+ }; // History.hashChangeInit
+
+ // Bind hashChangeInit
+ History.Adapter.onDomLoad(History.hashChangeInit);
+
+ } // History.emulated.hashChange
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * We must emulate the HTML5 State Management by using HTML4 HashChange
+ */
+
+ /**
+ * History.onHashChange(event)
+ * Trigger HTML5's window.onpopstate via HTML4 HashChange Support
+ */
+ History.onHashChange = function(event){
+ //History.debug('History.onHashChange', arguments);
+
+ // Prepare
+ var currentUrl = ((event && event.newURL) || History.getLocationHref()),
+ currentHash = History.getHashByUrl(currentUrl),
+ currentState = null,
+ currentStateHash = null,
+ currentStateHashExits = null,
+ discardObject;
+
+ // Check if we are the same state
+ if ( History.isLastHash(currentHash) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onHashChange: no change');
+ History.busy(false);
+ return false;
+ }
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Store our location for use in detecting back/forward direction
+ History.saveHash(currentHash);
+
+ // Expand Hash
+ if ( currentHash && History.isTraditionalAnchor(currentHash) ) {
+ //History.debug('History.onHashChange: traditional anchor', currentHash);
+ // Traditional Anchor Hash
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ return false;
+ }
+
+ // Create State
+ currentState = History.extractState(History.getFullUrl(currentHash||History.getLocationHref()),true);
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(currentState) ) {
+ //History.debug('History.onHashChange: no change');
+ // There has been no change (just the page's hash has finally propagated)
+ History.busy(false);
+ return false;
+ }
+
+ // Create the state Hash
+ currentStateHash = History.getHashByState(currentState);
+
+ // Check if we are DiscardedState
+ discardObject = History.discardedState(currentState);
+ if ( discardObject ) {
+ // Ignore this state as it has been discarded and go back to the state before it
+ if ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {
+ // We are going backwards
+ //History.debug('History.onHashChange: go backwards');
+ History.back(false);
+ } else {
+ // We are going forwards
+ //History.debug('History.onHashChange: go forwards');
+ History.forward(false);
+ }
+ return false;
+ }
+
+ // Push the new HTML5 State
+ //History.debug('History.onHashChange: success hashchange');
+ History.pushState(currentState.data,currentState.title,encodeURI(currentState.url),false);
+
+ // End onHashChange closure
+ return true;
+ };
+ History.Adapter.bind(window,'hashchange',History.onHashChange);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Object
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ html4Hash = History.getHash(),
+ wasExpected = History.expectedStateId == newState.id;
+
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Check if we are the same State
+ if ( newStateHash === oldStateHash ) {
+ //History.debug('History.pushState: no change', newStateHash);
+ History.busy(false);
+ return false;
+ }
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ if(!wasExpected)
+ History.Adapter.trigger(window,'statechange');
+
+ // Update HTML4 Hash
+ if ( !History.isHashEqual(newStateHash, html4Hash) && !History.isHashEqual(newStateHash, History.getShortUrl(History.getLocationHref())) ) {
+ History.setHash(newStateHash,false);
+ }
+
+ History.busy(false);
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Objects
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ previousState = History.getStateByIndex(-2);
+
+ // Discard Old State
+ History.discardState(oldState,newState,previousState);
+
+ // If the url hasn't changed, just store and save the state
+ // and fire a statechange event to be consistent with the
+ // html 5 api
+ if ( newStateHash === oldStateHash ) {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ //History.debug('History.pushState: trigger popstate');
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+ }
+ else {
+ // Alias to PushState
+ History.pushState(newState.data,newState.title,newState.url,false);
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // History.emulated.pushState
+
+
+
+ // ====================================================================
+ // Initialise
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /**
+ * Ensure initial state is handled correctly
+ */
+ if ( History.getHash() && !History.emulated.hashChange ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+
+ } // History.emulated.pushState
+
+ }; // History.initHtml4
+
+ // Try to Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/mootools.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/mootools.history.js
new file mode 100644
index 00000000..df63dee7
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/mootools.history.js
@@ -0,0 +1,3298 @@
+/*
+ json2.js
+ 2012-10-08
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ See http://www.JSON.org/js.html
+
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
+ This file creates a global JSON object containing two methods: stringify
+ and parse.
+
+ JSON.stringify(value, replacer, space)
+ value any JavaScript value, usually an object or array.
+
+ replacer an optional parameter that determines how object
+ values are stringified for objects. It can be a
+ function or an array of strings.
+
+ space an optional parameter that specifies the indentation
+ of nested structures. If it is omitted, the text will
+ be packed without extra whitespace. If it is a number,
+ it will specify the number of spaces to indent at each
+ level. If it is a string (such as '\t' or ' '),
+ it contains the characters used to indent at each level.
+
+ This method produces a JSON text from a JavaScript value.
+
+ When an object value is found, if the object contains a toJSON
+ method, its toJSON method will be called and the result will be
+ stringified. A toJSON method does not serialize: it returns the
+ value represented by the name/value pair that should be serialized,
+ or undefined if nothing should be serialized. The toJSON method
+ will be passed the key associated with the value, and this will be
+ bound to the value
+
+ For example, this would serialize Dates as ISO strings.
+
+ Date.prototype.toJSON = function (key) {
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ return this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z';
+ };
+
+ You can provide an optional replacer method. It will be passed the
+ key and value of each member, with this bound to the containing
+ object. The value that is returned from your method will be
+ serialized. If your method returns undefined, then the member will
+ be excluded from the serialization.
+
+ If the replacer parameter is an array of strings, then it will be
+ used to select the members to be serialized. It filters the results
+ such that only members with keys listed in the replacer array are
+ stringified.
+
+ Values that do not have JSON representations, such as undefined or
+ functions, will not be serialized. Such values in objects will be
+ dropped; in arrays they will be replaced with null. You can use
+ a replacer function to replace those with JSON values.
+ JSON.stringify(undefined) returns undefined.
+
+ The optional space parameter produces a stringification of the
+ value that is filled with line breaks and indentation to make it
+ easier to read.
+
+ If the space parameter is a non-empty string, then that string will
+ be used for indentation. If the space parameter is a number, then
+ the indentation will be that many spaces.
+
+ Example:
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
+ // text is '["e",{"pluribus":"unum"}]'
+
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+ text = JSON.stringify([new Date()], function (key, value) {
+ return this[key] instanceof Date ?
+ 'Date(' + this[key] + ')' : value;
+ });
+ // text is '["Date(---current time---)"]'
+
+
+ JSON.parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = JSON.parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
+ }
+ }
+ return value;
+ });
+
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+ var d;
+ if (typeof value === 'string' &&
+ value.slice(0, 5) === 'Date(' &&
+ value.slice(-1) === ')') {
+ d = new Date(value.slice(5, -1));
+ if (d) {
+ return d;
+ }
+ }
+ return value;
+ });
+
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+*/
+
+/*jslint evil: true, regexp: true */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
+ test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.
+
+if (typeof JSON !== 'object') {
+ JSON = {};
+}
+
+(function () {
+ 'use strict';
+
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ if (typeof Date.prototype.toJSON !== 'function') {
+
+ Date.prototype.toJSON = function (key) {
+
+ return isFinite(this.valueOf())
+ ? this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z'
+ : null;
+ };
+
+ String.prototype.toJSON =
+ Number.prototype.toJSON =
+ Boolean.prototype.toJSON = function (key) {
+ return this.valueOf();
+ };
+ }
+
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ gap,
+ indent,
+ meta = { // table of character substitutions
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ rep;
+
+
+ function quote(string) {
+
+// If the string contains no control characters, no quote characters, and no
+// backslash characters, then we can safely slap some quotes around it.
+// Otherwise we must also replace the offending characters with safe escape
+// sequences.
+
+ escapable.lastIndex = 0;
+ return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
+ var c = meta[a];
+ return typeof c === 'string'
+ ? c
+ : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"' : '"' + string + '"';
+ }
+
+
+ function str(key, holder) {
+
+// Produce a string from holder[key].
+
+ var i, // The loop counter.
+ k, // The member key.
+ v, // The member value.
+ length,
+ mind = gap,
+ partial,
+ value = holder[key];
+
+// If the value has a toJSON method, call it to obtain a replacement value.
+
+ if (value && typeof value === 'object' &&
+ typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+
+// If we were called with a replacer function, then call the replacer to
+// obtain a replacement value.
+
+ if (typeof rep === 'function') {
+ value = rep.call(holder, key, value);
+ }
+
+// What happens next depends on the value's type.
+
+ switch (typeof value) {
+ case 'string':
+ return quote(value);
+
+ case 'number':
+
+// JSON numbers must be finite. Encode non-finite numbers as null.
+
+ return isFinite(value) ? String(value) : 'null';
+
+ case 'boolean':
+ case 'null':
+
+// If the value is a boolean or null, convert it to a string. Note:
+// typeof null does not produce 'null'. The case is included here in
+// the remote chance that this gets fixed someday.
+
+ return String(value);
+
+// If the type is 'object', we might be dealing with an object or an array or
+// null.
+
+ case 'object':
+
+// Due to a specification blunder in ECMAScript, typeof null is 'object',
+// so watch out for that case.
+
+ if (!value) {
+ return 'null';
+ }
+
+// Make an array to hold the partial results of stringifying this object value.
+
+ gap += indent;
+ partial = [];
+
+// Is the value an array?
+
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+// The value is an array. Stringify every element. Use null as a placeholder
+// for non-JSON values.
+
+ length = value.length;
+ for (i = 0; i < length; i += 1) {
+ partial[i] = str(i, value) || 'null';
+ }
+
+// Join all of the elements together, separated with commas, and wrap them in
+// brackets.
+
+ v = partial.length === 0
+ ? '[]'
+ : gap
+ ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
+ : '[' + partial.join(',') + ']';
+ gap = mind;
+ return v;
+ }
+
+// If the replacer is an array, use it to select the members to be stringified.
+
+ if (rep && typeof rep === 'object') {
+ length = rep.length;
+ for (i = 0; i < length; i += 1) {
+ if (typeof rep[i] === 'string') {
+ k = rep[i];
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ } else {
+
+// Otherwise, iterate through all of the keys in the object.
+
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ }
+
+// Join all of the member texts together, separated with commas,
+// and wrap them in braces.
+
+ v = partial.length === 0
+ ? '{}'
+ : gap
+ ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
+ : '{' + partial.join(',') + '}';
+ gap = mind;
+ return v;
+ }
+ }
+
+// If the JSON object does not yet have a stringify method, give it one.
+
+ if (typeof JSON.stringify !== 'function') {
+ JSON.stringify = function (value, replacer, space) {
+
+// The stringify method takes a value and an optional replacer, and an optional
+// space parameter, and returns a JSON text. The replacer can be a function
+// that can replace values, or an array of strings that will select the keys.
+// A default replacer method can be provided. Use of the space parameter can
+// produce text that is more easily readable.
+
+ var i;
+ gap = '';
+ indent = '';
+
+// If the space parameter is a number, make an indent string containing that
+// many spaces.
+
+ if (typeof space === 'number') {
+ for (i = 0; i < space; i += 1) {
+ indent += ' ';
+ }
+
+// If the space parameter is a string, it will be used as the indent string.
+
+ } else if (typeof space === 'string') {
+ indent = space;
+ }
+
+// If there is a replacer, it must be a function or an array.
+// Otherwise, throw an error.
+
+ rep = replacer;
+ if (replacer && typeof replacer !== 'function' &&
+ (typeof replacer !== 'object' ||
+ typeof replacer.length !== 'number')) {
+ throw new Error('JSON.stringify');
+ }
+
+// Make a fake root object containing our value under the key of ''.
+// Return the result of stringifying the value.
+
+ return str('', {'': value});
+ };
+ }
+
+
+// If the JSON object does not yet have a parse method, give it one.
+
+ if (typeof JSON.parse !== 'function') {
+ JSON.parse = function (text, reviver) {
+
+// The parse method takes a text and an optional reviver function, and returns
+// a JavaScript value if the text is a valid JSON text.
+
+ var j;
+
+ function walk(holder, key) {
+
+// The walk method is used to recursively walk the resulting structure so
+// that modifications can be made.
+
+ var k, v, value = holder[key];
+ if (value && typeof value === 'object') {
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = walk(value, k);
+ if (v !== undefined) {
+ value[k] = v;
+ } else {
+ delete value[k];
+ }
+ }
+ }
+ }
+ return reviver.call(holder, key, value);
+ }
+
+
+// Parsing happens in four stages. In the first stage, we replace certain
+// Unicode characters with escape sequences. JavaScript handles many characters
+// incorrectly, either silently deleting them, or treating them as line endings.
+
+ text = String(text);
+ cx.lastIndex = 0;
+ if (cx.test(text)) {
+ text = text.replace(cx, function (a) {
+ return '\\u' +
+ ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ });
+ }
+
+// In the second stage, we run the text against regular expressions that look
+// for non-JSON patterns. We are especially concerned with '()' and 'new'
+// because they can cause invocation, and '=' because it can cause mutation.
+// But just to be safe, we want to reject all unexpected forms.
+
+// We split the second stage into 4 regexp operations in order to work around
+// crippling inefficiencies in IE's and Safari's regexp engines. First we
+// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
+// replace all simple value tokens with ']' characters. Third, we delete all
+// open brackets that follow a colon or comma or that begin the text. Finally,
+// we look to see that the remaining characters are only whitespace or ']' or
+// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
+
+ if (/^[\],:{}\s]*$/
+ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
+
+// In the third stage we use the eval function to compile the text into a
+// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
+// in JavaScript: it can begin a block or an object literal. We wrap the text
+// in parens to eliminate the ambiguity.
+
+ j = eval('(' + text + ')');
+
+// In the optional fourth stage, we recursively walk the new structure, passing
+// each name/value pair to a reviver function for possible transformation.
+
+ return typeof reviver === 'function'
+ ? walk({'': j}, '')
+ : j;
+ }
+
+// If the text is not JSON parseable, then a SyntaxError is thrown.
+
+ throw new SyntaxError('JSON.parse');
+ };
+ }
+}());/**
+ * History.js MooTools Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ MooTools = window.MooTools,
+ Element = window.Element;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Make MooTools aware of History.js Events
+ Object.append(Element.NativeEvents,{
+ 'popstate':2,
+ 'hashchange':2
+ });
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {function} callback
+ * @return {void}
+ */
+ bind: function(el,event,callback){
+ var El = typeof el === 'string' ? document.id(el) : el;
+ El.addEvent(event,callback);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return void
+ */
+ trigger: function(el,event,extra){
+ var El = typeof el === 'string' ? document.id(el) : el;
+ El.fireEvent(event,extra);
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {string} key - key for the event data to extract
+ * @param {string} event - custom and standard events
+ * @return {mixed}
+ */
+ extractEventData: function(key,event){
+ // MooTools Native then MooTools Custom
+ var result = (event && event.event && event.event[key]) || (event && event[key]) || undefined;
+
+ // Return
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {function} callback
+ * @return {void}
+ */
+ onDomLoad: function(callback) {
+ window.addEvent('domready',callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js HTML4 Support
+ * Depends on the HTML5 Support
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ document = window.document, // Make sure we are using the correct document
+ setTimeout = window.setTimeout||setTimeout,
+ clearTimeout = window.clearTimeout||clearTimeout,
+ setInterval = window.setInterval||setInterval,
+ History = window.History = window.History||{}; // Public History Object
+
+ // Check Existence
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ throw new Error('History.js HTML4 Support has already been loaded...');
+ }
+
+
+ // ========================================================================
+ // Initialise HTML4 Support
+
+ // Initialise HTML4 Support
+ History.initHtml4 = function(){
+ // Initialise
+ if ( typeof History.initHtml4.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initHtml4.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Properties
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = true;
+
+
+ // ====================================================================
+ // Hash Storage
+
+ /**
+ * History.savedHashes
+ * Store the hashes in an array
+ */
+ History.savedHashes = [];
+
+ /**
+ * History.isLastHash(newHash)
+ * Checks if the hash is the last hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.isLastHash = function(newHash){
+ // Prepare
+ var oldHash = History.getHashByIndex(),
+ isLast;
+
+ // Check
+ isLast = newHash === oldHash;
+
+ // Return isLast
+ return isLast;
+ };
+
+ /**
+ * History.isHashEqual(newHash, oldHash)
+ * Checks to see if two hashes are functionally equal
+ * @param {string} newHash
+ * @param {string} oldHash
+ * @return {boolean} true
+ */
+ History.isHashEqual = function(newHash, oldHash){
+ newHash = encodeURIComponent(newHash).replace(/%25/g, "%");
+ oldHash = encodeURIComponent(oldHash).replace(/%25/g, "%");
+ return newHash === oldHash;
+ };
+
+ /**
+ * History.saveHash(newHash)
+ * Push a Hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.saveHash = function(newHash){
+ // Check Hash
+ if ( History.isLastHash(newHash) ) {
+ return false;
+ }
+
+ // Push the Hash
+ History.savedHashes.push(newHash);
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getHashByIndex()
+ * Gets a hash by the index
+ * @param {integer} index
+ * @return {string}
+ */
+ History.getHashByIndex = function(index){
+ // Prepare
+ var hash = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ hash = History.savedHashes[History.savedHashes.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ hash = History.savedHashes[History.savedHashes.length+index];
+ }
+ else {
+ // Get from the beginning
+ hash = History.savedHashes[index];
+ }
+
+ // Return hash
+ return hash;
+ };
+
+
+ // ====================================================================
+ // Discarded States
+
+ /**
+ * History.discardedHashes
+ * A hashed array of discarded hashes
+ */
+ History.discardedHashes = {};
+
+ /**
+ * History.discardedStates
+ * A hashed array of discarded states
+ */
+ History.discardedStates = {};
+
+ /**
+ * History.discardState(State)
+ * Discards the state by ignoring it through History
+ * @param {object} State
+ * @return {true}
+ */
+ History.discardState = function(discardedState,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Prepare
+ var discardedStateHash = History.getHashByState(discardedState),
+ discardObject;
+
+ // Create Discard Object
+ discardObject = {
+ 'discardedState': discardedState,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to DiscardedStates
+ History.discardedStates[discardedStateHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardHash(hash)
+ * Discards the hash by ignoring it through History
+ * @param {string} hash
+ * @return {true}
+ */
+ History.discardHash = function(discardedHash,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Create Discard Object
+ var discardObject = {
+ 'discardedHash': discardedHash,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to discardedHash
+ History.discardedHashes[discardedHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardedState(State)
+ * Checks to see if the state is discarded
+ * @param {object} State
+ * @return {bool}
+ */
+ History.discardedState = function(State){
+ // Prepare
+ var StateHash = History.getHashByState(State),
+ discarded;
+
+ // Check
+ discarded = History.discardedStates[StateHash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.discardedHash(hash)
+ * Checks to see if the state is discarded
+ * @param {string} State
+ * @return {bool}
+ */
+ History.discardedHash = function(hash){
+ // Check
+ var discarded = History.discardedHashes[hash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.recycleState(State)
+ * Allows a discarded state to be used again
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.recycleState = function(State){
+ //History.debug('History.recycleState', arguments);
+ // Prepare
+ var StateHash = History.getHashByState(State);
+
+ // Remove from DiscardedStates
+ if ( History.discardedState(State) ) {
+ delete History.discardedStates[StateHash];
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ====================================================================
+ // HTML4 HashChange Support
+
+ if ( History.emulated.hashChange ) {
+ /*
+ * We must emulate the HTML4 HashChange Support by manually checking for hash changes
+ */
+
+ /**
+ * History.hashChangeInit()
+ * Init the HashChange Emulation
+ */
+ History.hashChangeInit = function(){
+ // Define our Checker Function
+ History.checkerFunction = null;
+
+ // Define some variables that will help in our checker function
+ var lastDocumentHash = '',
+ iframeId, iframe,
+ lastIframeHash, checkerRunning,
+ startedWithHash = Boolean(History.getHash());
+
+ // Handle depending on the browser
+ if ( History.isInternetExplorer() ) {
+ // IE6 and IE7
+ // We need to use an iframe to emulate the back and forward buttons
+
+ // Create iFrame
+ iframeId = 'historyjs-iframe';
+ iframe = document.createElement('iframe');
+
+ // Adjust iFarme
+ // IE 6 requires iframe to have a src on HTTPS pages, otherwise it will throw a
+ // "This page contains both secure and nonsecure items" warning.
+ iframe.setAttribute('id', iframeId);
+ iframe.setAttribute('src', '#');
+ iframe.style.display = 'none';
+
+ // Append iFrame
+ document.body.appendChild(iframe);
+
+ // Create initial history entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Define some variables that will help in our checker function
+ lastIframeHash = '';
+ checkerRunning = false;
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Check Running
+ if ( checkerRunning ) {
+ return false;
+ }
+
+ // Update Running
+ checkerRunning = true;
+
+ // Fetch
+ var
+ documentHash = History.getHash(),
+ iframeHash = History.getHash(iframe.contentWindow.document);
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Create a history entry in the iframe
+ if ( iframeHash !== documentHash ) {
+ //History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);
+
+ // Equalise
+ lastIframeHash = iframeHash = documentHash;
+
+ // Create History Entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Update the iframe's hash
+ iframe.contentWindow.document.location.hash = History.escapeHash(documentHash);
+ }
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // The iFrame Hash has changed (back button caused)
+ else if ( iframeHash !== lastIframeHash ) {
+ //History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);
+
+ // Equalise
+ lastIframeHash = iframeHash;
+
+ // If there is no iframe hash that means we're at the original
+ // iframe state.
+ // And if there was a hash on the original request, the original
+ // iframe state was replaced instantly, so skip this state and take
+ // the user back to where they came from.
+ if (startedWithHash && iframeHash === '') {
+ History.back();
+ }
+ else {
+ // Update the Hash
+ History.setHash(iframeHash,false);
+ }
+ }
+
+ // Reset Running
+ checkerRunning = false;
+
+ // Return true
+ return true;
+ };
+ }
+ else {
+ // We are not IE
+ // Firefox 1 or 2, Opera
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Prepare
+ var documentHash = History.getHash()||'';
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // Return true
+ return true;
+ };
+ }
+
+ // Apply the checker function
+ History.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));
+
+ // Done
+ return true;
+ }; // History.hashChangeInit
+
+ // Bind hashChangeInit
+ History.Adapter.onDomLoad(History.hashChangeInit);
+
+ } // History.emulated.hashChange
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * We must emulate the HTML5 State Management by using HTML4 HashChange
+ */
+
+ /**
+ * History.onHashChange(event)
+ * Trigger HTML5's window.onpopstate via HTML4 HashChange Support
+ */
+ History.onHashChange = function(event){
+ //History.debug('History.onHashChange', arguments);
+
+ // Prepare
+ var currentUrl = ((event && event.newURL) || History.getLocationHref()),
+ currentHash = History.getHashByUrl(currentUrl),
+ currentState = null,
+ currentStateHash = null,
+ currentStateHashExits = null,
+ discardObject;
+
+ // Check if we are the same state
+ if ( History.isLastHash(currentHash) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onHashChange: no change');
+ History.busy(false);
+ return false;
+ }
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Store our location for use in detecting back/forward direction
+ History.saveHash(currentHash);
+
+ // Expand Hash
+ if ( currentHash && History.isTraditionalAnchor(currentHash) ) {
+ //History.debug('History.onHashChange: traditional anchor', currentHash);
+ // Traditional Anchor Hash
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ return false;
+ }
+
+ // Create State
+ currentState = History.extractState(History.getFullUrl(currentHash||History.getLocationHref()),true);
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(currentState) ) {
+ //History.debug('History.onHashChange: no change');
+ // There has been no change (just the page's hash has finally propagated)
+ History.busy(false);
+ return false;
+ }
+
+ // Create the state Hash
+ currentStateHash = History.getHashByState(currentState);
+
+ // Check if we are DiscardedState
+ discardObject = History.discardedState(currentState);
+ if ( discardObject ) {
+ // Ignore this state as it has been discarded and go back to the state before it
+ if ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {
+ // We are going backwards
+ //History.debug('History.onHashChange: go backwards');
+ History.back(false);
+ } else {
+ // We are going forwards
+ //History.debug('History.onHashChange: go forwards');
+ History.forward(false);
+ }
+ return false;
+ }
+
+ // Push the new HTML5 State
+ //History.debug('History.onHashChange: success hashchange');
+ History.pushState(currentState.data,currentState.title,encodeURI(currentState.url),false);
+
+ // End onHashChange closure
+ return true;
+ };
+ History.Adapter.bind(window,'hashchange',History.onHashChange);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Object
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ html4Hash = History.getHash(),
+ wasExpected = History.expectedStateId == newState.id;
+
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Check if we are the same State
+ if ( newStateHash === oldStateHash ) {
+ //History.debug('History.pushState: no change', newStateHash);
+ History.busy(false);
+ return false;
+ }
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ if(!wasExpected)
+ History.Adapter.trigger(window,'statechange');
+
+ // Update HTML4 Hash
+ if ( !History.isHashEqual(newStateHash, html4Hash) && !History.isHashEqual(newStateHash, History.getShortUrl(History.getLocationHref())) ) {
+ History.setHash(newStateHash,false);
+ }
+
+ History.busy(false);
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Objects
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ previousState = History.getStateByIndex(-2);
+
+ // Discard Old State
+ History.discardState(oldState,newState,previousState);
+
+ // If the url hasn't changed, just store and save the state
+ // and fire a statechange event to be consistent with the
+ // html 5 api
+ if ( newStateHash === oldStateHash ) {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ //History.debug('History.pushState: trigger popstate');
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+ }
+ else {
+ // Alias to PushState
+ History.pushState(newState.data,newState.title,newState.url,false);
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // History.emulated.pushState
+
+
+
+ // ====================================================================
+ // Initialise
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /**
+ * Ensure initial state is handled correctly
+ */
+ if ( History.getHash() && !History.emulated.hashChange ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+
+ } // History.emulated.pushState
+
+ }; // History.initHtml4
+
+ // Try to Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/native.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/native.history.js
new file mode 100644
index 00000000..fe39c496
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/native.history.js
@@ -0,0 +1,3335 @@
+/*
+ json2.js
+ 2012-10-08
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ See http://www.JSON.org/js.html
+
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
+ This file creates a global JSON object containing two methods: stringify
+ and parse.
+
+ JSON.stringify(value, replacer, space)
+ value any JavaScript value, usually an object or array.
+
+ replacer an optional parameter that determines how object
+ values are stringified for objects. It can be a
+ function or an array of strings.
+
+ space an optional parameter that specifies the indentation
+ of nested structures. If it is omitted, the text will
+ be packed without extra whitespace. If it is a number,
+ it will specify the number of spaces to indent at each
+ level. If it is a string (such as '\t' or ' '),
+ it contains the characters used to indent at each level.
+
+ This method produces a JSON text from a JavaScript value.
+
+ When an object value is found, if the object contains a toJSON
+ method, its toJSON method will be called and the result will be
+ stringified. A toJSON method does not serialize: it returns the
+ value represented by the name/value pair that should be serialized,
+ or undefined if nothing should be serialized. The toJSON method
+ will be passed the key associated with the value, and this will be
+ bound to the value
+
+ For example, this would serialize Dates as ISO strings.
+
+ Date.prototype.toJSON = function (key) {
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ return this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z';
+ };
+
+ You can provide an optional replacer method. It will be passed the
+ key and value of each member, with this bound to the containing
+ object. The value that is returned from your method will be
+ serialized. If your method returns undefined, then the member will
+ be excluded from the serialization.
+
+ If the replacer parameter is an array of strings, then it will be
+ used to select the members to be serialized. It filters the results
+ such that only members with keys listed in the replacer array are
+ stringified.
+
+ Values that do not have JSON representations, such as undefined or
+ functions, will not be serialized. Such values in objects will be
+ dropped; in arrays they will be replaced with null. You can use
+ a replacer function to replace those with JSON values.
+ JSON.stringify(undefined) returns undefined.
+
+ The optional space parameter produces a stringification of the
+ value that is filled with line breaks and indentation to make it
+ easier to read.
+
+ If the space parameter is a non-empty string, then that string will
+ be used for indentation. If the space parameter is a number, then
+ the indentation will be that many spaces.
+
+ Example:
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
+ // text is '["e",{"pluribus":"unum"}]'
+
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+ text = JSON.stringify([new Date()], function (key, value) {
+ return this[key] instanceof Date ?
+ 'Date(' + this[key] + ')' : value;
+ });
+ // text is '["Date(---current time---)"]'
+
+
+ JSON.parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = JSON.parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
+ }
+ }
+ return value;
+ });
+
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+ var d;
+ if (typeof value === 'string' &&
+ value.slice(0, 5) === 'Date(' &&
+ value.slice(-1) === ')') {
+ d = new Date(value.slice(5, -1));
+ if (d) {
+ return d;
+ }
+ }
+ return value;
+ });
+
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+*/
+
+/*jslint evil: true, regexp: true */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
+ test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.
+
+if (typeof JSON !== 'object') {
+ JSON = {};
+}
+
+(function () {
+ 'use strict';
+
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ if (typeof Date.prototype.toJSON !== 'function') {
+
+ Date.prototype.toJSON = function (key) {
+
+ return isFinite(this.valueOf())
+ ? this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z'
+ : null;
+ };
+
+ String.prototype.toJSON =
+ Number.prototype.toJSON =
+ Boolean.prototype.toJSON = function (key) {
+ return this.valueOf();
+ };
+ }
+
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ gap,
+ indent,
+ meta = { // table of character substitutions
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ rep;
+
+
+ function quote(string) {
+
+// If the string contains no control characters, no quote characters, and no
+// backslash characters, then we can safely slap some quotes around it.
+// Otherwise we must also replace the offending characters with safe escape
+// sequences.
+
+ escapable.lastIndex = 0;
+ return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
+ var c = meta[a];
+ return typeof c === 'string'
+ ? c
+ : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"' : '"' + string + '"';
+ }
+
+
+ function str(key, holder) {
+
+// Produce a string from holder[key].
+
+ var i, // The loop counter.
+ k, // The member key.
+ v, // The member value.
+ length,
+ mind = gap,
+ partial,
+ value = holder[key];
+
+// If the value has a toJSON method, call it to obtain a replacement value.
+
+ if (value && typeof value === 'object' &&
+ typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+
+// If we were called with a replacer function, then call the replacer to
+// obtain a replacement value.
+
+ if (typeof rep === 'function') {
+ value = rep.call(holder, key, value);
+ }
+
+// What happens next depends on the value's type.
+
+ switch (typeof value) {
+ case 'string':
+ return quote(value);
+
+ case 'number':
+
+// JSON numbers must be finite. Encode non-finite numbers as null.
+
+ return isFinite(value) ? String(value) : 'null';
+
+ case 'boolean':
+ case 'null':
+
+// If the value is a boolean or null, convert it to a string. Note:
+// typeof null does not produce 'null'. The case is included here in
+// the remote chance that this gets fixed someday.
+
+ return String(value);
+
+// If the type is 'object', we might be dealing with an object or an array or
+// null.
+
+ case 'object':
+
+// Due to a specification blunder in ECMAScript, typeof null is 'object',
+// so watch out for that case.
+
+ if (!value) {
+ return 'null';
+ }
+
+// Make an array to hold the partial results of stringifying this object value.
+
+ gap += indent;
+ partial = [];
+
+// Is the value an array?
+
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+// The value is an array. Stringify every element. Use null as a placeholder
+// for non-JSON values.
+
+ length = value.length;
+ for (i = 0; i < length; i += 1) {
+ partial[i] = str(i, value) || 'null';
+ }
+
+// Join all of the elements together, separated with commas, and wrap them in
+// brackets.
+
+ v = partial.length === 0
+ ? '[]'
+ : gap
+ ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
+ : '[' + partial.join(',') + ']';
+ gap = mind;
+ return v;
+ }
+
+// If the replacer is an array, use it to select the members to be stringified.
+
+ if (rep && typeof rep === 'object') {
+ length = rep.length;
+ for (i = 0; i < length; i += 1) {
+ if (typeof rep[i] === 'string') {
+ k = rep[i];
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ } else {
+
+// Otherwise, iterate through all of the keys in the object.
+
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ }
+
+// Join all of the member texts together, separated with commas,
+// and wrap them in braces.
+
+ v = partial.length === 0
+ ? '{}'
+ : gap
+ ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
+ : '{' + partial.join(',') + '}';
+ gap = mind;
+ return v;
+ }
+ }
+
+// If the JSON object does not yet have a stringify method, give it one.
+
+ if (typeof JSON.stringify !== 'function') {
+ JSON.stringify = function (value, replacer, space) {
+
+// The stringify method takes a value and an optional replacer, and an optional
+// space parameter, and returns a JSON text. The replacer can be a function
+// that can replace values, or an array of strings that will select the keys.
+// A default replacer method can be provided. Use of the space parameter can
+// produce text that is more easily readable.
+
+ var i;
+ gap = '';
+ indent = '';
+
+// If the space parameter is a number, make an indent string containing that
+// many spaces.
+
+ if (typeof space === 'number') {
+ for (i = 0; i < space; i += 1) {
+ indent += ' ';
+ }
+
+// If the space parameter is a string, it will be used as the indent string.
+
+ } else if (typeof space === 'string') {
+ indent = space;
+ }
+
+// If there is a replacer, it must be a function or an array.
+// Otherwise, throw an error.
+
+ rep = replacer;
+ if (replacer && typeof replacer !== 'function' &&
+ (typeof replacer !== 'object' ||
+ typeof replacer.length !== 'number')) {
+ throw new Error('JSON.stringify');
+ }
+
+// Make a fake root object containing our value under the key of ''.
+// Return the result of stringifying the value.
+
+ return str('', {'': value});
+ };
+ }
+
+
+// If the JSON object does not yet have a parse method, give it one.
+
+ if (typeof JSON.parse !== 'function') {
+ JSON.parse = function (text, reviver) {
+
+// The parse method takes a text and an optional reviver function, and returns
+// a JavaScript value if the text is a valid JSON text.
+
+ var j;
+
+ function walk(holder, key) {
+
+// The walk method is used to recursively walk the resulting structure so
+// that modifications can be made.
+
+ var k, v, value = holder[key];
+ if (value && typeof value === 'object') {
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = walk(value, k);
+ if (v !== undefined) {
+ value[k] = v;
+ } else {
+ delete value[k];
+ }
+ }
+ }
+ }
+ return reviver.call(holder, key, value);
+ }
+
+
+// Parsing happens in four stages. In the first stage, we replace certain
+// Unicode characters with escape sequences. JavaScript handles many characters
+// incorrectly, either silently deleting them, or treating them as line endings.
+
+ text = String(text);
+ cx.lastIndex = 0;
+ if (cx.test(text)) {
+ text = text.replace(cx, function (a) {
+ return '\\u' +
+ ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ });
+ }
+
+// In the second stage, we run the text against regular expressions that look
+// for non-JSON patterns. We are especially concerned with '()' and 'new'
+// because they can cause invocation, and '=' because it can cause mutation.
+// But just to be safe, we want to reject all unexpected forms.
+
+// We split the second stage into 4 regexp operations in order to work around
+// crippling inefficiencies in IE's and Safari's regexp engines. First we
+// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
+// replace all simple value tokens with ']' characters. Third, we delete all
+// open brackets that follow a colon or comma or that begin the text. Finally,
+// we look to see that the remaining characters are only whitespace or ']' or
+// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
+
+ if (/^[\],:{}\s]*$/
+ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
+
+// In the third stage we use the eval function to compile the text into a
+// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
+// in JavaScript: it can begin a block or an object literal. We wrap the text
+// in parens to eliminate the ambiguity.
+
+ j = eval('(' + text + ')');
+
+// In the optional fourth stage, we recursively walk the new structure, passing
+// each name/value pair to a reviver function for possible transformation.
+
+ return typeof reviver === 'function'
+ ? walk({'': j}, '')
+ : j;
+ }
+
+// If the text is not JSON parseable, then a SyntaxError is thrown.
+
+ throw new SyntaxError('JSON.parse');
+ };
+ }
+}());/**
+ * History.js Native Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var History = window.History = window.History||{};
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.handlers[uid][eventName] = Array
+ */
+ handlers: {},
+
+ /**
+ * History.Adapter._uid
+ * The current element unique identifier
+ */
+ _uid: 1,
+
+ /**
+ * History.Adapter.uid(element)
+ * @param {Element} element
+ * @return {String} uid
+ */
+ uid: function(element){
+ return element._uid || (element._uid = History.Adapter._uid++);
+ },
+
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element} element
+ * @param {String} eventName - custom and standard events
+ * @param {Function} callback
+ * @return
+ */
+ bind: function(element,eventName,callback){
+ // Prepare
+ var uid = History.Adapter.uid(element);
+
+ // Apply Listener
+ History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
+ History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
+ History.Adapter.handlers[uid][eventName].push(callback);
+
+ // Bind Global Listener
+ element['on'+eventName] = (function(element,eventName){
+ return function(event){
+ History.Adapter.trigger(element,eventName,event);
+ };
+ })(element,eventName);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element} element
+ * @param {String} eventName - custom and standard events
+ * @param {Object} event - a object of event data
+ * @return
+ */
+ trigger: function(element,eventName,event){
+ // Prepare
+ event = event || {};
+ var uid = History.Adapter.uid(element),
+ i,n;
+
+ // Apply Listener
+ History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
+ History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
+
+ // Fire Listeners
+ for ( i=0,n=History.Adapter.handlers[uid][eventName].length; i
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ document = window.document, // Make sure we are using the correct document
+ setTimeout = window.setTimeout||setTimeout,
+ clearTimeout = window.clearTimeout||clearTimeout,
+ setInterval = window.setInterval||setInterval,
+ History = window.History = window.History||{}; // Public History Object
+
+ // Check Existence
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ throw new Error('History.js HTML4 Support has already been loaded...');
+ }
+
+
+ // ========================================================================
+ // Initialise HTML4 Support
+
+ // Initialise HTML4 Support
+ History.initHtml4 = function(){
+ // Initialise
+ if ( typeof History.initHtml4.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initHtml4.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Properties
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = true;
+
+
+ // ====================================================================
+ // Hash Storage
+
+ /**
+ * History.savedHashes
+ * Store the hashes in an array
+ */
+ History.savedHashes = [];
+
+ /**
+ * History.isLastHash(newHash)
+ * Checks if the hash is the last hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.isLastHash = function(newHash){
+ // Prepare
+ var oldHash = History.getHashByIndex(),
+ isLast;
+
+ // Check
+ isLast = newHash === oldHash;
+
+ // Return isLast
+ return isLast;
+ };
+
+ /**
+ * History.isHashEqual(newHash, oldHash)
+ * Checks to see if two hashes are functionally equal
+ * @param {string} newHash
+ * @param {string} oldHash
+ * @return {boolean} true
+ */
+ History.isHashEqual = function(newHash, oldHash){
+ newHash = encodeURIComponent(newHash).replace(/%25/g, "%");
+ oldHash = encodeURIComponent(oldHash).replace(/%25/g, "%");
+ return newHash === oldHash;
+ };
+
+ /**
+ * History.saveHash(newHash)
+ * Push a Hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.saveHash = function(newHash){
+ // Check Hash
+ if ( History.isLastHash(newHash) ) {
+ return false;
+ }
+
+ // Push the Hash
+ History.savedHashes.push(newHash);
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getHashByIndex()
+ * Gets a hash by the index
+ * @param {integer} index
+ * @return {string}
+ */
+ History.getHashByIndex = function(index){
+ // Prepare
+ var hash = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ hash = History.savedHashes[History.savedHashes.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ hash = History.savedHashes[History.savedHashes.length+index];
+ }
+ else {
+ // Get from the beginning
+ hash = History.savedHashes[index];
+ }
+
+ // Return hash
+ return hash;
+ };
+
+
+ // ====================================================================
+ // Discarded States
+
+ /**
+ * History.discardedHashes
+ * A hashed array of discarded hashes
+ */
+ History.discardedHashes = {};
+
+ /**
+ * History.discardedStates
+ * A hashed array of discarded states
+ */
+ History.discardedStates = {};
+
+ /**
+ * History.discardState(State)
+ * Discards the state by ignoring it through History
+ * @param {object} State
+ * @return {true}
+ */
+ History.discardState = function(discardedState,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Prepare
+ var discardedStateHash = History.getHashByState(discardedState),
+ discardObject;
+
+ // Create Discard Object
+ discardObject = {
+ 'discardedState': discardedState,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to DiscardedStates
+ History.discardedStates[discardedStateHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardHash(hash)
+ * Discards the hash by ignoring it through History
+ * @param {string} hash
+ * @return {true}
+ */
+ History.discardHash = function(discardedHash,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Create Discard Object
+ var discardObject = {
+ 'discardedHash': discardedHash,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to discardedHash
+ History.discardedHashes[discardedHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardedState(State)
+ * Checks to see if the state is discarded
+ * @param {object} State
+ * @return {bool}
+ */
+ History.discardedState = function(State){
+ // Prepare
+ var StateHash = History.getHashByState(State),
+ discarded;
+
+ // Check
+ discarded = History.discardedStates[StateHash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.discardedHash(hash)
+ * Checks to see if the state is discarded
+ * @param {string} State
+ * @return {bool}
+ */
+ History.discardedHash = function(hash){
+ // Check
+ var discarded = History.discardedHashes[hash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.recycleState(State)
+ * Allows a discarded state to be used again
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.recycleState = function(State){
+ //History.debug('History.recycleState', arguments);
+ // Prepare
+ var StateHash = History.getHashByState(State);
+
+ // Remove from DiscardedStates
+ if ( History.discardedState(State) ) {
+ delete History.discardedStates[StateHash];
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ====================================================================
+ // HTML4 HashChange Support
+
+ if ( History.emulated.hashChange ) {
+ /*
+ * We must emulate the HTML4 HashChange Support by manually checking for hash changes
+ */
+
+ /**
+ * History.hashChangeInit()
+ * Init the HashChange Emulation
+ */
+ History.hashChangeInit = function(){
+ // Define our Checker Function
+ History.checkerFunction = null;
+
+ // Define some variables that will help in our checker function
+ var lastDocumentHash = '',
+ iframeId, iframe,
+ lastIframeHash, checkerRunning,
+ startedWithHash = Boolean(History.getHash());
+
+ // Handle depending on the browser
+ if ( History.isInternetExplorer() ) {
+ // IE6 and IE7
+ // We need to use an iframe to emulate the back and forward buttons
+
+ // Create iFrame
+ iframeId = 'historyjs-iframe';
+ iframe = document.createElement('iframe');
+
+ // Adjust iFarme
+ // IE 6 requires iframe to have a src on HTTPS pages, otherwise it will throw a
+ // "This page contains both secure and nonsecure items" warning.
+ iframe.setAttribute('id', iframeId);
+ iframe.setAttribute('src', '#');
+ iframe.style.display = 'none';
+
+ // Append iFrame
+ document.body.appendChild(iframe);
+
+ // Create initial history entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Define some variables that will help in our checker function
+ lastIframeHash = '';
+ checkerRunning = false;
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Check Running
+ if ( checkerRunning ) {
+ return false;
+ }
+
+ // Update Running
+ checkerRunning = true;
+
+ // Fetch
+ var
+ documentHash = History.getHash(),
+ iframeHash = History.getHash(iframe.contentWindow.document);
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Create a history entry in the iframe
+ if ( iframeHash !== documentHash ) {
+ //History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);
+
+ // Equalise
+ lastIframeHash = iframeHash = documentHash;
+
+ // Create History Entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Update the iframe's hash
+ iframe.contentWindow.document.location.hash = History.escapeHash(documentHash);
+ }
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // The iFrame Hash has changed (back button caused)
+ else if ( iframeHash !== lastIframeHash ) {
+ //History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);
+
+ // Equalise
+ lastIframeHash = iframeHash;
+
+ // If there is no iframe hash that means we're at the original
+ // iframe state.
+ // And if there was a hash on the original request, the original
+ // iframe state was replaced instantly, so skip this state and take
+ // the user back to where they came from.
+ if (startedWithHash && iframeHash === '') {
+ History.back();
+ }
+ else {
+ // Update the Hash
+ History.setHash(iframeHash,false);
+ }
+ }
+
+ // Reset Running
+ checkerRunning = false;
+
+ // Return true
+ return true;
+ };
+ }
+ else {
+ // We are not IE
+ // Firefox 1 or 2, Opera
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Prepare
+ var documentHash = History.getHash()||'';
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // Return true
+ return true;
+ };
+ }
+
+ // Apply the checker function
+ History.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));
+
+ // Done
+ return true;
+ }; // History.hashChangeInit
+
+ // Bind hashChangeInit
+ History.Adapter.onDomLoad(History.hashChangeInit);
+
+ } // History.emulated.hashChange
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * We must emulate the HTML5 State Management by using HTML4 HashChange
+ */
+
+ /**
+ * History.onHashChange(event)
+ * Trigger HTML5's window.onpopstate via HTML4 HashChange Support
+ */
+ History.onHashChange = function(event){
+ //History.debug('History.onHashChange', arguments);
+
+ // Prepare
+ var currentUrl = ((event && event.newURL) || History.getLocationHref()),
+ currentHash = History.getHashByUrl(currentUrl),
+ currentState = null,
+ currentStateHash = null,
+ currentStateHashExits = null,
+ discardObject;
+
+ // Check if we are the same state
+ if ( History.isLastHash(currentHash) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onHashChange: no change');
+ History.busy(false);
+ return false;
+ }
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Store our location for use in detecting back/forward direction
+ History.saveHash(currentHash);
+
+ // Expand Hash
+ if ( currentHash && History.isTraditionalAnchor(currentHash) ) {
+ //History.debug('History.onHashChange: traditional anchor', currentHash);
+ // Traditional Anchor Hash
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ return false;
+ }
+
+ // Create State
+ currentState = History.extractState(History.getFullUrl(currentHash||History.getLocationHref()),true);
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(currentState) ) {
+ //History.debug('History.onHashChange: no change');
+ // There has been no change (just the page's hash has finally propagated)
+ History.busy(false);
+ return false;
+ }
+
+ // Create the state Hash
+ currentStateHash = History.getHashByState(currentState);
+
+ // Check if we are DiscardedState
+ discardObject = History.discardedState(currentState);
+ if ( discardObject ) {
+ // Ignore this state as it has been discarded and go back to the state before it
+ if ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {
+ // We are going backwards
+ //History.debug('History.onHashChange: go backwards');
+ History.back(false);
+ } else {
+ // We are going forwards
+ //History.debug('History.onHashChange: go forwards');
+ History.forward(false);
+ }
+ return false;
+ }
+
+ // Push the new HTML5 State
+ //History.debug('History.onHashChange: success hashchange');
+ History.pushState(currentState.data,currentState.title,encodeURI(currentState.url),false);
+
+ // End onHashChange closure
+ return true;
+ };
+ History.Adapter.bind(window,'hashchange',History.onHashChange);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Object
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ html4Hash = History.getHash(),
+ wasExpected = History.expectedStateId == newState.id;
+
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Check if we are the same State
+ if ( newStateHash === oldStateHash ) {
+ //History.debug('History.pushState: no change', newStateHash);
+ History.busy(false);
+ return false;
+ }
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ if(!wasExpected)
+ History.Adapter.trigger(window,'statechange');
+
+ // Update HTML4 Hash
+ if ( !History.isHashEqual(newStateHash, html4Hash) && !History.isHashEqual(newStateHash, History.getShortUrl(History.getLocationHref())) ) {
+ History.setHash(newStateHash,false);
+ }
+
+ History.busy(false);
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Objects
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ previousState = History.getStateByIndex(-2);
+
+ // Discard Old State
+ History.discardState(oldState,newState,previousState);
+
+ // If the url hasn't changed, just store and save the state
+ // and fire a statechange event to be consistent with the
+ // html 5 api
+ if ( newStateHash === oldStateHash ) {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ //History.debug('History.pushState: trigger popstate');
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+ }
+ else {
+ // Alias to PushState
+ History.pushState(newState.data,newState.title,newState.url,false);
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // History.emulated.pushState
+
+
+
+ // ====================================================================
+ // Initialise
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /**
+ * Ensure initial state is handled correctly
+ */
+ if ( History.getHash() && !History.emulated.hashChange ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+
+ } // History.emulated.pushState
+
+ }; // History.initHtml4
+
+ // Try to Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/right.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/right.history.js
new file mode 100644
index 00000000..ef0eb22f
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/right.history.js
@@ -0,0 +1,3292 @@
+/*
+ json2.js
+ 2012-10-08
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ See http://www.JSON.org/js.html
+
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
+ This file creates a global JSON object containing two methods: stringify
+ and parse.
+
+ JSON.stringify(value, replacer, space)
+ value any JavaScript value, usually an object or array.
+
+ replacer an optional parameter that determines how object
+ values are stringified for objects. It can be a
+ function or an array of strings.
+
+ space an optional parameter that specifies the indentation
+ of nested structures. If it is omitted, the text will
+ be packed without extra whitespace. If it is a number,
+ it will specify the number of spaces to indent at each
+ level. If it is a string (such as '\t' or ' '),
+ it contains the characters used to indent at each level.
+
+ This method produces a JSON text from a JavaScript value.
+
+ When an object value is found, if the object contains a toJSON
+ method, its toJSON method will be called and the result will be
+ stringified. A toJSON method does not serialize: it returns the
+ value represented by the name/value pair that should be serialized,
+ or undefined if nothing should be serialized. The toJSON method
+ will be passed the key associated with the value, and this will be
+ bound to the value
+
+ For example, this would serialize Dates as ISO strings.
+
+ Date.prototype.toJSON = function (key) {
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ return this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z';
+ };
+
+ You can provide an optional replacer method. It will be passed the
+ key and value of each member, with this bound to the containing
+ object. The value that is returned from your method will be
+ serialized. If your method returns undefined, then the member will
+ be excluded from the serialization.
+
+ If the replacer parameter is an array of strings, then it will be
+ used to select the members to be serialized. It filters the results
+ such that only members with keys listed in the replacer array are
+ stringified.
+
+ Values that do not have JSON representations, such as undefined or
+ functions, will not be serialized. Such values in objects will be
+ dropped; in arrays they will be replaced with null. You can use
+ a replacer function to replace those with JSON values.
+ JSON.stringify(undefined) returns undefined.
+
+ The optional space parameter produces a stringification of the
+ value that is filled with line breaks and indentation to make it
+ easier to read.
+
+ If the space parameter is a non-empty string, then that string will
+ be used for indentation. If the space parameter is a number, then
+ the indentation will be that many spaces.
+
+ Example:
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
+ // text is '["e",{"pluribus":"unum"}]'
+
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+ text = JSON.stringify([new Date()], function (key, value) {
+ return this[key] instanceof Date ?
+ 'Date(' + this[key] + ')' : value;
+ });
+ // text is '["Date(---current time---)"]'
+
+
+ JSON.parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = JSON.parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
+ }
+ }
+ return value;
+ });
+
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+ var d;
+ if (typeof value === 'string' &&
+ value.slice(0, 5) === 'Date(' &&
+ value.slice(-1) === ')') {
+ d = new Date(value.slice(5, -1));
+ if (d) {
+ return d;
+ }
+ }
+ return value;
+ });
+
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+*/
+
+/*jslint evil: true, regexp: true */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
+ test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.
+
+if (typeof JSON !== 'object') {
+ JSON = {};
+}
+
+(function () {
+ 'use strict';
+
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ if (typeof Date.prototype.toJSON !== 'function') {
+
+ Date.prototype.toJSON = function (key) {
+
+ return isFinite(this.valueOf())
+ ? this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z'
+ : null;
+ };
+
+ String.prototype.toJSON =
+ Number.prototype.toJSON =
+ Boolean.prototype.toJSON = function (key) {
+ return this.valueOf();
+ };
+ }
+
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ gap,
+ indent,
+ meta = { // table of character substitutions
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ rep;
+
+
+ function quote(string) {
+
+// If the string contains no control characters, no quote characters, and no
+// backslash characters, then we can safely slap some quotes around it.
+// Otherwise we must also replace the offending characters with safe escape
+// sequences.
+
+ escapable.lastIndex = 0;
+ return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
+ var c = meta[a];
+ return typeof c === 'string'
+ ? c
+ : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"' : '"' + string + '"';
+ }
+
+
+ function str(key, holder) {
+
+// Produce a string from holder[key].
+
+ var i, // The loop counter.
+ k, // The member key.
+ v, // The member value.
+ length,
+ mind = gap,
+ partial,
+ value = holder[key];
+
+// If the value has a toJSON method, call it to obtain a replacement value.
+
+ if (value && typeof value === 'object' &&
+ typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+
+// If we were called with a replacer function, then call the replacer to
+// obtain a replacement value.
+
+ if (typeof rep === 'function') {
+ value = rep.call(holder, key, value);
+ }
+
+// What happens next depends on the value's type.
+
+ switch (typeof value) {
+ case 'string':
+ return quote(value);
+
+ case 'number':
+
+// JSON numbers must be finite. Encode non-finite numbers as null.
+
+ return isFinite(value) ? String(value) : 'null';
+
+ case 'boolean':
+ case 'null':
+
+// If the value is a boolean or null, convert it to a string. Note:
+// typeof null does not produce 'null'. The case is included here in
+// the remote chance that this gets fixed someday.
+
+ return String(value);
+
+// If the type is 'object', we might be dealing with an object or an array or
+// null.
+
+ case 'object':
+
+// Due to a specification blunder in ECMAScript, typeof null is 'object',
+// so watch out for that case.
+
+ if (!value) {
+ return 'null';
+ }
+
+// Make an array to hold the partial results of stringifying this object value.
+
+ gap += indent;
+ partial = [];
+
+// Is the value an array?
+
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+// The value is an array. Stringify every element. Use null as a placeholder
+// for non-JSON values.
+
+ length = value.length;
+ for (i = 0; i < length; i += 1) {
+ partial[i] = str(i, value) || 'null';
+ }
+
+// Join all of the elements together, separated with commas, and wrap them in
+// brackets.
+
+ v = partial.length === 0
+ ? '[]'
+ : gap
+ ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
+ : '[' + partial.join(',') + ']';
+ gap = mind;
+ return v;
+ }
+
+// If the replacer is an array, use it to select the members to be stringified.
+
+ if (rep && typeof rep === 'object') {
+ length = rep.length;
+ for (i = 0; i < length; i += 1) {
+ if (typeof rep[i] === 'string') {
+ k = rep[i];
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ } else {
+
+// Otherwise, iterate through all of the keys in the object.
+
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ }
+
+// Join all of the member texts together, separated with commas,
+// and wrap them in braces.
+
+ v = partial.length === 0
+ ? '{}'
+ : gap
+ ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
+ : '{' + partial.join(',') + '}';
+ gap = mind;
+ return v;
+ }
+ }
+
+// If the JSON object does not yet have a stringify method, give it one.
+
+ if (typeof JSON.stringify !== 'function') {
+ JSON.stringify = function (value, replacer, space) {
+
+// The stringify method takes a value and an optional replacer, and an optional
+// space parameter, and returns a JSON text. The replacer can be a function
+// that can replace values, or an array of strings that will select the keys.
+// A default replacer method can be provided. Use of the space parameter can
+// produce text that is more easily readable.
+
+ var i;
+ gap = '';
+ indent = '';
+
+// If the space parameter is a number, make an indent string containing that
+// many spaces.
+
+ if (typeof space === 'number') {
+ for (i = 0; i < space; i += 1) {
+ indent += ' ';
+ }
+
+// If the space parameter is a string, it will be used as the indent string.
+
+ } else if (typeof space === 'string') {
+ indent = space;
+ }
+
+// If there is a replacer, it must be a function or an array.
+// Otherwise, throw an error.
+
+ rep = replacer;
+ if (replacer && typeof replacer !== 'function' &&
+ (typeof replacer !== 'object' ||
+ typeof replacer.length !== 'number')) {
+ throw new Error('JSON.stringify');
+ }
+
+// Make a fake root object containing our value under the key of ''.
+// Return the result of stringifying the value.
+
+ return str('', {'': value});
+ };
+ }
+
+
+// If the JSON object does not yet have a parse method, give it one.
+
+ if (typeof JSON.parse !== 'function') {
+ JSON.parse = function (text, reviver) {
+
+// The parse method takes a text and an optional reviver function, and returns
+// a JavaScript value if the text is a valid JSON text.
+
+ var j;
+
+ function walk(holder, key) {
+
+// The walk method is used to recursively walk the resulting structure so
+// that modifications can be made.
+
+ var k, v, value = holder[key];
+ if (value && typeof value === 'object') {
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = walk(value, k);
+ if (v !== undefined) {
+ value[k] = v;
+ } else {
+ delete value[k];
+ }
+ }
+ }
+ }
+ return reviver.call(holder, key, value);
+ }
+
+
+// Parsing happens in four stages. In the first stage, we replace certain
+// Unicode characters with escape sequences. JavaScript handles many characters
+// incorrectly, either silently deleting them, or treating them as line endings.
+
+ text = String(text);
+ cx.lastIndex = 0;
+ if (cx.test(text)) {
+ text = text.replace(cx, function (a) {
+ return '\\u' +
+ ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ });
+ }
+
+// In the second stage, we run the text against regular expressions that look
+// for non-JSON patterns. We are especially concerned with '()' and 'new'
+// because they can cause invocation, and '=' because it can cause mutation.
+// But just to be safe, we want to reject all unexpected forms.
+
+// We split the second stage into 4 regexp operations in order to work around
+// crippling inefficiencies in IE's and Safari's regexp engines. First we
+// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
+// replace all simple value tokens with ']' characters. Third, we delete all
+// open brackets that follow a colon or comma or that begin the text. Finally,
+// we look to see that the remaining characters are only whitespace or ']' or
+// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
+
+ if (/^[\],:{}\s]*$/
+ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
+
+// In the third stage we use the eval function to compile the text into a
+// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
+// in JavaScript: it can begin a block or an object literal. We wrap the text
+// in parens to eliminate the ambiguity.
+
+ j = eval('(' + text + ')');
+
+// In the optional fourth stage, we recursively walk the new structure, passing
+// each name/value pair to a reviver function for possible transformation.
+
+ return typeof reviver === 'function'
+ ? walk({'': j}, '')
+ : j;
+ }
+
+// If the text is not JSON parseable, then a SyntaxError is thrown.
+
+ throw new SyntaxError('JSON.parse');
+ };
+ }
+}());/**
+ * History.js RightJS Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ document = window.document,
+ RightJS = window.RightJS,
+ $ = RightJS.$;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|Selector} el
+ * @param {String} event - custom and standard events
+ * @param {Function} callback
+ * @return
+ */
+ bind: function(el,event,callback){
+ $(el).on(event,callback);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|Selector} el
+ * @param {String} event - custom and standard events
+ * @param {Object} extraEventData - a object of extra event data
+ * @return
+ */
+ trigger: function(el,event,extraEventData){
+ $(el).fire(event,extraEventData);
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {String} key - key for the event data to extract
+ * @param {String} event - custom and standard events
+ * @return {mixed}
+ */
+ extractEventData: function(key,event){
+ // Right.js Native
+ // Right.js Custom
+ var result = (event && event._ && event._[key]) || undefined;
+
+ // Return
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {Function} callback
+ * @return
+ */
+ onDomLoad: function(callback) {
+ $(document).onReady(callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js HTML4 Support
+ * Depends on the HTML5 Support
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ document = window.document, // Make sure we are using the correct document
+ setTimeout = window.setTimeout||setTimeout,
+ clearTimeout = window.clearTimeout||clearTimeout,
+ setInterval = window.setInterval||setInterval,
+ History = window.History = window.History||{}; // Public History Object
+
+ // Check Existence
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ throw new Error('History.js HTML4 Support has already been loaded...');
+ }
+
+
+ // ========================================================================
+ // Initialise HTML4 Support
+
+ // Initialise HTML4 Support
+ History.initHtml4 = function(){
+ // Initialise
+ if ( typeof History.initHtml4.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initHtml4.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Properties
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = true;
+
+
+ // ====================================================================
+ // Hash Storage
+
+ /**
+ * History.savedHashes
+ * Store the hashes in an array
+ */
+ History.savedHashes = [];
+
+ /**
+ * History.isLastHash(newHash)
+ * Checks if the hash is the last hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.isLastHash = function(newHash){
+ // Prepare
+ var oldHash = History.getHashByIndex(),
+ isLast;
+
+ // Check
+ isLast = newHash === oldHash;
+
+ // Return isLast
+ return isLast;
+ };
+
+ /**
+ * History.isHashEqual(newHash, oldHash)
+ * Checks to see if two hashes are functionally equal
+ * @param {string} newHash
+ * @param {string} oldHash
+ * @return {boolean} true
+ */
+ History.isHashEqual = function(newHash, oldHash){
+ newHash = encodeURIComponent(newHash).replace(/%25/g, "%");
+ oldHash = encodeURIComponent(oldHash).replace(/%25/g, "%");
+ return newHash === oldHash;
+ };
+
+ /**
+ * History.saveHash(newHash)
+ * Push a Hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.saveHash = function(newHash){
+ // Check Hash
+ if ( History.isLastHash(newHash) ) {
+ return false;
+ }
+
+ // Push the Hash
+ History.savedHashes.push(newHash);
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getHashByIndex()
+ * Gets a hash by the index
+ * @param {integer} index
+ * @return {string}
+ */
+ History.getHashByIndex = function(index){
+ // Prepare
+ var hash = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ hash = History.savedHashes[History.savedHashes.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ hash = History.savedHashes[History.savedHashes.length+index];
+ }
+ else {
+ // Get from the beginning
+ hash = History.savedHashes[index];
+ }
+
+ // Return hash
+ return hash;
+ };
+
+
+ // ====================================================================
+ // Discarded States
+
+ /**
+ * History.discardedHashes
+ * A hashed array of discarded hashes
+ */
+ History.discardedHashes = {};
+
+ /**
+ * History.discardedStates
+ * A hashed array of discarded states
+ */
+ History.discardedStates = {};
+
+ /**
+ * History.discardState(State)
+ * Discards the state by ignoring it through History
+ * @param {object} State
+ * @return {true}
+ */
+ History.discardState = function(discardedState,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Prepare
+ var discardedStateHash = History.getHashByState(discardedState),
+ discardObject;
+
+ // Create Discard Object
+ discardObject = {
+ 'discardedState': discardedState,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to DiscardedStates
+ History.discardedStates[discardedStateHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardHash(hash)
+ * Discards the hash by ignoring it through History
+ * @param {string} hash
+ * @return {true}
+ */
+ History.discardHash = function(discardedHash,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Create Discard Object
+ var discardObject = {
+ 'discardedHash': discardedHash,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to discardedHash
+ History.discardedHashes[discardedHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardedState(State)
+ * Checks to see if the state is discarded
+ * @param {object} State
+ * @return {bool}
+ */
+ History.discardedState = function(State){
+ // Prepare
+ var StateHash = History.getHashByState(State),
+ discarded;
+
+ // Check
+ discarded = History.discardedStates[StateHash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.discardedHash(hash)
+ * Checks to see if the state is discarded
+ * @param {string} State
+ * @return {bool}
+ */
+ History.discardedHash = function(hash){
+ // Check
+ var discarded = History.discardedHashes[hash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.recycleState(State)
+ * Allows a discarded state to be used again
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.recycleState = function(State){
+ //History.debug('History.recycleState', arguments);
+ // Prepare
+ var StateHash = History.getHashByState(State);
+
+ // Remove from DiscardedStates
+ if ( History.discardedState(State) ) {
+ delete History.discardedStates[StateHash];
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ====================================================================
+ // HTML4 HashChange Support
+
+ if ( History.emulated.hashChange ) {
+ /*
+ * We must emulate the HTML4 HashChange Support by manually checking for hash changes
+ */
+
+ /**
+ * History.hashChangeInit()
+ * Init the HashChange Emulation
+ */
+ History.hashChangeInit = function(){
+ // Define our Checker Function
+ History.checkerFunction = null;
+
+ // Define some variables that will help in our checker function
+ var lastDocumentHash = '',
+ iframeId, iframe,
+ lastIframeHash, checkerRunning,
+ startedWithHash = Boolean(History.getHash());
+
+ // Handle depending on the browser
+ if ( History.isInternetExplorer() ) {
+ // IE6 and IE7
+ // We need to use an iframe to emulate the back and forward buttons
+
+ // Create iFrame
+ iframeId = 'historyjs-iframe';
+ iframe = document.createElement('iframe');
+
+ // Adjust iFarme
+ // IE 6 requires iframe to have a src on HTTPS pages, otherwise it will throw a
+ // "This page contains both secure and nonsecure items" warning.
+ iframe.setAttribute('id', iframeId);
+ iframe.setAttribute('src', '#');
+ iframe.style.display = 'none';
+
+ // Append iFrame
+ document.body.appendChild(iframe);
+
+ // Create initial history entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Define some variables that will help in our checker function
+ lastIframeHash = '';
+ checkerRunning = false;
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Check Running
+ if ( checkerRunning ) {
+ return false;
+ }
+
+ // Update Running
+ checkerRunning = true;
+
+ // Fetch
+ var
+ documentHash = History.getHash(),
+ iframeHash = History.getHash(iframe.contentWindow.document);
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Create a history entry in the iframe
+ if ( iframeHash !== documentHash ) {
+ //History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);
+
+ // Equalise
+ lastIframeHash = iframeHash = documentHash;
+
+ // Create History Entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Update the iframe's hash
+ iframe.contentWindow.document.location.hash = History.escapeHash(documentHash);
+ }
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // The iFrame Hash has changed (back button caused)
+ else if ( iframeHash !== lastIframeHash ) {
+ //History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);
+
+ // Equalise
+ lastIframeHash = iframeHash;
+
+ // If there is no iframe hash that means we're at the original
+ // iframe state.
+ // And if there was a hash on the original request, the original
+ // iframe state was replaced instantly, so skip this state and take
+ // the user back to where they came from.
+ if (startedWithHash && iframeHash === '') {
+ History.back();
+ }
+ else {
+ // Update the Hash
+ History.setHash(iframeHash,false);
+ }
+ }
+
+ // Reset Running
+ checkerRunning = false;
+
+ // Return true
+ return true;
+ };
+ }
+ else {
+ // We are not IE
+ // Firefox 1 or 2, Opera
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Prepare
+ var documentHash = History.getHash()||'';
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // Return true
+ return true;
+ };
+ }
+
+ // Apply the checker function
+ History.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));
+
+ // Done
+ return true;
+ }; // History.hashChangeInit
+
+ // Bind hashChangeInit
+ History.Adapter.onDomLoad(History.hashChangeInit);
+
+ } // History.emulated.hashChange
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * We must emulate the HTML5 State Management by using HTML4 HashChange
+ */
+
+ /**
+ * History.onHashChange(event)
+ * Trigger HTML5's window.onpopstate via HTML4 HashChange Support
+ */
+ History.onHashChange = function(event){
+ //History.debug('History.onHashChange', arguments);
+
+ // Prepare
+ var currentUrl = ((event && event.newURL) || History.getLocationHref()),
+ currentHash = History.getHashByUrl(currentUrl),
+ currentState = null,
+ currentStateHash = null,
+ currentStateHashExits = null,
+ discardObject;
+
+ // Check if we are the same state
+ if ( History.isLastHash(currentHash) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onHashChange: no change');
+ History.busy(false);
+ return false;
+ }
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Store our location for use in detecting back/forward direction
+ History.saveHash(currentHash);
+
+ // Expand Hash
+ if ( currentHash && History.isTraditionalAnchor(currentHash) ) {
+ //History.debug('History.onHashChange: traditional anchor', currentHash);
+ // Traditional Anchor Hash
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ return false;
+ }
+
+ // Create State
+ currentState = History.extractState(History.getFullUrl(currentHash||History.getLocationHref()),true);
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(currentState) ) {
+ //History.debug('History.onHashChange: no change');
+ // There has been no change (just the page's hash has finally propagated)
+ History.busy(false);
+ return false;
+ }
+
+ // Create the state Hash
+ currentStateHash = History.getHashByState(currentState);
+
+ // Check if we are DiscardedState
+ discardObject = History.discardedState(currentState);
+ if ( discardObject ) {
+ // Ignore this state as it has been discarded and go back to the state before it
+ if ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {
+ // We are going backwards
+ //History.debug('History.onHashChange: go backwards');
+ History.back(false);
+ } else {
+ // We are going forwards
+ //History.debug('History.onHashChange: go forwards');
+ History.forward(false);
+ }
+ return false;
+ }
+
+ // Push the new HTML5 State
+ //History.debug('History.onHashChange: success hashchange');
+ History.pushState(currentState.data,currentState.title,encodeURI(currentState.url),false);
+
+ // End onHashChange closure
+ return true;
+ };
+ History.Adapter.bind(window,'hashchange',History.onHashChange);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Object
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ html4Hash = History.getHash(),
+ wasExpected = History.expectedStateId == newState.id;
+
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Check if we are the same State
+ if ( newStateHash === oldStateHash ) {
+ //History.debug('History.pushState: no change', newStateHash);
+ History.busy(false);
+ return false;
+ }
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ if(!wasExpected)
+ History.Adapter.trigger(window,'statechange');
+
+ // Update HTML4 Hash
+ if ( !History.isHashEqual(newStateHash, html4Hash) && !History.isHashEqual(newStateHash, History.getShortUrl(History.getLocationHref())) ) {
+ History.setHash(newStateHash,false);
+ }
+
+ History.busy(false);
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Objects
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ previousState = History.getStateByIndex(-2);
+
+ // Discard Old State
+ History.discardState(oldState,newState,previousState);
+
+ // If the url hasn't changed, just store and save the state
+ // and fire a statechange event to be consistent with the
+ // html 5 api
+ if ( newStateHash === oldStateHash ) {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ //History.debug('History.pushState: trigger popstate');
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+ }
+ else {
+ // Alias to PushState
+ History.pushState(newState.data,newState.title,newState.url,false);
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // History.emulated.pushState
+
+
+
+ // ====================================================================
+ // Initialise
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /**
+ * Ensure initial state is handled correctly
+ */
+ if ( History.getHash() && !History.emulated.hashChange ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+
+ } // History.emulated.pushState
+
+ }; // History.initHtml4
+
+ // Try to Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/zepto.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/zepto.history.js
new file mode 100644
index 00000000..02b19b77
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html4+html5/zepto.history.js
@@ -0,0 +1,3288 @@
+/*
+ json2.js
+ 2012-10-08
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ See http://www.JSON.org/js.html
+
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
+ This file creates a global JSON object containing two methods: stringify
+ and parse.
+
+ JSON.stringify(value, replacer, space)
+ value any JavaScript value, usually an object or array.
+
+ replacer an optional parameter that determines how object
+ values are stringified for objects. It can be a
+ function or an array of strings.
+
+ space an optional parameter that specifies the indentation
+ of nested structures. If it is omitted, the text will
+ be packed without extra whitespace. If it is a number,
+ it will specify the number of spaces to indent at each
+ level. If it is a string (such as '\t' or ' '),
+ it contains the characters used to indent at each level.
+
+ This method produces a JSON text from a JavaScript value.
+
+ When an object value is found, if the object contains a toJSON
+ method, its toJSON method will be called and the result will be
+ stringified. A toJSON method does not serialize: it returns the
+ value represented by the name/value pair that should be serialized,
+ or undefined if nothing should be serialized. The toJSON method
+ will be passed the key associated with the value, and this will be
+ bound to the value
+
+ For example, this would serialize Dates as ISO strings.
+
+ Date.prototype.toJSON = function (key) {
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ return this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z';
+ };
+
+ You can provide an optional replacer method. It will be passed the
+ key and value of each member, with this bound to the containing
+ object. The value that is returned from your method will be
+ serialized. If your method returns undefined, then the member will
+ be excluded from the serialization.
+
+ If the replacer parameter is an array of strings, then it will be
+ used to select the members to be serialized. It filters the results
+ such that only members with keys listed in the replacer array are
+ stringified.
+
+ Values that do not have JSON representations, such as undefined or
+ functions, will not be serialized. Such values in objects will be
+ dropped; in arrays they will be replaced with null. You can use
+ a replacer function to replace those with JSON values.
+ JSON.stringify(undefined) returns undefined.
+
+ The optional space parameter produces a stringification of the
+ value that is filled with line breaks and indentation to make it
+ easier to read.
+
+ If the space parameter is a non-empty string, then that string will
+ be used for indentation. If the space parameter is a number, then
+ the indentation will be that many spaces.
+
+ Example:
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
+ // text is '["e",{"pluribus":"unum"}]'
+
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+ text = JSON.stringify([new Date()], function (key, value) {
+ return this[key] instanceof Date ?
+ 'Date(' + this[key] + ')' : value;
+ });
+ // text is '["Date(---current time---)"]'
+
+
+ JSON.parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = JSON.parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
+ }
+ }
+ return value;
+ });
+
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+ var d;
+ if (typeof value === 'string' &&
+ value.slice(0, 5) === 'Date(' &&
+ value.slice(-1) === ')') {
+ d = new Date(value.slice(5, -1));
+ if (d) {
+ return d;
+ }
+ }
+ return value;
+ });
+
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+*/
+
+/*jslint evil: true, regexp: true */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
+ test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.
+
+if (typeof JSON !== 'object') {
+ JSON = {};
+}
+
+(function () {
+ 'use strict';
+
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ if (typeof Date.prototype.toJSON !== 'function') {
+
+ Date.prototype.toJSON = function (key) {
+
+ return isFinite(this.valueOf())
+ ? this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z'
+ : null;
+ };
+
+ String.prototype.toJSON =
+ Number.prototype.toJSON =
+ Boolean.prototype.toJSON = function (key) {
+ return this.valueOf();
+ };
+ }
+
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ gap,
+ indent,
+ meta = { // table of character substitutions
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ rep;
+
+
+ function quote(string) {
+
+// If the string contains no control characters, no quote characters, and no
+// backslash characters, then we can safely slap some quotes around it.
+// Otherwise we must also replace the offending characters with safe escape
+// sequences.
+
+ escapable.lastIndex = 0;
+ return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
+ var c = meta[a];
+ return typeof c === 'string'
+ ? c
+ : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"' : '"' + string + '"';
+ }
+
+
+ function str(key, holder) {
+
+// Produce a string from holder[key].
+
+ var i, // The loop counter.
+ k, // The member key.
+ v, // The member value.
+ length,
+ mind = gap,
+ partial,
+ value = holder[key];
+
+// If the value has a toJSON method, call it to obtain a replacement value.
+
+ if (value && typeof value === 'object' &&
+ typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+
+// If we were called with a replacer function, then call the replacer to
+// obtain a replacement value.
+
+ if (typeof rep === 'function') {
+ value = rep.call(holder, key, value);
+ }
+
+// What happens next depends on the value's type.
+
+ switch (typeof value) {
+ case 'string':
+ return quote(value);
+
+ case 'number':
+
+// JSON numbers must be finite. Encode non-finite numbers as null.
+
+ return isFinite(value) ? String(value) : 'null';
+
+ case 'boolean':
+ case 'null':
+
+// If the value is a boolean or null, convert it to a string. Note:
+// typeof null does not produce 'null'. The case is included here in
+// the remote chance that this gets fixed someday.
+
+ return String(value);
+
+// If the type is 'object', we might be dealing with an object or an array or
+// null.
+
+ case 'object':
+
+// Due to a specification blunder in ECMAScript, typeof null is 'object',
+// so watch out for that case.
+
+ if (!value) {
+ return 'null';
+ }
+
+// Make an array to hold the partial results of stringifying this object value.
+
+ gap += indent;
+ partial = [];
+
+// Is the value an array?
+
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+// The value is an array. Stringify every element. Use null as a placeholder
+// for non-JSON values.
+
+ length = value.length;
+ for (i = 0; i < length; i += 1) {
+ partial[i] = str(i, value) || 'null';
+ }
+
+// Join all of the elements together, separated with commas, and wrap them in
+// brackets.
+
+ v = partial.length === 0
+ ? '[]'
+ : gap
+ ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
+ : '[' + partial.join(',') + ']';
+ gap = mind;
+ return v;
+ }
+
+// If the replacer is an array, use it to select the members to be stringified.
+
+ if (rep && typeof rep === 'object') {
+ length = rep.length;
+ for (i = 0; i < length; i += 1) {
+ if (typeof rep[i] === 'string') {
+ k = rep[i];
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ } else {
+
+// Otherwise, iterate through all of the keys in the object.
+
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ }
+
+// Join all of the member texts together, separated with commas,
+// and wrap them in braces.
+
+ v = partial.length === 0
+ ? '{}'
+ : gap
+ ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
+ : '{' + partial.join(',') + '}';
+ gap = mind;
+ return v;
+ }
+ }
+
+// If the JSON object does not yet have a stringify method, give it one.
+
+ if (typeof JSON.stringify !== 'function') {
+ JSON.stringify = function (value, replacer, space) {
+
+// The stringify method takes a value and an optional replacer, and an optional
+// space parameter, and returns a JSON text. The replacer can be a function
+// that can replace values, or an array of strings that will select the keys.
+// A default replacer method can be provided. Use of the space parameter can
+// produce text that is more easily readable.
+
+ var i;
+ gap = '';
+ indent = '';
+
+// If the space parameter is a number, make an indent string containing that
+// many spaces.
+
+ if (typeof space === 'number') {
+ for (i = 0; i < space; i += 1) {
+ indent += ' ';
+ }
+
+// If the space parameter is a string, it will be used as the indent string.
+
+ } else if (typeof space === 'string') {
+ indent = space;
+ }
+
+// If there is a replacer, it must be a function or an array.
+// Otherwise, throw an error.
+
+ rep = replacer;
+ if (replacer && typeof replacer !== 'function' &&
+ (typeof replacer !== 'object' ||
+ typeof replacer.length !== 'number')) {
+ throw new Error('JSON.stringify');
+ }
+
+// Make a fake root object containing our value under the key of ''.
+// Return the result of stringifying the value.
+
+ return str('', {'': value});
+ };
+ }
+
+
+// If the JSON object does not yet have a parse method, give it one.
+
+ if (typeof JSON.parse !== 'function') {
+ JSON.parse = function (text, reviver) {
+
+// The parse method takes a text and an optional reviver function, and returns
+// a JavaScript value if the text is a valid JSON text.
+
+ var j;
+
+ function walk(holder, key) {
+
+// The walk method is used to recursively walk the resulting structure so
+// that modifications can be made.
+
+ var k, v, value = holder[key];
+ if (value && typeof value === 'object') {
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = walk(value, k);
+ if (v !== undefined) {
+ value[k] = v;
+ } else {
+ delete value[k];
+ }
+ }
+ }
+ }
+ return reviver.call(holder, key, value);
+ }
+
+
+// Parsing happens in four stages. In the first stage, we replace certain
+// Unicode characters with escape sequences. JavaScript handles many characters
+// incorrectly, either silently deleting them, or treating them as line endings.
+
+ text = String(text);
+ cx.lastIndex = 0;
+ if (cx.test(text)) {
+ text = text.replace(cx, function (a) {
+ return '\\u' +
+ ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ });
+ }
+
+// In the second stage, we run the text against regular expressions that look
+// for non-JSON patterns. We are especially concerned with '()' and 'new'
+// because they can cause invocation, and '=' because it can cause mutation.
+// But just to be safe, we want to reject all unexpected forms.
+
+// We split the second stage into 4 regexp operations in order to work around
+// crippling inefficiencies in IE's and Safari's regexp engines. First we
+// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
+// replace all simple value tokens with ']' characters. Third, we delete all
+// open brackets that follow a colon or comma or that begin the text. Finally,
+// we look to see that the remaining characters are only whitespace or ']' or
+// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
+
+ if (/^[\],:{}\s]*$/
+ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
+
+// In the third stage we use the eval function to compile the text into a
+// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
+// in JavaScript: it can begin a block or an object literal. We wrap the text
+// in parens to eliminate the ambiguity.
+
+ j = eval('(' + text + ')');
+
+// In the optional fourth stage, we recursively walk the new structure, passing
+// each name/value pair to a reviver function for possible transformation.
+
+ return typeof reviver === 'function'
+ ? walk({'': j}, '')
+ : j;
+ }
+
+// If the text is not JSON parseable, then a SyntaxError is thrown.
+
+ throw new SyntaxError('JSON.parse');
+ };
+ }
+}());/**
+ * History.js Zepto Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ Zepto = window.Zepto;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {function} callback
+ * @return {void}
+ */
+ bind: function(el,event,callback){
+ new Zepto(el).bind(event,callback);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @return {void}
+ */
+ trigger: function(el,event){
+ new Zepto(el).trigger(event);
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {string} key - key for the event data to extract
+ * @param {string} event - custom and standard events
+ * @return {mixed}
+ */
+ extractEventData: function(key,event){
+ // Zepto Native
+ var result = (event && event[key]) || undefined;
+
+ // Return
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {function} callback
+ * @return {void}
+ */
+ onDomLoad: function(callback) {
+ new Zepto(callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js HTML4 Support
+ * Depends on the HTML5 Support
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ document = window.document, // Make sure we are using the correct document
+ setTimeout = window.setTimeout||setTimeout,
+ clearTimeout = window.clearTimeout||clearTimeout,
+ setInterval = window.setInterval||setInterval,
+ History = window.History = window.History||{}; // Public History Object
+
+ // Check Existence
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ throw new Error('History.js HTML4 Support has already been loaded...');
+ }
+
+
+ // ========================================================================
+ // Initialise HTML4 Support
+
+ // Initialise HTML4 Support
+ History.initHtml4 = function(){
+ // Initialise
+ if ( typeof History.initHtml4.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initHtml4.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Properties
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = true;
+
+
+ // ====================================================================
+ // Hash Storage
+
+ /**
+ * History.savedHashes
+ * Store the hashes in an array
+ */
+ History.savedHashes = [];
+
+ /**
+ * History.isLastHash(newHash)
+ * Checks if the hash is the last hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.isLastHash = function(newHash){
+ // Prepare
+ var oldHash = History.getHashByIndex(),
+ isLast;
+
+ // Check
+ isLast = newHash === oldHash;
+
+ // Return isLast
+ return isLast;
+ };
+
+ /**
+ * History.isHashEqual(newHash, oldHash)
+ * Checks to see if two hashes are functionally equal
+ * @param {string} newHash
+ * @param {string} oldHash
+ * @return {boolean} true
+ */
+ History.isHashEqual = function(newHash, oldHash){
+ newHash = encodeURIComponent(newHash).replace(/%25/g, "%");
+ oldHash = encodeURIComponent(oldHash).replace(/%25/g, "%");
+ return newHash === oldHash;
+ };
+
+ /**
+ * History.saveHash(newHash)
+ * Push a Hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.saveHash = function(newHash){
+ // Check Hash
+ if ( History.isLastHash(newHash) ) {
+ return false;
+ }
+
+ // Push the Hash
+ History.savedHashes.push(newHash);
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getHashByIndex()
+ * Gets a hash by the index
+ * @param {integer} index
+ * @return {string}
+ */
+ History.getHashByIndex = function(index){
+ // Prepare
+ var hash = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ hash = History.savedHashes[History.savedHashes.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ hash = History.savedHashes[History.savedHashes.length+index];
+ }
+ else {
+ // Get from the beginning
+ hash = History.savedHashes[index];
+ }
+
+ // Return hash
+ return hash;
+ };
+
+
+ // ====================================================================
+ // Discarded States
+
+ /**
+ * History.discardedHashes
+ * A hashed array of discarded hashes
+ */
+ History.discardedHashes = {};
+
+ /**
+ * History.discardedStates
+ * A hashed array of discarded states
+ */
+ History.discardedStates = {};
+
+ /**
+ * History.discardState(State)
+ * Discards the state by ignoring it through History
+ * @param {object} State
+ * @return {true}
+ */
+ History.discardState = function(discardedState,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Prepare
+ var discardedStateHash = History.getHashByState(discardedState),
+ discardObject;
+
+ // Create Discard Object
+ discardObject = {
+ 'discardedState': discardedState,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to DiscardedStates
+ History.discardedStates[discardedStateHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardHash(hash)
+ * Discards the hash by ignoring it through History
+ * @param {string} hash
+ * @return {true}
+ */
+ History.discardHash = function(discardedHash,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Create Discard Object
+ var discardObject = {
+ 'discardedHash': discardedHash,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to discardedHash
+ History.discardedHashes[discardedHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardedState(State)
+ * Checks to see if the state is discarded
+ * @param {object} State
+ * @return {bool}
+ */
+ History.discardedState = function(State){
+ // Prepare
+ var StateHash = History.getHashByState(State),
+ discarded;
+
+ // Check
+ discarded = History.discardedStates[StateHash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.discardedHash(hash)
+ * Checks to see if the state is discarded
+ * @param {string} State
+ * @return {bool}
+ */
+ History.discardedHash = function(hash){
+ // Check
+ var discarded = History.discardedHashes[hash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.recycleState(State)
+ * Allows a discarded state to be used again
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.recycleState = function(State){
+ //History.debug('History.recycleState', arguments);
+ // Prepare
+ var StateHash = History.getHashByState(State);
+
+ // Remove from DiscardedStates
+ if ( History.discardedState(State) ) {
+ delete History.discardedStates[StateHash];
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ====================================================================
+ // HTML4 HashChange Support
+
+ if ( History.emulated.hashChange ) {
+ /*
+ * We must emulate the HTML4 HashChange Support by manually checking for hash changes
+ */
+
+ /**
+ * History.hashChangeInit()
+ * Init the HashChange Emulation
+ */
+ History.hashChangeInit = function(){
+ // Define our Checker Function
+ History.checkerFunction = null;
+
+ // Define some variables that will help in our checker function
+ var lastDocumentHash = '',
+ iframeId, iframe,
+ lastIframeHash, checkerRunning,
+ startedWithHash = Boolean(History.getHash());
+
+ // Handle depending on the browser
+ if ( History.isInternetExplorer() ) {
+ // IE6 and IE7
+ // We need to use an iframe to emulate the back and forward buttons
+
+ // Create iFrame
+ iframeId = 'historyjs-iframe';
+ iframe = document.createElement('iframe');
+
+ // Adjust iFarme
+ // IE 6 requires iframe to have a src on HTTPS pages, otherwise it will throw a
+ // "This page contains both secure and nonsecure items" warning.
+ iframe.setAttribute('id', iframeId);
+ iframe.setAttribute('src', '#');
+ iframe.style.display = 'none';
+
+ // Append iFrame
+ document.body.appendChild(iframe);
+
+ // Create initial history entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Define some variables that will help in our checker function
+ lastIframeHash = '';
+ checkerRunning = false;
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Check Running
+ if ( checkerRunning ) {
+ return false;
+ }
+
+ // Update Running
+ checkerRunning = true;
+
+ // Fetch
+ var
+ documentHash = History.getHash(),
+ iframeHash = History.getHash(iframe.contentWindow.document);
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Create a history entry in the iframe
+ if ( iframeHash !== documentHash ) {
+ //History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);
+
+ // Equalise
+ lastIframeHash = iframeHash = documentHash;
+
+ // Create History Entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Update the iframe's hash
+ iframe.contentWindow.document.location.hash = History.escapeHash(documentHash);
+ }
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // The iFrame Hash has changed (back button caused)
+ else if ( iframeHash !== lastIframeHash ) {
+ //History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);
+
+ // Equalise
+ lastIframeHash = iframeHash;
+
+ // If there is no iframe hash that means we're at the original
+ // iframe state.
+ // And if there was a hash on the original request, the original
+ // iframe state was replaced instantly, so skip this state and take
+ // the user back to where they came from.
+ if (startedWithHash && iframeHash === '') {
+ History.back();
+ }
+ else {
+ // Update the Hash
+ History.setHash(iframeHash,false);
+ }
+ }
+
+ // Reset Running
+ checkerRunning = false;
+
+ // Return true
+ return true;
+ };
+ }
+ else {
+ // We are not IE
+ // Firefox 1 or 2, Opera
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Prepare
+ var documentHash = History.getHash()||'';
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // Return true
+ return true;
+ };
+ }
+
+ // Apply the checker function
+ History.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));
+
+ // Done
+ return true;
+ }; // History.hashChangeInit
+
+ // Bind hashChangeInit
+ History.Adapter.onDomLoad(History.hashChangeInit);
+
+ } // History.emulated.hashChange
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * We must emulate the HTML5 State Management by using HTML4 HashChange
+ */
+
+ /**
+ * History.onHashChange(event)
+ * Trigger HTML5's window.onpopstate via HTML4 HashChange Support
+ */
+ History.onHashChange = function(event){
+ //History.debug('History.onHashChange', arguments);
+
+ // Prepare
+ var currentUrl = ((event && event.newURL) || History.getLocationHref()),
+ currentHash = History.getHashByUrl(currentUrl),
+ currentState = null,
+ currentStateHash = null,
+ currentStateHashExits = null,
+ discardObject;
+
+ // Check if we are the same state
+ if ( History.isLastHash(currentHash) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onHashChange: no change');
+ History.busy(false);
+ return false;
+ }
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Store our location for use in detecting back/forward direction
+ History.saveHash(currentHash);
+
+ // Expand Hash
+ if ( currentHash && History.isTraditionalAnchor(currentHash) ) {
+ //History.debug('History.onHashChange: traditional anchor', currentHash);
+ // Traditional Anchor Hash
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ return false;
+ }
+
+ // Create State
+ currentState = History.extractState(History.getFullUrl(currentHash||History.getLocationHref()),true);
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(currentState) ) {
+ //History.debug('History.onHashChange: no change');
+ // There has been no change (just the page's hash has finally propagated)
+ History.busy(false);
+ return false;
+ }
+
+ // Create the state Hash
+ currentStateHash = History.getHashByState(currentState);
+
+ // Check if we are DiscardedState
+ discardObject = History.discardedState(currentState);
+ if ( discardObject ) {
+ // Ignore this state as it has been discarded and go back to the state before it
+ if ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {
+ // We are going backwards
+ //History.debug('History.onHashChange: go backwards');
+ History.back(false);
+ } else {
+ // We are going forwards
+ //History.debug('History.onHashChange: go forwards');
+ History.forward(false);
+ }
+ return false;
+ }
+
+ // Push the new HTML5 State
+ //History.debug('History.onHashChange: success hashchange');
+ History.pushState(currentState.data,currentState.title,encodeURI(currentState.url),false);
+
+ // End onHashChange closure
+ return true;
+ };
+ History.Adapter.bind(window,'hashchange',History.onHashChange);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Object
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ html4Hash = History.getHash(),
+ wasExpected = History.expectedStateId == newState.id;
+
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Check if we are the same State
+ if ( newStateHash === oldStateHash ) {
+ //History.debug('History.pushState: no change', newStateHash);
+ History.busy(false);
+ return false;
+ }
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ if(!wasExpected)
+ History.Adapter.trigger(window,'statechange');
+
+ // Update HTML4 Hash
+ if ( !History.isHashEqual(newStateHash, html4Hash) && !History.isHashEqual(newStateHash, History.getShortUrl(History.getLocationHref())) ) {
+ History.setHash(newStateHash,false);
+ }
+
+ History.busy(false);
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Objects
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ previousState = History.getStateByIndex(-2);
+
+ // Discard Old State
+ History.discardState(oldState,newState,previousState);
+
+ // If the url hasn't changed, just store and save the state
+ // and fire a statechange event to be consistent with the
+ // html 5 api
+ if ( newStateHash === oldStateHash ) {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ //History.debug('History.pushState: trigger popstate');
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+ }
+ else {
+ // Alias to PushState
+ History.pushState(newState.data,newState.title,newState.url,false);
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // History.emulated.pushState
+
+
+
+ // ====================================================================
+ // Initialise
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /**
+ * Ensure initial state is handled correctly
+ */
+ if ( History.getHash() && !History.emulated.hashChange ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+
+ } // History.emulated.pushState
+
+ }; // History.initHtml4
+
+ // Try to Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/dojo.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/dojo.history.js
new file mode 100644
index 00000000..1adedd24
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/dojo.history.js
@@ -0,0 +1,2165 @@
+/**
+ * History.js Dojo Adapter
+ *
+ * Essentially the same as the native adapter but uses dojo/ready for the dom load callback.
+ *
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var History = window.History = window.History||{},
+ require = window.require;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.handlers[uid][eventName] = Array
+ */
+ handlers: {},
+
+ /**
+ * History.Adapter._uid
+ * The current element unique identifier
+ */
+ _uid: 1,
+
+ /**
+ * History.Adapter.uid(element)
+ * @param {Element} element
+ * @return {String} uid
+ */
+ uid: function(element){
+ return element._uid || (element._uid = History.Adapter._uid++);
+ },
+
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element} element
+ * @param {String} eventName - custom and standard events
+ * @param {Function} callback
+ * @return
+ */
+ bind: function(element,eventName,callback){
+ // Prepare
+ var uid = History.Adapter.uid(element);
+
+ // Apply Listener
+ History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
+ History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
+ History.Adapter.handlers[uid][eventName].push(callback);
+
+ // Bind Global Listener
+ element['on'+eventName] = (function(element,eventName){
+ return function(event){
+ History.Adapter.trigger(element,eventName,event);
+ };
+ })(element,eventName);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element} element
+ * @param {String} eventName - custom and standard events
+ * @param {Object} event - a object of event data
+ * @return
+ */
+ trigger: function(element,eventName,event){
+ // Prepare
+ event = event || {};
+ var uid = History.Adapter.uid(element),
+ i,n;
+
+ // Apply Listener
+ History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
+ History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
+
+ // Fire Listeners
+ for ( i=0,n=History.Adapter.handlers[uid][eventName].length; i
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/extjs.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/extjs.history.js
new file mode 100644
index 00000000..58aba58b
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/extjs.history.js
@@ -0,0 +1,2135 @@
+/**
+ * History.js ExtJS Adapter
+ * @author Sean Adkinson
+ * @copyright 2012 Sean Adkinson
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ Ext = window.Ext;
+
+ window.JSON = {
+ stringify: Ext.JSON.encode,
+ parse: Ext.JSON.decode
+ };
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ observables: {},
+
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {function} callback
+ * @param {Object} scope
+ * @return {void}
+ */
+ bind: function(element,eventName,callback,scope){
+ Ext.EventManager.addListener(element, eventName, callback, scope);
+
+ //bind an observable to the element that will let us "trigger" events on it
+ var id = Ext.id(element, 'history-'), observable = this.observables[id];
+ if (!observable) {
+ observable = Ext.create('Ext.util.Observable');
+ this.observables[id] = observable;
+ }
+ observable.on(eventName, callback, scope);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return {void}
+ */
+ trigger: function(element,eventName,extra){
+ var id = Ext.id(element, 'history-'), observable = this.observables[id];
+ if (observable) {
+ observable.fireEvent(eventName, extra);
+ }
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {string} key - key for the event data to extract
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return {mixed}
+ */
+ extractEventData: function(key,event,extra){
+ var result = (event && event.browserEvent && event.browserEvent[key]) || (extra && extra[key]) || undefined;
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {function} callback
+ * @return {void}
+ */
+ onDomLoad: function(callback) {
+ Ext.onReady(callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/jquery.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/jquery.history.js
new file mode 100644
index 00000000..c53a5b4f
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/jquery.history.js
@@ -0,0 +1,2121 @@
+/**
+ * History.js jQuery Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ jQuery = window.jQuery;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {function} callback
+ * @return {void}
+ */
+ bind: function(el,event,callback){
+ jQuery(el).bind(event,callback);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return {void}
+ */
+ trigger: function(el,event,extra){
+ jQuery(el).trigger(event,extra);
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {string} key - key for the event data to extract
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return {mixed}
+ */
+ extractEventData: function(key,event,extra){
+ // jQuery Native then jQuery Custom
+ var result = (event && event.originalEvent && event.originalEvent[key]) || (extra && extra[key]) || undefined;
+
+ // Return
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {function} callback
+ * @return {void}
+ */
+ onDomLoad: function(callback) {
+ jQuery(callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+
+/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/mootools.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/mootools.history.js
new file mode 100644
index 00000000..b5eca0bb
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/mootools.history.js
@@ -0,0 +1,2128 @@
+/**
+ * History.js MooTools Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ MooTools = window.MooTools,
+ Element = window.Element;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Make MooTools aware of History.js Events
+ Object.append(Element.NativeEvents,{
+ 'popstate':2,
+ 'hashchange':2
+ });
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {function} callback
+ * @return {void}
+ */
+ bind: function(el,event,callback){
+ var El = typeof el === 'string' ? document.id(el) : el;
+ El.addEvent(event,callback);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return void
+ */
+ trigger: function(el,event,extra){
+ var El = typeof el === 'string' ? document.id(el) : el;
+ El.fireEvent(event,extra);
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {string} key - key for the event data to extract
+ * @param {string} event - custom and standard events
+ * @return {mixed}
+ */
+ extractEventData: function(key,event){
+ // MooTools Native then MooTools Custom
+ var result = (event && event.event && event.event[key]) || (event && event[key]) || undefined;
+
+ // Return
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {function} callback
+ * @return {void}
+ */
+ onDomLoad: function(callback) {
+ window.addEvent('domready',callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/native.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/native.history.js
new file mode 100644
index 00000000..f87e3f41
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/native.history.js
@@ -0,0 +1,2165 @@
+/**
+ * History.js Native Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var History = window.History = window.History||{};
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.handlers[uid][eventName] = Array
+ */
+ handlers: {},
+
+ /**
+ * History.Adapter._uid
+ * The current element unique identifier
+ */
+ _uid: 1,
+
+ /**
+ * History.Adapter.uid(element)
+ * @param {Element} element
+ * @return {String} uid
+ */
+ uid: function(element){
+ return element._uid || (element._uid = History.Adapter._uid++);
+ },
+
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element} element
+ * @param {String} eventName - custom and standard events
+ * @param {Function} callback
+ * @return
+ */
+ bind: function(element,eventName,callback){
+ // Prepare
+ var uid = History.Adapter.uid(element);
+
+ // Apply Listener
+ History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
+ History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
+ History.Adapter.handlers[uid][eventName].push(callback);
+
+ // Bind Global Listener
+ element['on'+eventName] = (function(element,eventName){
+ return function(event){
+ History.Adapter.trigger(element,eventName,event);
+ };
+ })(element,eventName);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element} element
+ * @param {String} eventName - custom and standard events
+ * @param {Object} event - a object of event data
+ * @return
+ */
+ trigger: function(element,eventName,event){
+ // Prepare
+ event = event || {};
+ var uid = History.Adapter.uid(element),
+ i,n;
+
+ // Apply Listener
+ History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
+ History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
+
+ // Fire Listeners
+ for ( i=0,n=History.Adapter.handlers[uid][eventName].length; i
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/right.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/right.history.js
new file mode 100644
index 00000000..9a81c833
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/right.history.js
@@ -0,0 +1,2122 @@
+/**
+ * History.js RightJS Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ document = window.document,
+ RightJS = window.RightJS,
+ $ = RightJS.$;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|Selector} el
+ * @param {String} event - custom and standard events
+ * @param {Function} callback
+ * @return
+ */
+ bind: function(el,event,callback){
+ $(el).on(event,callback);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|Selector} el
+ * @param {String} event - custom and standard events
+ * @param {Object} extraEventData - a object of extra event data
+ * @return
+ */
+ trigger: function(el,event,extraEventData){
+ $(el).fire(event,extraEventData);
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {String} key - key for the event data to extract
+ * @param {String} event - custom and standard events
+ * @return {mixed}
+ */
+ extractEventData: function(key,event){
+ // Right.js Native
+ // Right.js Custom
+ var result = (event && event._ && event._[key]) || undefined;
+
+ // Return
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {Function} callback
+ * @return
+ */
+ onDomLoad: function(callback) {
+ $(document).onReady(callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/zepto.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/zepto.history.js
new file mode 100644
index 00000000..f35ea195
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled-uncompressed/html5/zepto.history.js
@@ -0,0 +1,2118 @@
+/**
+ * History.js Zepto Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ Zepto = window.Zepto;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {function} callback
+ * @return {void}
+ */
+ bind: function(el,event,callback){
+ new Zepto(el).bind(event,callback);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @return {void}
+ */
+ trigger: function(el,event){
+ new Zepto(el).trigger(event);
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {string} key - key for the event data to extract
+ * @param {string} event - custom and standard events
+ * @return {mixed}
+ */
+ extractEventData: function(key,event){
+ // Zepto Native
+ var result = (event && event[key]) || undefined;
+
+ // Return
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {function} callback
+ * @return {void}
+ */
+ onDomLoad: function(callback) {
+ new Zepto(callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/dojo.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/dojo.history.js
new file mode 100644
index 00000000..3ac2c663
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/dojo.history.js
@@ -0,0 +1 @@
+typeof JSON!="object"&&(JSON={}),function(){"use strict";function f(e){return e<10?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return typeof t=="string"?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,r,i,s,o=gap,u,a=t[e];a&&typeof a=="object"&&typeof a.toJSON=="function"&&(a=a.toJSON(e)),typeof rep=="function"&&(a=rep.call(t,e,a));switch(typeof a){case"string":return quote(a);case"number":return isFinite(a)?String(a):"null";case"boolean":case"null":return String(a);case"object":if(!a)return"null";gap+=indent,u=[];if(Object.prototype.toString.apply(a)==="[object Array]"){s=a.length;for(n=0;n ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/extjs.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/extjs.history.js
new file mode 100644
index 00000000..c546f51d
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/extjs.history.js
@@ -0,0 +1 @@
+typeof JSON!="object"&&(JSON={}),function(){"use strict";function f(e){return e<10?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return typeof t=="string"?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,r,i,s,o=gap,u,a=t[e];a&&typeof a=="object"&&typeof a.toJSON=="function"&&(a=a.toJSON(e)),typeof rep=="function"&&(a=rep.call(t,e,a));switch(typeof a){case"string":return quote(a);case"number":return isFinite(a)?String(a):"null";case"boolean":case"null":return String(a);case"object":if(!a)return"null";gap+=indent,u=[];if(Object.prototype.toString.apply(a)==="[object Array]"){s=a.length;for(n=0;n ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/jquery.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/jquery.history.js
new file mode 100644
index 00000000..20f8c9e0
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/jquery.history.js
@@ -0,0 +1 @@
+typeof JSON!="object"&&(JSON={}),function(){"use strict";function f(e){return e<10?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return typeof t=="string"?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,r,i,s,o=gap,u,a=t[e];a&&typeof a=="object"&&typeof a.toJSON=="function"&&(a=a.toJSON(e)),typeof rep=="function"&&(a=rep.call(t,e,a));switch(typeof a){case"string":return quote(a);case"number":return isFinite(a)?String(a):"null";case"boolean":case"null":return String(a);case"object":if(!a)return"null";gap+=indent,u=[];if(Object.prototype.toString.apply(a)==="[object Array]"){s=a.length;for(n=0;n ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/mootools.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/mootools.history.js
new file mode 100644
index 00000000..2e699f2b
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/mootools.history.js
@@ -0,0 +1 @@
+typeof JSON!="object"&&(JSON={}),function(){"use strict";function f(e){return e<10?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return typeof t=="string"?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,r,i,s,o=gap,u,a=t[e];a&&typeof a=="object"&&typeof a.toJSON=="function"&&(a=a.toJSON(e)),typeof rep=="function"&&(a=rep.call(t,e,a));switch(typeof a){case"string":return quote(a);case"number":return isFinite(a)?String(a):"null";case"boolean":case"null":return String(a);case"object":if(!a)return"null";gap+=indent,u=[];if(Object.prototype.toString.apply(a)==="[object Array]"){s=a.length;for(n=0;n ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/native.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/native.history.js
new file mode 100644
index 00000000..649fc35c
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/native.history.js
@@ -0,0 +1 @@
+typeof JSON!="object"&&(JSON={}),function(){"use strict";function f(e){return e<10?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return typeof t=="string"?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,r,i,s,o=gap,u,a=t[e];a&&typeof a=="object"&&typeof a.toJSON=="function"&&(a=a.toJSON(e)),typeof rep=="function"&&(a=rep.call(t,e,a));switch(typeof a){case"string":return quote(a);case"number":return isFinite(a)?String(a):"null";case"boolean":case"null":return String(a);case"object":if(!a)return"null";gap+=indent,u=[];if(Object.prototype.toString.apply(a)==="[object Array]"){s=a.length;for(n=0;n ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/right.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/right.history.js
new file mode 100644
index 00000000..64087af2
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/right.history.js
@@ -0,0 +1 @@
+typeof JSON!="object"&&(JSON={}),function(){"use strict";function f(e){return e<10?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return typeof t=="string"?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,r,i,s,o=gap,u,a=t[e];a&&typeof a=="object"&&typeof a.toJSON=="function"&&(a=a.toJSON(e)),typeof rep=="function"&&(a=rep.call(t,e,a));switch(typeof a){case"string":return quote(a);case"number":return isFinite(a)?String(a):"null";case"boolean":case"null":return String(a);case"object":if(!a)return"null";gap+=indent,u=[];if(Object.prototype.toString.apply(a)==="[object Array]"){s=a.length;for(n=0;n ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/zepto.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/zepto.history.js
new file mode 100644
index 00000000..ffc67e40
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html4+html5/zepto.history.js
@@ -0,0 +1 @@
+typeof JSON!="object"&&(JSON={}),function(){"use strict";function f(e){return e<10?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return typeof t=="string"?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,r,i,s,o=gap,u,a=t[e];a&&typeof a=="object"&&typeof a.toJSON=="function"&&(a=a.toJSON(e)),typeof rep=="function"&&(a=rep.call(t,e,a));switch(typeof a){case"string":return quote(a);case"number":return isFinite(a)?String(a):"null";case"boolean":case"null":return String(a);case"object":if(!a)return"null";gap+=indent,u=[];if(Object.prototype.toString.apply(a)==="[object Array]"){s=a.length;for(n=0;n ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/dojo.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/dojo.history.js
new file mode 100644
index 00000000..c879d4f1
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/dojo.history.js
@@ -0,0 +1 @@
+(function(e,t){"use strict";var n=e.History=e.History||{},r=e.require;if(typeof n.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");n.Adapter={handlers:{},_uid:1,uid:function(e){return e._uid||(e._uid=n.Adapter._uid++)},bind:function(e,t,r){var i=n.Adapter.uid(e);n.Adapter.handlers[i]=n.Adapter.handlers[i]||{},n.Adapter.handlers[i][t]=n.Adapter.handlers[i][t]||[],n.Adapter.handlers[i][t].push(r),e["on"+t]=function(e,t){return function(r){n.Adapter.trigger(e,t,r)}}(e,t)},trigger:function(e,t,r){r=r||{};var i=n.Adapter.uid(e),s,o;n.Adapter.handlers[i]=n.Adapter.handlers[i]||{},n.Adapter.handlers[i][t]=n.Adapter.handlers[i][t]||[];for(s=0,o=n.Adapter.handlers[i][t].length;s ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/extjs.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/extjs.history.js
new file mode 100644
index 00000000..a9ee3ffb
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/extjs.history.js
@@ -0,0 +1 @@
+(function(e,t){"use strict";var n=e.History=e.History||{},r=e.Ext;e.JSON={stringify:r.JSON.encode,parse:r.JSON.decode};if(typeof n.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");n.Adapter={observables:{},bind:function(e,t,n,i){r.EventManager.addListener(e,t,n,i);var s=r.id(e,"history-"),o=this.observables[s];o||(o=r.create("Ext.util.Observable"),this.observables[s]=o),o.on(t,n,i)},trigger:function(e,t,n){var i=r.id(e,"history-"),s=this.observables[i];s&&s.fireEvent(t,n)},extractEventData:function(e,n,r){var i=n&&n.browserEvent&&n.browserEvent[e]||r&&r[e]||t;return i},onDomLoad:function(e){r.onReady(e)}},typeof n.init!="undefined"&&n.init()})(window),function(e,t){"use strict";var n=e.console||t,r=e.document,i=e.navigator,s=e.sessionStorage||!1,o=e.setTimeout,u=e.clearTimeout,a=e.setInterval,f=e.clearInterval,l=e.JSON,c=e.alert,h=e.History=e.History||{},p=e.history;try{s.setItem("TEST","1"),s.removeItem("TEST")}catch(d){s=!1}l.stringify=l.stringify||l.encode,l.parse=l.parse||l.decode;if(typeof h.init!="undefined")throw new Error("History.js Core has already been loaded...");h.init=function(e){return typeof h.Adapter=="undefined"?!1:(typeof h.initCore!="undefined"&&h.initCore(),typeof h.initHtml4!="undefined"&&h.initHtml4(),!0)},h.initCore=function(d){if(typeof h.initCore.initialized!="undefined")return!1;h.initCore.initialized=!0,h.options=h.options||{},h.options.hashChangeInterval=h.options.hashChangeInterval||100,h.options.safariPollInterval=h.options.safariPollInterval||500,h.options.doubleCheckInterval=h.options.doubleCheckInterval||500,h.options.disableSuid=h.options.disableSuid||!1,h.options.storeInterval=h.options.storeInterval||1e3,h.options.busyDelay=h.options.busyDelay||250,h.options.debug=h.options.debug||!1,h.options.initialTitle=h.options.initialTitle||r.title,h.options.html4Mode=h.options.html4Mode||!1,h.options.delayInit=h.options.delayInit||!1,h.intervalList=[],h.clearAllIntervals=function(){var e,t=h.intervalList;if(typeof t!="undefined"&&t!==null){for(e=0;e ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/jquery.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/jquery.history.js
new file mode 100644
index 00000000..caeb7aa4
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/jquery.history.js
@@ -0,0 +1 @@
+(function(e,t){"use strict";var n=e.History=e.History||{},r=e.jQuery;if(typeof n.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");n.Adapter={bind:function(e,t,n){r(e).bind(t,n)},trigger:function(e,t,n){r(e).trigger(t,n)},extractEventData:function(e,n,r){var i=n&&n.originalEvent&&n.originalEvent[e]||r&&r[e]||t;return i},onDomLoad:function(e){r(e)}},typeof n.init!="undefined"&&n.init()})(window),function(e,t){"use strict";var n=e.console||t,r=e.document,i=e.navigator,s=e.sessionStorage||!1,o=e.setTimeout,u=e.clearTimeout,a=e.setInterval,f=e.clearInterval,l=e.JSON,c=e.alert,h=e.History=e.History||{},p=e.history;try{s.setItem("TEST","1"),s.removeItem("TEST")}catch(d){s=!1}l.stringify=l.stringify||l.encode,l.parse=l.parse||l.decode;if(typeof h.init!="undefined")throw new Error("History.js Core has already been loaded...");h.init=function(e){return typeof h.Adapter=="undefined"?!1:(typeof h.initCore!="undefined"&&h.initCore(),typeof h.initHtml4!="undefined"&&h.initHtml4(),!0)},h.initCore=function(d){if(typeof h.initCore.initialized!="undefined")return!1;h.initCore.initialized=!0,h.options=h.options||{},h.options.hashChangeInterval=h.options.hashChangeInterval||100,h.options.safariPollInterval=h.options.safariPollInterval||500,h.options.doubleCheckInterval=h.options.doubleCheckInterval||500,h.options.disableSuid=h.options.disableSuid||!1,h.options.storeInterval=h.options.storeInterval||1e3,h.options.busyDelay=h.options.busyDelay||250,h.options.debug=h.options.debug||!1,h.options.initialTitle=h.options.initialTitle||r.title,h.options.html4Mode=h.options.html4Mode||!1,h.options.delayInit=h.options.delayInit||!1,h.intervalList=[],h.clearAllIntervals=function(){var e,t=h.intervalList;if(typeof t!="undefined"&&t!==null){for(e=0;e ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/mootools.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/mootools.history.js
new file mode 100644
index 00000000..5082b839
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/mootools.history.js
@@ -0,0 +1 @@
+(function(e,t){"use strict";var n=e.History=e.History||{},r=e.MooTools,i=e.Element;if(typeof n.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");Object.append(i.NativeEvents,{popstate:2,hashchange:2}),n.Adapter={bind:function(e,t,n){var r=typeof e=="string"?document.id(e):e;r.addEvent(t,n)},trigger:function(e,t,n){var r=typeof e=="string"?document.id(e):e;r.fireEvent(t,n)},extractEventData:function(e,n){var r=n&&n.event&&n.event[e]||n&&n[e]||t;return r},onDomLoad:function(t){e.addEvent("domready",t)}},typeof n.init!="undefined"&&n.init()})(window),function(e,t){"use strict";var n=e.console||t,r=e.document,i=e.navigator,s=e.sessionStorage||!1,o=e.setTimeout,u=e.clearTimeout,a=e.setInterval,f=e.clearInterval,l=e.JSON,c=e.alert,h=e.History=e.History||{},p=e.history;try{s.setItem("TEST","1"),s.removeItem("TEST")}catch(d){s=!1}l.stringify=l.stringify||l.encode,l.parse=l.parse||l.decode;if(typeof h.init!="undefined")throw new Error("History.js Core has already been loaded...");h.init=function(e){return typeof h.Adapter=="undefined"?!1:(typeof h.initCore!="undefined"&&h.initCore(),typeof h.initHtml4!="undefined"&&h.initHtml4(),!0)},h.initCore=function(d){if(typeof h.initCore.initialized!="undefined")return!1;h.initCore.initialized=!0,h.options=h.options||{},h.options.hashChangeInterval=h.options.hashChangeInterval||100,h.options.safariPollInterval=h.options.safariPollInterval||500,h.options.doubleCheckInterval=h.options.doubleCheckInterval||500,h.options.disableSuid=h.options.disableSuid||!1,h.options.storeInterval=h.options.storeInterval||1e3,h.options.busyDelay=h.options.busyDelay||250,h.options.debug=h.options.debug||!1,h.options.initialTitle=h.options.initialTitle||r.title,h.options.html4Mode=h.options.html4Mode||!1,h.options.delayInit=h.options.delayInit||!1,h.intervalList=[],h.clearAllIntervals=function(){var e,t=h.intervalList;if(typeof t!="undefined"&&t!==null){for(e=0;e ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/native.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/native.history.js
new file mode 100644
index 00000000..3da05c27
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/native.history.js
@@ -0,0 +1 @@
+(function(e,t){"use strict";var n=e.History=e.History||{};if(typeof n.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");n.Adapter={handlers:{},_uid:1,uid:function(e){return e._uid||(e._uid=n.Adapter._uid++)},bind:function(e,t,r){var i=n.Adapter.uid(e);n.Adapter.handlers[i]=n.Adapter.handlers[i]||{},n.Adapter.handlers[i][t]=n.Adapter.handlers[i][t]||[],n.Adapter.handlers[i][t].push(r),e["on"+t]=function(e,t){return function(r){n.Adapter.trigger(e,t,r)}}(e,t)},trigger:function(e,t,r){r=r||{};var i=n.Adapter.uid(e),s,o;n.Adapter.handlers[i]=n.Adapter.handlers[i]||{},n.Adapter.handlers[i][t]=n.Adapter.handlers[i][t]||[];for(s=0,o=n.Adapter.handlers[i][t].length;s ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/right.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/right.history.js
new file mode 100644
index 00000000..80cf820f
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/right.history.js
@@ -0,0 +1 @@
+(function(e,t){"use strict";var n=e.History=e.History||{},r=e.document,i=e.RightJS,s=i.$;if(typeof n.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");n.Adapter={bind:function(e,t,n){s(e).on(t,n)},trigger:function(e,t,n){s(e).fire(t,n)},extractEventData:function(e,n){var r=n&&n._&&n._[e]||t;return r},onDomLoad:function(e){s(r).onReady(e)}},typeof n.init!="undefined"&&n.init()})(window),function(e,t){"use strict";var n=e.console||t,r=e.document,i=e.navigator,s=e.sessionStorage||!1,o=e.setTimeout,u=e.clearTimeout,a=e.setInterval,f=e.clearInterval,l=e.JSON,c=e.alert,h=e.History=e.History||{},p=e.history;try{s.setItem("TEST","1"),s.removeItem("TEST")}catch(d){s=!1}l.stringify=l.stringify||l.encode,l.parse=l.parse||l.decode;if(typeof h.init!="undefined")throw new Error("History.js Core has already been loaded...");h.init=function(e){return typeof h.Adapter=="undefined"?!1:(typeof h.initCore!="undefined"&&h.initCore(),typeof h.initHtml4!="undefined"&&h.initHtml4(),!0)},h.initCore=function(d){if(typeof h.initCore.initialized!="undefined")return!1;h.initCore.initialized=!0,h.options=h.options||{},h.options.hashChangeInterval=h.options.hashChangeInterval||100,h.options.safariPollInterval=h.options.safariPollInterval||500,h.options.doubleCheckInterval=h.options.doubleCheckInterval||500,h.options.disableSuid=h.options.disableSuid||!1,h.options.storeInterval=h.options.storeInterval||1e3,h.options.busyDelay=h.options.busyDelay||250,h.options.debug=h.options.debug||!1,h.options.initialTitle=h.options.initialTitle||r.title,h.options.html4Mode=h.options.html4Mode||!1,h.options.delayInit=h.options.delayInit||!1,h.intervalList=[],h.clearAllIntervals=function(){var e,t=h.intervalList;if(typeof t!="undefined"&&t!==null){for(e=0;e ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/zepto.history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/zepto.history.js
new file mode 100644
index 00000000..07b366d8
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/bundled/html5/zepto.history.js
@@ -0,0 +1 @@
+(function(e,t){"use strict";var n=e.History=e.History||{},r=e.Zepto;if(typeof n.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");n.Adapter={bind:function(e,t,n){(new r(e)).bind(t,n)},trigger:function(e,t){(new r(e)).trigger(t)},extractEventData:function(e,n){var r=n&&n[e]||t;return r},onDomLoad:function(e){new r(e)}},typeof n.init!="undefined"&&n.init()})(window),function(e,t){"use strict";var n=e.console||t,r=e.document,i=e.navigator,s=e.sessionStorage||!1,o=e.setTimeout,u=e.clearTimeout,a=e.setInterval,f=e.clearInterval,l=e.JSON,c=e.alert,h=e.History=e.History||{},p=e.history;try{s.setItem("TEST","1"),s.removeItem("TEST")}catch(d){s=!1}l.stringify=l.stringify||l.encode,l.parse=l.parse||l.decode;if(typeof h.init!="undefined")throw new Error("History.js Core has already been loaded...");h.init=function(e){return typeof h.Adapter=="undefined"?!1:(typeof h.initCore!="undefined"&&h.initCore(),typeof h.initHtml4!="undefined"&&h.initHtml4(),!0)},h.initCore=function(d){if(typeof h.initCore.initialized!="undefined")return!1;h.initCore.initialized=!0,h.options=h.options||{},h.options.hashChangeInterval=h.options.hashChangeInterval||100,h.options.safariPollInterval=h.options.safariPollInterval||500,h.options.doubleCheckInterval=h.options.doubleCheckInterval||500,h.options.disableSuid=h.options.disableSuid||!1,h.options.storeInterval=h.options.storeInterval||1e3,h.options.busyDelay=h.options.busyDelay||250,h.options.debug=h.options.debug||!1,h.options.initialTitle=h.options.initialTitle||r.title,h.options.html4Mode=h.options.html4Mode||!1,h.options.delayInit=h.options.delayInit||!1,h.intervalList=[],h.clearAllIntervals=function(){var e,t=h.intervalList;if(typeof t!="undefined"&&t!==null){for(e=0;e ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()}(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/compressed/history.adapter.dojo.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/compressed/history.adapter.dojo.js
new file mode 100644
index 00000000..f0ac1ca1
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/compressed/history.adapter.dojo.js
@@ -0,0 +1 @@
+(function(e,t){"use strict";var n=e.History=e.History||{},r=e.require;if(typeof n.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");n.Adapter={handlers:{},_uid:1,uid:function(e){return e._uid||(e._uid=n.Adapter._uid++)},bind:function(e,t,r){var i=n.Adapter.uid(e);n.Adapter.handlers[i]=n.Adapter.handlers[i]||{},n.Adapter.handlers[i][t]=n.Adapter.handlers[i][t]||[],n.Adapter.handlers[i][t].push(r),e["on"+t]=function(e,t){return function(r){n.Adapter.trigger(e,t,r)}}(e,t)},trigger:function(e,t,r){r=r||{};var i=n.Adapter.uid(e),s,o;n.Adapter.handlers[i]=n.Adapter.handlers[i]||{},n.Adapter.handlers[i][t]=n.Adapter.handlers[i][t]||[];for(s=0,o=n.Adapter.handlers[i][t].length;s ")&&n[0]);return e>4?e:!1}();return e},h.isInternetExplorer=function(){var e=h.isInternetExplorer.cached=typeof h.isInternetExplorer.cached!="undefined"?h.isInternetExplorer.cached:Boolean(h.getInternetExplorerMajorVersion());return e},h.options.html4Mode?h.emulated={pushState:!0,hashChange:!0}:h.emulated={pushState:!Boolean(e.history&&e.history.pushState&&e.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(i.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(i.userAgent)),hashChange:Boolean(!("onhashchange"in e||"onhashchange"in r)||h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8)},h.enabled=!h.emulated.pushState,h.bugs={setHash:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),safariPoll:Boolean(!h.emulated.pushState&&i.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(i.userAgent)),ieDoubleCheck:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(h.isInternetExplorer()&&h.getInternetExplorerMajorVersion()<7)},h.isEmptyObject=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},h.cloneObject=function(e){var t,n;return e?(t=l.stringify(e),n=l.parse(t)):n={},n},h.getRootUrl=function(){var e=r.location.protocol+"//"+(r.location.hostname||r.location.host);if(r.location.port||!1)e+=":"+r.location.port;return e+="/",e},h.getBaseHref=function(){var e=r.getElementsByTagName("base"),t=null,n="";return e.length===1&&(t=e[0],n=t.href.replace(/[^\/]+$/,"")),n=n.replace(/\/+$/,""),n&&(n+="/"),n},h.getBaseUrl=function(){var e=h.getBaseHref()||h.getBasePageUrl()||h.getRootUrl();return e},h.getPageUrl=function(){var e=h.getState(!1,!1),t=(e||{}).url||h.getLocationHref(),n;return n=t.replace(/\/+$/,"").replace(/[^\/]+$/,function(e,t,n){return/\./.test(e)?e:e+"/"}),n},h.getBasePageUrl=function(){var e=h.getLocationHref().replace(/[#\?].*/,"").replace(/[^\/]+$/,function(e,t,n){return/[^\/]$/.test(e)?"":e}).replace(/\/+$/,"")+"/";return e},h.getFullUrl=function(e,t){var n=e,r=e.substring(0,1);return t=typeof t=="undefined"?!0:t,/[a-z]+\:\/\//.test(e)||(r==="/"?n=h.getRootUrl()+e.replace(/^\/+/,""):r==="#"?n=h.getPageUrl().replace(/#.*/,"")+e:r==="?"?n=h.getPageUrl().replace(/[\?#].*/,"")+e:t?n=h.getBaseUrl()+e.replace(/^(\.\/)+/,""):n=h.getBasePageUrl()+e.replace(/^(\.\/)+/,"")),n.replace(/\#$/,"")},h.getShortUrl=function(e){var t=e,n=h.getBaseUrl(),r=h.getRootUrl();return h.emulated.pushState&&(t=t.replace(n,"")),t=t.replace(r,"/"),h.isTraditionalAnchor(t)&&(t="./"+t),t=t.replace(/^(\.\/)+/g,"./").replace(/\#$/,""),t},h.getLocationHref=function(e){return e=e||r,e.URL===e.location.href?e.location.href:e.location.href===decodeURIComponent(e.URL)?e.URL:e.location.hash&&decodeURIComponent(e.location.href.replace(/^[^#]+/,""))===e.location.hash?e.location.href:e.URL.indexOf("#")==-1&&e.location.href.indexOf("#")!=-1?e.location.href:e.URL||e.location.href},h.store={},h.idToState=h.idToState||{},h.stateToId=h.stateToId||{},h.urlToId=h.urlToId||{},h.storedStates=h.storedStates||[],h.savedStates=h.savedStates||[],h.normalizeStore=function(){h.store.idToState=h.store.idToState||{},h.store.urlToId=h.store.urlToId||{},h.store.stateToId=h.store.stateToId||{}},h.getState=function(e,t){typeof e=="undefined"&&(e=!0),typeof t=="undefined"&&(t=!0);var n=h.getLastSavedState();return!n&&t&&(n=h.createStateObject()),e&&(n=h.cloneObject(n),n.url=n.cleanUrl||n.url),n},h.getIdByState=function(e){var t=h.extractId(e.url),n;if(!t){n=h.getStateString(e);if(typeof h.stateToId[n]!="undefined")t=h.stateToId[n];else if(typeof h.store.stateToId[n]!="undefined")t=h.store.stateToId[n];else{for(;;){t=(new Date).getTime()+String(Math.random()).replace(/\D/g,"");if(typeof h.idToState[t]=="undefined"&&typeof h.store.idToState[t]=="undefined")break}h.stateToId[n]=t,h.idToState[t]=e}}return t},h.normalizeState=function(e){var t,n;if(!e||typeof e!="object")e={};if(typeof e.normalized!="undefined")return e;if(!e.data||typeof e.data!="object")e.data={};return t={},t.normalized=!0,t.title=e.title||"",t.url=h.getFullUrl(e.url?e.url:h.getLocationHref()),t.hash=h.getShortUrl(t.url),t.data=h.cloneObject(e.data),t.id=h.getIdByState(t),t.cleanUrl=t.url.replace(/\??\&_suid.*/,""),t.url=t.cleanUrl,n=!h.isEmptyObject(t.data),(t.title||n)&&h.options.disableSuid!==!0&&(t.hash=h.getShortUrl(t.url).replace(/\??\&_suid.*/,""),/\?/.test(t.hash)||(t.hash+="?"),t.hash+="&_suid="+t.id),t.hashedUrl=h.getFullUrl(t.hash),(h.emulated.pushState||h.bugs.safariPoll)&&h.hasUrlDuplicate(t)&&(t.url=t.hashedUrl),t},h.createStateObject=function(e,t,n){var r={data:e,title:t,url:n};return r=h.normalizeState(r),r},h.getStateById=function(e){e=String(e);var n=h.idToState[e]||h.store.idToState[e]||t;return n},h.getStateString=function(e){var t,n,r;return t=h.normalizeState(e),n={data:t.data,title:e.title,url:e.url},r=l.stringify(n),r},h.getStateId=function(e){var t,n;return t=h.normalizeState(e),n=t.id,n},h.getHashByState=function(e){var t,n;return t=h.normalizeState(e),n=t.hash,n},h.extractId=function(e){var t,n,r,i;return e.indexOf("#")!=-1?i=e.split("#")[0]:i=e,n=/(.*)\&_suid=([0-9]+)$/.exec(i),r=n?n[1]||e:e,t=n?String(n[2]||""):"",t||!1},h.isTraditionalAnchor=function(e){var t=!/[\/\?\.]/.test(e);return t},h.extractState=function(e,t){var n=null,r,i;return t=t||!1,r=h.extractId(e),r&&(n=h.getStateById(r)),n||(i=h.getFullUrl(e),r=h.getIdByUrl(i)||!1,r&&(n=h.getStateById(r)),!n&&t&&!h.isTraditionalAnchor(e)&&(n=h.createStateObject(null,null,i))),n},h.getIdByUrl=function(e){var n=h.urlToId[e]||h.store.urlToId[e]||t;return n},h.getLastSavedState=function(){return h.savedStates[h.savedStates.length-1]||t},h.getLastStoredState=function(){return h.storedStates[h.storedStates.length-1]||t},h.hasUrlDuplicate=function(e){var t=!1,n;return n=h.extractState(e.url),t=n&&n.id!==e.id,t},h.storeState=function(e){return h.urlToId[e.url]=e.id,h.storedStates.push(h.cloneObject(e)),e},h.isLastSavedState=function(e){var t=!1,n,r,i;return h.savedStates.length&&(n=e.id,r=h.getLastSavedState(),i=r.id,t=n===i),t},h.saveState=function(e){return h.isLastSavedState(e)?!1:(h.savedStates.push(h.cloneObject(e)),!0)},h.getStateByIndex=function(e){var t=null;return typeof e=="undefined"?t=h.savedStates[h.savedStates.length-1]:e<0?t=h.savedStates[h.savedStates.length+e]:t=h.savedStates[e],t},h.getCurrentIndex=function(){var e=null;return h.savedStates.length<1?e=0:e=h.savedStates.length-1,e},h.getHash=function(e){var t=h.getLocationHref(e),n;return n=h.getHashByUrl(t),n},h.unescapeHash=function(e){var t=h.normalizeHash(e);return t=decodeURIComponent(t),t},h.normalizeHash=function(e){var t=e.replace(/[^#]*#/,"").replace(/#.*/,"");return t},h.setHash=function(e,t){var n,i;return t!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.setHash,args:arguments,queue:t}),!1):(h.busy(!0),n=h.extractState(e,!0),n&&!h.emulated.pushState?h.pushState(n.data,n.title,n.url,!1):h.getHash()!==e&&(h.bugs.setHash?(i=h.getPageUrl(),h.pushState(null,null,i+"#"+e,!1)):r.location.hash=e),h)},h.escapeHash=function(t){var n=h.normalizeHash(t);return n=e.encodeURIComponent(n),h.bugs.hashEscape||(n=n.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?")),n},h.getHashByUrl=function(e){var t=String(e).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");return t=h.unescapeHash(t),t},h.setTitle=function(e){var t=e.title,n;t||(n=h.getStateByIndex(0),n&&n.url===e.url&&(t=n.title||h.options.initialTitle));try{r.getElementsByTagName("title")[0].innerHTML=t.replace("<","<").replace(">",">").replace(" & "," & ")}catch(i){}return r.title=t,h},h.queues=[],h.busy=function(e){typeof e!="undefined"?h.busy.flag=e:typeof h.busy.flag=="undefined"&&(h.busy.flag=!1);if(!h.busy.flag){u(h.busy.timeout);var t=function(){var e,n,r;if(h.busy.flag)return;for(e=h.queues.length-1;e>=0;--e){n=h.queues[e];if(n.length===0)continue;r=n.shift(),h.fireQueueItem(r),h.busy.timeout=o(t,h.options.busyDelay)}};h.busy.timeout=o(t,h.options.busyDelay)}return h.busy.flag},h.busy.flag=!1,h.fireQueueItem=function(e){return e.callback.apply(e.scope||h,e.args||[])},h.pushQueue=function(e){return h.queues[e.queue||0]=h.queues[e.queue||0]||[],h.queues[e.queue||0].push(e),h},h.queue=function(e,t){return typeof e=="function"&&(e={callback:e}),typeof t!="undefined"&&(e.queue=t),h.busy()?h.pushQueue(e):h.fireQueueItem(e),h},h.clearQueue=function(){return h.busy.flag=!1,h.queues=[],h},h.stateChanged=!1,h.doubleChecker=!1,h.doubleCheckComplete=function(){return h.stateChanged=!0,h.doubleCheckClear(),h},h.doubleCheckClear=function(){return h.doubleChecker&&(u(h.doubleChecker),h.doubleChecker=!1),h},h.doubleCheck=function(e){return h.stateChanged=!1,h.doubleCheckClear(),h.bugs.ieDoubleCheck&&(h.doubleChecker=o(function(){return h.doubleCheckClear(),h.stateChanged||e(),!0},h.options.doubleCheckInterval)),h},h.safariStatePoll=function(){var t=h.extractState(h.getLocationHref()),n;if(!h.isLastSavedState(t))return n=t,n||(n=h.createStateObject()),h.Adapter.trigger(e,"popstate"),h;return},h.back=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.back,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.back(!1)}),p.go(-1),!0)},h.forward=function(e){return e!==!1&&h.busy()?(h.pushQueue({scope:h,callback:h.forward,args:arguments,queue:e}),!1):(h.busy(!0),h.doubleCheck(function(){h.forward(!1)}),p.go(1),!0)},h.go=function(e,t){var n;if(e>0)for(n=1;n<=e;++n)h.forward(t);else{if(!(e<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(n=-1;n>=e;--n)h.back(t)}return h};if(h.emulated.pushState){var v=function(){};h.pushState=h.pushState||v,h.replaceState=h.replaceState||v}else h.onPopState=function(t,n){var r=!1,i=!1,s,o;return h.doubleCheckComplete(),s=h.getHash(),s?(o=h.extractState(s||h.getLocationHref(),!0),o?h.replaceState(o.data,o.title,o.url,!1):(h.Adapter.trigger(e,"anchorchange"),h.busy(!1)),h.expectedStateId=!1,!1):(r=h.Adapter.extractEventData("state",t,n)||!1,r?i=h.getStateById(r):h.expectedStateId?i=h.getStateById(h.expectedStateId):i=h.extractState(h.getLocationHref()),i||(i=h.createStateObject(null,null,h.getLocationHref())),h.expectedStateId=!1,h.isLastSavedState(i)?(h.busy(!1),!1):(h.storeState(i),h.saveState(i),h.setTitle(i),h.Adapter.trigger(e,"statechange"),h.busy(!1),!0))},h.Adapter.bind(e,"popstate",h.onPopState),h.pushState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.pushState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.pushState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0},h.replaceState=function(t,n,r,i){if(h.getHashByUrl(r)&&h.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(i!==!1&&h.busy())return h.pushQueue({scope:h,callback:h.replaceState,args:arguments,queue:i}),!1;h.busy(!0);var s=h.createStateObject(t,n,r);return h.isLastSavedState(s)?h.busy(!1):(h.storeState(s),h.expectedStateId=s.id,p.replaceState(s.id,s.title,s.url),h.Adapter.trigger(e,"popstate")),!0};if(s){try{h.store=l.parse(s.getItem("History.store"))||{}}catch(m){h.store={}}h.normalizeStore()}else h.store={},h.normalizeStore();h.Adapter.bind(e,"unload",h.clearAllIntervals),h.saveState(h.storeState(h.extractState(h.getLocationHref(),!0))),s&&(h.onUnload=function(){var e,t,n;try{e=l.parse(s.getItem("History.store"))||{}}catch(r){e={}}e.idToState=e.idToState||{},e.urlToId=e.urlToId||{},e.stateToId=e.stateToId||{};for(t in h.idToState){if(!h.idToState.hasOwnProperty(t))continue;e.idToState[t]=h.idToState[t]}for(t in h.urlToId){if(!h.urlToId.hasOwnProperty(t))continue;e.urlToId[t]=h.urlToId[t]}for(t in h.stateToId){if(!h.stateToId.hasOwnProperty(t))continue;e.stateToId[t]=h.stateToId[t]}h.store=e,h.normalizeStore(),n=l.stringify(e);try{s.setItem("History.store",n)}catch(i){if(i.code!==DOMException.QUOTA_EXCEEDED_ERR)throw i;s.length&&(s.removeItem("History.store"),s.setItem("History.store",n))}},h.intervalList.push(a(h.onUnload,h.options.storeInterval)),h.Adapter.bind(e,"beforeunload",h.onUnload),h.Adapter.bind(e,"unload",h.onUnload));if(!h.emulated.pushState){h.bugs.safariPoll&&h.intervalList.push(a(h.safariStatePoll,h.options.safariPollInterval));if(i.vendor==="Apple Computer, Inc."||(i.appCodeName||"")==="Mozilla")h.Adapter.bind(e,"hashchange",function(){h.Adapter.trigger(e,"popstate")}),h.getHash()&&h.Adapter.onDomLoad(function(){h.Adapter.trigger(e,"hashchange")})}},(!h.options||!h.options.delayInit)&&h.init()})(window)
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/compressed/json2.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/compressed/json2.js
new file mode 100644
index 00000000..0eb302e6
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/compressed/json2.js
@@ -0,0 +1 @@
+typeof JSON!="object"&&(JSON={}),function(){"use strict";function f(e){return e<10?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return typeof t=="string"?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,r,i,s,o=gap,u,a=t[e];a&&typeof a=="object"&&typeof a.toJSON=="function"&&(a=a.toJSON(e)),typeof rep=="function"&&(a=rep.call(t,e,a));switch(typeof a){case"string":return quote(a);case"number":return isFinite(a)?String(a):"null";case"boolean":case"null":return String(a);case"object":if(!a)return"null";gap+=indent,u=[];if(Object.prototype.toString.apply(a)==="[object Array]"){s=a.length;for(n=0;n
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var History = window.History = window.History||{},
+ require = window.require;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.handlers[uid][eventName] = Array
+ */
+ handlers: {},
+
+ /**
+ * History.Adapter._uid
+ * The current element unique identifier
+ */
+ _uid: 1,
+
+ /**
+ * History.Adapter.uid(element)
+ * @param {Element} element
+ * @return {String} uid
+ */
+ uid: function(element){
+ return element._uid || (element._uid = History.Adapter._uid++);
+ },
+
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element} element
+ * @param {String} eventName - custom and standard events
+ * @param {Function} callback
+ * @return
+ */
+ bind: function(element,eventName,callback){
+ // Prepare
+ var uid = History.Adapter.uid(element);
+
+ // Apply Listener
+ History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
+ History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
+ History.Adapter.handlers[uid][eventName].push(callback);
+
+ // Bind Global Listener
+ element['on'+eventName] = (function(element,eventName){
+ return function(event){
+ History.Adapter.trigger(element,eventName,event);
+ };
+ })(element,eventName);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element} element
+ * @param {String} eventName - custom and standard events
+ * @param {Object} event - a object of event data
+ * @return
+ */
+ trigger: function(element,eventName,event){
+ // Prepare
+ event = event || {};
+ var uid = History.Adapter.uid(element),
+ i,n;
+
+ // Apply Listener
+ History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
+ History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
+
+ // Fire Listeners
+ for ( i=0,n=History.Adapter.handlers[uid][eventName].length; i
+ * @copyright 2012 Sean Adkinson
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ Ext = window.Ext;
+
+ window.JSON = {
+ stringify: Ext.JSON.encode,
+ parse: Ext.JSON.decode
+ };
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ observables: {},
+
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {function} callback
+ * @param {Object} scope
+ * @return {void}
+ */
+ bind: function(element,eventName,callback,scope){
+ Ext.EventManager.addListener(element, eventName, callback, scope);
+
+ //bind an observable to the element that will let us "trigger" events on it
+ var id = Ext.id(element, 'history-'), observable = this.observables[id];
+ if (!observable) {
+ observable = Ext.create('Ext.util.Observable');
+ this.observables[id] = observable;
+ }
+ observable.on(eventName, callback, scope);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return {void}
+ */
+ trigger: function(element,eventName,extra){
+ var id = Ext.id(element, 'history-'), observable = this.observables[id];
+ if (observable) {
+ observable.fireEvent(eventName, extra);
+ }
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {string} key - key for the event data to extract
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return {mixed}
+ */
+ extractEventData: function(key,event,extra){
+ var result = (event && event.browserEvent && event.browserEvent[key]) || (extra && extra[key]) || undefined;
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {function} callback
+ * @return {void}
+ */
+ onDomLoad: function(callback) {
+ Ext.onReady(callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.adapter.jquery.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.adapter.jquery.js
new file mode 100644
index 00000000..8c252d5b
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.adapter.jquery.js
@@ -0,0 +1,77 @@
+/**
+ * History.js jQuery Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ jQuery = window.jQuery;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {function} callback
+ * @return {void}
+ */
+ bind: function(el,event,callback){
+ jQuery(el).bind(event,callback);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return {void}
+ */
+ trigger: function(el,event,extra){
+ jQuery(el).trigger(event,extra);
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {string} key - key for the event data to extract
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return {mixed}
+ */
+ extractEventData: function(key,event,extra){
+ // jQuery Native then jQuery Custom
+ var result = (event && event.originalEvent && event.originalEvent[key]) || (extra && extra[key]) || undefined;
+
+ // Return
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {function} callback
+ * @return {void}
+ */
+ onDomLoad: function(callback) {
+ jQuery(callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.adapter.mootools.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.adapter.mootools.js
new file mode 100644
index 00000000..404425c4
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.adapter.mootools.js
@@ -0,0 +1,84 @@
+/**
+ * History.js MooTools Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ MooTools = window.MooTools,
+ Element = window.Element;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Make MooTools aware of History.js Events
+ Object.append(Element.NativeEvents,{
+ 'popstate':2,
+ 'hashchange':2
+ });
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {function} callback
+ * @return {void}
+ */
+ bind: function(el,event,callback){
+ var El = typeof el === 'string' ? document.id(el) : el;
+ El.addEvent(event,callback);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {Object=} extra - a object of extra event data (optional)
+ * @return void
+ */
+ trigger: function(el,event,extra){
+ var El = typeof el === 'string' ? document.id(el) : el;
+ El.fireEvent(event,extra);
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {string} key - key for the event data to extract
+ * @param {string} event - custom and standard events
+ * @return {mixed}
+ */
+ extractEventData: function(key,event){
+ // MooTools Native then MooTools Custom
+ var result = (event && event.event && event.event[key]) || (event && event[key]) || undefined;
+
+ // Return
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {function} callback
+ * @return {void}
+ */
+ onDomLoad: function(callback) {
+ window.addEvent('domready',callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.adapter.native.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.adapter.native.js
new file mode 100644
index 00000000..cb42fbd6
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.adapter.native.js
@@ -0,0 +1,121 @@
+/**
+ * History.js Native Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var History = window.History = window.History||{};
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.handlers[uid][eventName] = Array
+ */
+ handlers: {},
+
+ /**
+ * History.Adapter._uid
+ * The current element unique identifier
+ */
+ _uid: 1,
+
+ /**
+ * History.Adapter.uid(element)
+ * @param {Element} element
+ * @return {String} uid
+ */
+ uid: function(element){
+ return element._uid || (element._uid = History.Adapter._uid++);
+ },
+
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element} element
+ * @param {String} eventName - custom and standard events
+ * @param {Function} callback
+ * @return
+ */
+ bind: function(element,eventName,callback){
+ // Prepare
+ var uid = History.Adapter.uid(element);
+
+ // Apply Listener
+ History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
+ History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
+ History.Adapter.handlers[uid][eventName].push(callback);
+
+ // Bind Global Listener
+ element['on'+eventName] = (function(element,eventName){
+ return function(event){
+ History.Adapter.trigger(element,eventName,event);
+ };
+ })(element,eventName);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element} element
+ * @param {String} eventName - custom and standard events
+ * @param {Object} event - a object of event data
+ * @return
+ */
+ trigger: function(element,eventName,event){
+ // Prepare
+ event = event || {};
+ var uid = History.Adapter.uid(element),
+ i,n;
+
+ // Apply Listener
+ History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
+ History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
+
+ // Fire Listeners
+ for ( i=0,n=History.Adapter.handlers[uid][eventName].length; i
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ document = window.document,
+ RightJS = window.RightJS,
+ $ = RightJS.$;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|Selector} el
+ * @param {String} event - custom and standard events
+ * @param {Function} callback
+ * @return
+ */
+ bind: function(el,event,callback){
+ $(el).on(event,callback);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|Selector} el
+ * @param {String} event - custom and standard events
+ * @param {Object} extraEventData - a object of extra event data
+ * @return
+ */
+ trigger: function(el,event,extraEventData){
+ $(el).fire(event,extraEventData);
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {String} key - key for the event data to extract
+ * @param {String} event - custom and standard events
+ * @return {mixed}
+ */
+ extractEventData: function(key,event){
+ // Right.js Native
+ // Right.js Custom
+ var result = (event && event._ && event._[key]) || undefined;
+
+ // Return
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {Function} callback
+ * @return
+ */
+ onDomLoad: function(callback) {
+ $(document).onReady(callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.adapter.zepto.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.adapter.zepto.js
new file mode 100644
index 00000000..f1295f9d
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.adapter.zepto.js
@@ -0,0 +1,74 @@
+/**
+ * History.js Zepto Adapter
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+// Closure
+(function(window,undefined){
+ "use strict";
+
+ // Localise Globals
+ var
+ History = window.History = window.History||{},
+ Zepto = window.Zepto;
+
+ // Check Existence
+ if ( typeof History.Adapter !== 'undefined' ) {
+ throw new Error('History.js Adapter has already been loaded...');
+ }
+
+ // Add the Adapter
+ History.Adapter = {
+ /**
+ * History.Adapter.bind(el,event,callback)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @param {function} callback
+ * @return {void}
+ */
+ bind: function(el,event,callback){
+ new Zepto(el).bind(event,callback);
+ },
+
+ /**
+ * History.Adapter.trigger(el,event)
+ * @param {Element|string} el
+ * @param {string} event - custom and standard events
+ * @return {void}
+ */
+ trigger: function(el,event){
+ new Zepto(el).trigger(event);
+ },
+
+ /**
+ * History.Adapter.extractEventData(key,event,extra)
+ * @param {string} key - key for the event data to extract
+ * @param {string} event - custom and standard events
+ * @return {mixed}
+ */
+ extractEventData: function(key,event){
+ // Zepto Native
+ var result = (event && event[key]) || undefined;
+
+ // Return
+ return result;
+ },
+
+ /**
+ * History.Adapter.onDomLoad(callback)
+ * @param {function} callback
+ * @return {void}
+ */
+ onDomLoad: function(callback) {
+ new Zepto(callback);
+ }
+ };
+
+ // Try and Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.html4.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.html4.js
new file mode 100644
index 00000000..610c8ee6
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.html4.js
@@ -0,0 +1,685 @@
+/**
+ * History.js HTML4 Support
+ * Depends on the HTML5 Support
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ document = window.document, // Make sure we are using the correct document
+ setTimeout = window.setTimeout||setTimeout,
+ clearTimeout = window.clearTimeout||clearTimeout,
+ setInterval = window.setInterval||setInterval,
+ History = window.History = window.History||{}; // Public History Object
+
+ // Check Existence
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ throw new Error('History.js HTML4 Support has already been loaded...');
+ }
+
+
+ // ========================================================================
+ // Initialise HTML4 Support
+
+ // Initialise HTML4 Support
+ History.initHtml4 = function(){
+ // Initialise
+ if ( typeof History.initHtml4.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initHtml4.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Properties
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = true;
+
+
+ // ====================================================================
+ // Hash Storage
+
+ /**
+ * History.savedHashes
+ * Store the hashes in an array
+ */
+ History.savedHashes = [];
+
+ /**
+ * History.isLastHash(newHash)
+ * Checks if the hash is the last hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.isLastHash = function(newHash){
+ // Prepare
+ var oldHash = History.getHashByIndex(),
+ isLast;
+
+ // Check
+ isLast = newHash === oldHash;
+
+ // Return isLast
+ return isLast;
+ };
+
+ /**
+ * History.isHashEqual(newHash, oldHash)
+ * Checks to see if two hashes are functionally equal
+ * @param {string} newHash
+ * @param {string} oldHash
+ * @return {boolean} true
+ */
+ History.isHashEqual = function(newHash, oldHash){
+ newHash = encodeURIComponent(newHash).replace(/%25/g, "%");
+ oldHash = encodeURIComponent(oldHash).replace(/%25/g, "%");
+ return newHash === oldHash;
+ };
+
+ /**
+ * History.saveHash(newHash)
+ * Push a Hash
+ * @param {string} newHash
+ * @return {boolean} true
+ */
+ History.saveHash = function(newHash){
+ // Check Hash
+ if ( History.isLastHash(newHash) ) {
+ return false;
+ }
+
+ // Push the Hash
+ History.savedHashes.push(newHash);
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getHashByIndex()
+ * Gets a hash by the index
+ * @param {integer} index
+ * @return {string}
+ */
+ History.getHashByIndex = function(index){
+ // Prepare
+ var hash = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ hash = History.savedHashes[History.savedHashes.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ hash = History.savedHashes[History.savedHashes.length+index];
+ }
+ else {
+ // Get from the beginning
+ hash = History.savedHashes[index];
+ }
+
+ // Return hash
+ return hash;
+ };
+
+
+ // ====================================================================
+ // Discarded States
+
+ /**
+ * History.discardedHashes
+ * A hashed array of discarded hashes
+ */
+ History.discardedHashes = {};
+
+ /**
+ * History.discardedStates
+ * A hashed array of discarded states
+ */
+ History.discardedStates = {};
+
+ /**
+ * History.discardState(State)
+ * Discards the state by ignoring it through History
+ * @param {object} State
+ * @return {true}
+ */
+ History.discardState = function(discardedState,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Prepare
+ var discardedStateHash = History.getHashByState(discardedState),
+ discardObject;
+
+ // Create Discard Object
+ discardObject = {
+ 'discardedState': discardedState,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to DiscardedStates
+ History.discardedStates[discardedStateHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardHash(hash)
+ * Discards the hash by ignoring it through History
+ * @param {string} hash
+ * @return {true}
+ */
+ History.discardHash = function(discardedHash,forwardState,backState){
+ //History.debug('History.discardState', arguments);
+ // Create Discard Object
+ var discardObject = {
+ 'discardedHash': discardedHash,
+ 'backState': backState,
+ 'forwardState': forwardState
+ };
+
+ // Add to discardedHash
+ History.discardedHashes[discardedHash] = discardObject;
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.discardedState(State)
+ * Checks to see if the state is discarded
+ * @param {object} State
+ * @return {bool}
+ */
+ History.discardedState = function(State){
+ // Prepare
+ var StateHash = History.getHashByState(State),
+ discarded;
+
+ // Check
+ discarded = History.discardedStates[StateHash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.discardedHash(hash)
+ * Checks to see if the state is discarded
+ * @param {string} State
+ * @return {bool}
+ */
+ History.discardedHash = function(hash){
+ // Check
+ var discarded = History.discardedHashes[hash]||false;
+
+ // Return true
+ return discarded;
+ };
+
+ /**
+ * History.recycleState(State)
+ * Allows a discarded state to be used again
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.recycleState = function(State){
+ //History.debug('History.recycleState', arguments);
+ // Prepare
+ var StateHash = History.getHashByState(State);
+
+ // Remove from DiscardedStates
+ if ( History.discardedState(State) ) {
+ delete History.discardedStates[StateHash];
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ====================================================================
+ // HTML4 HashChange Support
+
+ if ( History.emulated.hashChange ) {
+ /*
+ * We must emulate the HTML4 HashChange Support by manually checking for hash changes
+ */
+
+ /**
+ * History.hashChangeInit()
+ * Init the HashChange Emulation
+ */
+ History.hashChangeInit = function(){
+ // Define our Checker Function
+ History.checkerFunction = null;
+
+ // Define some variables that will help in our checker function
+ var lastDocumentHash = '',
+ iframeId, iframe,
+ lastIframeHash, checkerRunning,
+ startedWithHash = Boolean(History.getHash());
+
+ // Handle depending on the browser
+ if ( History.isInternetExplorer() ) {
+ // IE6 and IE7
+ // We need to use an iframe to emulate the back and forward buttons
+
+ // Create iFrame
+ iframeId = 'historyjs-iframe';
+ iframe = document.createElement('iframe');
+
+ // Adjust iFarme
+ // IE 6 requires iframe to have a src on HTTPS pages, otherwise it will throw a
+ // "This page contains both secure and nonsecure items" warning.
+ iframe.setAttribute('id', iframeId);
+ iframe.setAttribute('src', '#');
+ iframe.style.display = 'none';
+
+ // Append iFrame
+ document.body.appendChild(iframe);
+
+ // Create initial history entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Define some variables that will help in our checker function
+ lastIframeHash = '';
+ checkerRunning = false;
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Check Running
+ if ( checkerRunning ) {
+ return false;
+ }
+
+ // Update Running
+ checkerRunning = true;
+
+ // Fetch
+ var
+ documentHash = History.getHash(),
+ iframeHash = History.getHash(iframe.contentWindow.document);
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Create a history entry in the iframe
+ if ( iframeHash !== documentHash ) {
+ //History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);
+
+ // Equalise
+ lastIframeHash = iframeHash = documentHash;
+
+ // Create History Entry
+ iframe.contentWindow.document.open();
+ iframe.contentWindow.document.close();
+
+ // Update the iframe's hash
+ iframe.contentWindow.document.location.hash = History.escapeHash(documentHash);
+ }
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // The iFrame Hash has changed (back button caused)
+ else if ( iframeHash !== lastIframeHash ) {
+ //History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);
+
+ // Equalise
+ lastIframeHash = iframeHash;
+
+ // If there is no iframe hash that means we're at the original
+ // iframe state.
+ // And if there was a hash on the original request, the original
+ // iframe state was replaced instantly, so skip this state and take
+ // the user back to where they came from.
+ if (startedWithHash && iframeHash === '') {
+ History.back();
+ }
+ else {
+ // Update the Hash
+ History.setHash(iframeHash,false);
+ }
+ }
+
+ // Reset Running
+ checkerRunning = false;
+
+ // Return true
+ return true;
+ };
+ }
+ else {
+ // We are not IE
+ // Firefox 1 or 2, Opera
+
+ // Define the checker function
+ History.checkerFunction = function(){
+ // Prepare
+ var documentHash = History.getHash()||'';
+
+ // The Document Hash has changed (application caused)
+ if ( documentHash !== lastDocumentHash ) {
+ // Equalise
+ lastDocumentHash = documentHash;
+
+ // Trigger Hashchange Event
+ History.Adapter.trigger(window,'hashchange');
+ }
+
+ // Return true
+ return true;
+ };
+ }
+
+ // Apply the checker function
+ History.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));
+
+ // Done
+ return true;
+ }; // History.hashChangeInit
+
+ // Bind hashChangeInit
+ History.Adapter.onDomLoad(History.hashChangeInit);
+
+ } // History.emulated.hashChange
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * We must emulate the HTML5 State Management by using HTML4 HashChange
+ */
+
+ /**
+ * History.onHashChange(event)
+ * Trigger HTML5's window.onpopstate via HTML4 HashChange Support
+ */
+ History.onHashChange = function(event){
+ //History.debug('History.onHashChange', arguments);
+
+ // Prepare
+ var currentUrl = ((event && event.newURL) || History.getLocationHref()),
+ currentHash = History.getHashByUrl(currentUrl),
+ currentState = null,
+ currentStateHash = null,
+ currentStateHashExits = null,
+ discardObject;
+
+ // Check if we are the same state
+ if ( History.isLastHash(currentHash) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onHashChange: no change');
+ History.busy(false);
+ return false;
+ }
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Store our location for use in detecting back/forward direction
+ History.saveHash(currentHash);
+
+ // Expand Hash
+ if ( currentHash && History.isTraditionalAnchor(currentHash) ) {
+ //History.debug('History.onHashChange: traditional anchor', currentHash);
+ // Traditional Anchor Hash
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ return false;
+ }
+
+ // Create State
+ currentState = History.extractState(History.getFullUrl(currentHash||History.getLocationHref()),true);
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(currentState) ) {
+ //History.debug('History.onHashChange: no change');
+ // There has been no change (just the page's hash has finally propagated)
+ History.busy(false);
+ return false;
+ }
+
+ // Create the state Hash
+ currentStateHash = History.getHashByState(currentState);
+
+ // Check if we are DiscardedState
+ discardObject = History.discardedState(currentState);
+ if ( discardObject ) {
+ // Ignore this state as it has been discarded and go back to the state before it
+ if ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {
+ // We are going backwards
+ //History.debug('History.onHashChange: go backwards');
+ History.back(false);
+ } else {
+ // We are going forwards
+ //History.debug('History.onHashChange: go forwards');
+ History.forward(false);
+ }
+ return false;
+ }
+
+ // Push the new HTML5 State
+ //History.debug('History.onHashChange: success hashchange');
+ History.pushState(currentState.data,currentState.title,encodeURI(currentState.url),false);
+
+ // End onHashChange closure
+ return true;
+ };
+ History.Adapter.bind(window,'hashchange',History.onHashChange);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Object
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ html4Hash = History.getHash(),
+ wasExpected = History.expectedStateId == newState.id;
+
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Check if we are the same State
+ if ( newStateHash === oldStateHash ) {
+ //History.debug('History.pushState: no change', newStateHash);
+ History.busy(false);
+ return false;
+ }
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ if(!wasExpected)
+ History.Adapter.trigger(window,'statechange');
+
+ // Update HTML4 Hash
+ if ( !History.isHashEqual(newStateHash, html4Hash) && !History.isHashEqual(newStateHash, History.getShortUrl(History.getLocationHref())) ) {
+ History.setHash(newStateHash,false);
+ }
+
+ History.busy(false);
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // We assume that the URL passed in is URI-encoded, but this makes
+ // sure that it's fully URI encoded; any '%'s that are encoded are
+ // converted back into '%'s
+ url = encodeURI(url).replace(/%25/g, "%");
+
+ // Check the State
+ if ( History.getHashByUrl(url) ) {
+ throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy
+ History.busy(true);
+
+ // Fetch the State Objects
+ var newState = History.createStateObject(data,title,url),
+ newStateHash = History.getHashByState(newState),
+ oldState = History.getState(false),
+ oldStateHash = History.getHashByState(oldState),
+ previousState = History.getStateByIndex(-2);
+
+ // Discard Old State
+ History.discardState(oldState,newState,previousState);
+
+ // If the url hasn't changed, just store and save the state
+ // and fire a statechange event to be consistent with the
+ // html 5 api
+ if ( newStateHash === oldStateHash ) {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Recycle the State
+ History.recycleState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Update HTML5 State
+ History.saveState(newState);
+
+ // Fire HTML5 Event
+ //History.debug('History.pushState: trigger popstate');
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+ }
+ else {
+ // Alias to PushState
+ History.pushState(newState.data,newState.title,newState.url,false);
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // History.emulated.pushState
+
+
+
+ // ====================================================================
+ // Initialise
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /**
+ * Ensure initial state is handled correctly
+ */
+ if ( History.getHash() && !History.emulated.hashChange ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+
+ } // History.emulated.pushState
+
+ }; // History.initHtml4
+
+ // Try to Initialise History
+ if ( typeof History.init !== 'undefined' ) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.js
new file mode 100644
index 00000000..299e7721
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/history.js
@@ -0,0 +1,2044 @@
+/**
+ * History.js Core
+ * @author Benjamin Arthur Lupton
+ * @copyright 2010-2011 Benjamin Arthur Lupton
+ * @license New BSD License
+ */
+
+(function(window,undefined){
+ "use strict";
+
+ // ========================================================================
+ // Initialise
+
+ // Localise Globals
+ var
+ console = window.console||undefined, // Prevent a JSLint complain
+ document = window.document, // Make sure we are using the correct document
+ navigator = window.navigator, // Make sure we are using the correct navigator
+ sessionStorage = window.sessionStorage||false, // sessionStorage
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ setInterval = window.setInterval,
+ clearInterval = window.clearInterval,
+ JSON = window.JSON,
+ alert = window.alert,
+ History = window.History = window.History||{}, // Public History Object
+ history = window.history; // Old History Object
+
+ try {
+ sessionStorage.setItem('TEST', '1');
+ sessionStorage.removeItem('TEST');
+ } catch(e) {
+ sessionStorage = false;
+ }
+
+ // MooTools Compatibility
+ JSON.stringify = JSON.stringify||JSON.encode;
+ JSON.parse = JSON.parse||JSON.decode;
+
+ // Check Existence
+ if ( typeof History.init !== 'undefined' ) {
+ throw new Error('History.js Core has already been loaded...');
+ }
+
+ // Initialise History
+ History.init = function(options){
+ // Check Load Status of Adapter
+ if ( typeof History.Adapter === 'undefined' ) {
+ return false;
+ }
+
+ // Check Load Status of Core
+ if ( typeof History.initCore !== 'undefined' ) {
+ History.initCore();
+ }
+
+ // Check Load Status of HTML4 Support
+ if ( typeof History.initHtml4 !== 'undefined' ) {
+ History.initHtml4();
+ }
+
+ // Return true
+ return true;
+ };
+
+
+ // ========================================================================
+ // Initialise Core
+
+ // Initialise Core
+ History.initCore = function(options){
+ // Initialise
+ if ( typeof History.initCore.initialized !== 'undefined' ) {
+ // Already Loaded
+ return false;
+ }
+ else {
+ History.initCore.initialized = true;
+ }
+
+
+ // ====================================================================
+ // Options
+
+ /**
+ * History.options
+ * Configurable options
+ */
+ History.options = History.options||{};
+
+ /**
+ * History.options.hashChangeInterval
+ * How long should the interval be before hashchange checks
+ */
+ History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
+
+ /**
+ * History.options.safariPollInterval
+ * How long should the interval be before safari poll checks
+ */
+ History.options.safariPollInterval = History.options.safariPollInterval || 500;
+
+ /**
+ * History.options.doubleCheckInterval
+ * How long should the interval be before we perform a double check
+ */
+ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
+
+ /**
+ * History.options.disableSuid
+ * Force History not to append suid
+ */
+ History.options.disableSuid = History.options.disableSuid || false;
+
+ /**
+ * History.options.storeInterval
+ * How long should we wait between store calls
+ */
+ History.options.storeInterval = History.options.storeInterval || 1000;
+
+ /**
+ * History.options.busyDelay
+ * How long should we wait between busy events
+ */
+ History.options.busyDelay = History.options.busyDelay || 250;
+
+ /**
+ * History.options.debug
+ * If true will enable debug messages to be logged
+ */
+ History.options.debug = History.options.debug || false;
+
+ /**
+ * History.options.initialTitle
+ * What is the title of the initial state
+ */
+ History.options.initialTitle = History.options.initialTitle || document.title;
+
+ /**
+ * History.options.html4Mode
+ * If true, will force HTMl4 mode (hashtags)
+ */
+ History.options.html4Mode = History.options.html4Mode || false;
+
+ /**
+ * History.options.delayInit
+ * Want to override default options and call init manually.
+ */
+ History.options.delayInit = History.options.delayInit || false;
+
+
+ // ====================================================================
+ // Interval record
+
+ /**
+ * History.intervalList
+ * List of intervals set, to be cleared when document is unloaded.
+ */
+ History.intervalList = [];
+
+ /**
+ * History.clearAllIntervals
+ * Clears all setInterval instances.
+ */
+ History.clearAllIntervals = function(){
+ var i, il = History.intervalList;
+ if (typeof il !== "undefined" && il !== null) {
+ for (i = 0; i < il.length; i++) {
+ clearInterval(il[i]);
+ }
+ History.intervalList = null;
+ }
+ };
+
+
+ // ====================================================================
+ // Debug
+
+ /**
+ * History.debug(message,...)
+ * Logs the passed arguments if debug enabled
+ */
+ History.debug = function(){
+ if ( (History.options.debug||false) ) {
+ History.log.apply(History,arguments);
+ }
+ };
+
+ /**
+ * History.log(message,...)
+ * Logs the passed arguments
+ */
+ History.log = function(){
+ // Prepare
+ var
+ consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
+ textarea = document.getElementById('log'),
+ message,
+ i,n,
+ args,arg
+ ;
+
+ // Write to Console
+ if ( consoleExists ) {
+ args = Array.prototype.slice.call(arguments);
+ message = args.shift();
+ if ( typeof console.debug !== 'undefined' ) {
+ console.debug.apply(console,[message,args]);
+ }
+ else {
+ console.log.apply(console,[message,args]);
+ }
+ }
+ else {
+ message = ("\n"+arguments[0]+"\n");
+ }
+
+ // Write to log
+ for ( i=1,n=arguments.length; i
+ * @author James Padolsey
+ */
+ History.getInternetExplorerMajorVersion = function(){
+ var result = History.getInternetExplorerMajorVersion.cached =
+ (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
+ ? History.getInternetExplorerMajorVersion.cached
+ : (function(){
+ var v = 3,
+ div = document.createElement('div'),
+ all = div.getElementsByTagName('i');
+ while ( (div.innerHTML = '') && all[0] ) {}
+ return (v > 4) ? v : false;
+ })()
+ ;
+ return result;
+ };
+
+ /**
+ * History.isInternetExplorer()
+ * Are we using Internet Explorer?
+ * @return {boolean}
+ * @license Public Domain
+ * @author Benjamin Arthur Lupton
+ */
+ History.isInternetExplorer = function(){
+ var result =
+ History.isInternetExplorer.cached =
+ (typeof History.isInternetExplorer.cached !== 'undefined')
+ ? History.isInternetExplorer.cached
+ : Boolean(History.getInternetExplorerMajorVersion())
+ ;
+ return result;
+ };
+
+ /**
+ * History.emulated
+ * Which features require emulating?
+ */
+
+ if (History.options.html4Mode) {
+ History.emulated = {
+ pushState : true,
+ hashChange: true
+ };
+ }
+
+ else {
+
+ History.emulated = {
+ pushState: !Boolean(
+ window.history && window.history.pushState && window.history.replaceState
+ && !(
+ (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
+ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
+ )
+ ),
+ hashChange: Boolean(
+ !(('onhashchange' in window) || ('onhashchange' in document))
+ ||
+ (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
+ )
+ };
+ }
+
+ /**
+ * History.enabled
+ * Is History enabled?
+ */
+ History.enabled = !History.emulated.pushState;
+
+ /**
+ * History.bugs
+ * Which bugs are present
+ */
+ History.bugs = {
+ /**
+ * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
+ * https://bugs.webkit.org/show_bug.cgi?id=56249
+ */
+ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
+ * https://bugs.webkit.org/show_bug.cgi?id=42940
+ */
+ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
+
+ /**
+ * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
+ */
+ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
+
+ /**
+ * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
+ */
+ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
+ };
+
+ /**
+ * History.isEmptyObject(obj)
+ * Checks to see if the Object is Empty
+ * @param {Object} obj
+ * @return {boolean}
+ */
+ History.isEmptyObject = function(obj) {
+ for ( var name in obj ) {
+ if ( obj.hasOwnProperty(name) ) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ /**
+ * History.cloneObject(obj)
+ * Clones a object and eliminate all references to the original contexts
+ * @param {Object} obj
+ * @return {Object}
+ */
+ History.cloneObject = function(obj) {
+ var hash,newObj;
+ if ( obj ) {
+ hash = JSON.stringify(obj);
+ newObj = JSON.parse(hash);
+ }
+ else {
+ newObj = {};
+ }
+ return newObj;
+ };
+
+
+ // ====================================================================
+ // URL Helpers
+
+ /**
+ * History.getRootUrl()
+ * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
+ * @return {String} rootUrl
+ */
+ History.getRootUrl = function(){
+ // Create
+ var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
+ if ( document.location.port||false ) {
+ rootUrl += ':'+document.location.port;
+ }
+ rootUrl += '/';
+
+ // Return
+ return rootUrl;
+ };
+
+ /**
+ * History.getBaseHref()
+ * Fetches the `href` attribute of the ` ` element if it exists
+ * @return {String} baseHref
+ */
+ History.getBaseHref = function(){
+ // Create
+ var
+ baseElements = document.getElementsByTagName('base'),
+ baseElement = null,
+ baseHref = '';
+
+ // Test for Base Element
+ if ( baseElements.length === 1 ) {
+ // Prepare for Base Element
+ baseElement = baseElements[0];
+ baseHref = baseElement.href.replace(/[^\/]+$/,'');
+ }
+
+ // Adjust trailing slash
+ baseHref = baseHref.replace(/\/+$/,'');
+ if ( baseHref ) baseHref += '/';
+
+ // Return
+ return baseHref;
+ };
+
+ /**
+ * History.getBaseUrl()
+ * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
+ * @return {String} baseUrl
+ */
+ History.getBaseUrl = function(){
+ // Create
+ var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
+
+ // Return
+ return baseUrl;
+ };
+
+ /**
+ * History.getPageUrl()
+ * Fetches the URL of the current page
+ * @return {String} pageUrl
+ */
+ History.getPageUrl = function(){
+ // Fetch
+ var
+ State = History.getState(false,false),
+ stateUrl = (State||{}).url||History.getLocationHref(),
+ pageUrl;
+
+ // Create
+ pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/\./).test(part) ? part : part+'/';
+ });
+
+ // Return
+ return pageUrl;
+ };
+
+ /**
+ * History.getBasePageUrl()
+ * Fetches the Url of the directory of the current page
+ * @return {String} basePageUrl
+ */
+ History.getBasePageUrl = function(){
+ // Create
+ var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
+ return (/[^\/]$/).test(part) ? '' : part;
+ }).replace(/\/+$/,'')+'/';
+
+ // Return
+ return basePageUrl;
+ };
+
+ /**
+ * History.getFullUrl(url)
+ * Ensures that we have an absolute URL and not a relative URL
+ * @param {string} url
+ * @param {Boolean} allowBaseHref
+ * @return {string} fullUrl
+ */
+ History.getFullUrl = function(url,allowBaseHref){
+ // Prepare
+ var fullUrl = url, firstChar = url.substring(0,1);
+ allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
+
+ // Check
+ if ( /[a-z]+\:\/\//.test(url) ) {
+ // Full URL
+ }
+ else if ( firstChar === '/' ) {
+ // Root URL
+ fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
+ }
+ else if ( firstChar === '#' ) {
+ // Anchor URL
+ fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
+ }
+ else if ( firstChar === '?' ) {
+ // Query URL
+ fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
+ }
+ else {
+ // Relative URL
+ if ( allowBaseHref ) {
+ fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
+ } else {
+ fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
+ }
+ // We have an if condition above as we do not want hashes
+ // which are relative to the baseHref in our URLs
+ // as if the baseHref changes, then all our bookmarks
+ // would now point to different locations
+ // whereas the basePageUrl will always stay the same
+ }
+
+ // Return
+ return fullUrl.replace(/\#$/,'');
+ };
+
+ /**
+ * History.getShortUrl(url)
+ * Ensures that we have a relative URL and not a absolute URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getShortUrl = function(url){
+ // Prepare
+ var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
+
+ // Trim baseUrl
+ if ( History.emulated.pushState ) {
+ // We are in a if statement as when pushState is not emulated
+ // The actual url these short urls are relative to can change
+ // So within the same session, we the url may end up somewhere different
+ shortUrl = shortUrl.replace(baseUrl,'');
+ }
+
+ // Trim rootUrl
+ shortUrl = shortUrl.replace(rootUrl,'/');
+
+ // Ensure we can still detect it as a state
+ if ( History.isTraditionalAnchor(shortUrl) ) {
+ shortUrl = './'+shortUrl;
+ }
+
+ // Clean It
+ shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
+
+ // Return
+ return shortUrl;
+ };
+
+ /**
+ * History.getLocationHref(document)
+ * Returns a normalized version of document.location.href
+ * accounting for browser inconsistencies, etc.
+ *
+ * This URL will be URI-encoded and will include the hash
+ *
+ * @param {object} document
+ * @return {string} url
+ */
+ History.getLocationHref = function(doc) {
+ doc = doc || document;
+
+ // most of the time, this will be true
+ if (doc.URL === doc.location.href)
+ return doc.location.href;
+
+ // some versions of webkit URI-decode document.location.href
+ // but they leave document.URL in an encoded state
+ if (doc.location.href === decodeURIComponent(doc.URL))
+ return doc.URL;
+
+ // FF 3.6 only updates document.URL when a page is reloaded
+ // document.location.href is updated correctly
+ if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
+ return doc.location.href;
+
+ if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
+ return doc.location.href;
+
+ return doc.URL || doc.location.href;
+ };
+
+
+ // ====================================================================
+ // State Storage
+
+ /**
+ * History.store
+ * The store for all session specific data
+ */
+ History.store = {};
+
+ /**
+ * History.idToState
+ * 1-1: State ID to State Object
+ */
+ History.idToState = History.idToState||{};
+
+ /**
+ * History.stateToId
+ * 1-1: State String to State ID
+ */
+ History.stateToId = History.stateToId||{};
+
+ /**
+ * History.urlToId
+ * 1-1: State URL to State ID
+ */
+ History.urlToId = History.urlToId||{};
+
+ /**
+ * History.storedStates
+ * Store the states in an array
+ */
+ History.storedStates = History.storedStates||[];
+
+ /**
+ * History.savedStates
+ * Saved the states in an array
+ */
+ History.savedStates = History.savedStates||[];
+
+ /**
+ * History.noramlizeStore()
+ * Noramlize the store by adding necessary values
+ */
+ History.normalizeStore = function(){
+ History.store.idToState = History.store.idToState||{};
+ History.store.urlToId = History.store.urlToId||{};
+ History.store.stateToId = History.store.stateToId||{};
+ };
+
+ /**
+ * History.getState()
+ * Get an object containing the data, title and url of the current state
+ * @param {Boolean} friendly
+ * @param {Boolean} create
+ * @return {Object} State
+ */
+ History.getState = function(friendly,create){
+ // Prepare
+ if ( typeof friendly === 'undefined' ) { friendly = true; }
+ if ( typeof create === 'undefined' ) { create = true; }
+
+ // Fetch
+ var State = History.getLastSavedState();
+
+ // Create
+ if ( !State && create ) {
+ State = History.createStateObject();
+ }
+
+ // Adjust
+ if ( friendly ) {
+ State = History.cloneObject(State);
+ State.url = State.cleanUrl||State.url;
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByState(State)
+ * Gets a ID for a State
+ * @param {State} newState
+ * @return {String} id
+ */
+ History.getIdByState = function(newState){
+
+ // Fetch ID
+ var id = History.extractId(newState.url),
+ str;
+
+ if ( !id ) {
+ // Find ID via State String
+ str = History.getStateString(newState);
+ if ( typeof History.stateToId[str] !== 'undefined' ) {
+ id = History.stateToId[str];
+ }
+ else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
+ id = History.store.stateToId[str];
+ }
+ else {
+ // Generate a new ID
+ while ( true ) {
+ id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
+ if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
+ break;
+ }
+ }
+
+ // Apply the new State to the ID
+ History.stateToId[str] = id;
+ History.idToState[id] = newState;
+ }
+ }
+
+ // Return ID
+ return id;
+ };
+
+ /**
+ * History.normalizeState(State)
+ * Expands a State Object
+ * @param {object} State
+ * @return {object}
+ */
+ History.normalizeState = function(oldState){
+ // Variables
+ var newState, dataNotEmpty;
+
+ // Prepare
+ if ( !oldState || (typeof oldState !== 'object') ) {
+ oldState = {};
+ }
+
+ // Check
+ if ( typeof oldState.normalized !== 'undefined' ) {
+ return oldState;
+ }
+
+ // Adjust
+ if ( !oldState.data || (typeof oldState.data !== 'object') ) {
+ oldState.data = {};
+ }
+
+ // ----------------------------------------------------------------
+
+ // Create
+ newState = {};
+ newState.normalized = true;
+ newState.title = oldState.title||'';
+ newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
+ newState.hash = History.getShortUrl(newState.url);
+ newState.data = History.cloneObject(oldState.data);
+
+ // Fetch ID
+ newState.id = History.getIdByState(newState);
+
+ // ----------------------------------------------------------------
+
+ // Clean the URL
+ newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
+ newState.url = newState.cleanUrl;
+
+ // Check to see if we have more than just a url
+ dataNotEmpty = !History.isEmptyObject(newState.data);
+
+ // Apply
+ if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
+ // Add ID to Hash
+ newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
+ if ( !/\?/.test(newState.hash) ) {
+ newState.hash += '?';
+ }
+ newState.hash += '&_suid='+newState.id;
+ }
+
+ // Create the Hashed URL
+ newState.hashedUrl = History.getFullUrl(newState.hash);
+
+ // ----------------------------------------------------------------
+
+ // Update the URL if we have a duplicate
+ if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
+ newState.url = newState.hashedUrl;
+ }
+
+ // ----------------------------------------------------------------
+
+ // Return
+ return newState;
+ };
+
+ /**
+ * History.createStateObject(data,title,url)
+ * Creates a object based on the data, title and url state params
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {object}
+ */
+ History.createStateObject = function(data,title,url){
+ // Hashify
+ var State = {
+ 'data': data,
+ 'title': title,
+ 'url': url
+ };
+
+ // Expand the State
+ State = History.normalizeState(State);
+
+ // Return object
+ return State;
+ };
+
+ /**
+ * History.getStateById(id)
+ * Get a state by it's UID
+ * @param {String} id
+ */
+ History.getStateById = function(id){
+ // Prepare
+ id = String(id);
+
+ // Retrieve
+ var State = History.idToState[id] || History.store.idToState[id] || undefined;
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * Get a State's String
+ * @param {State} passedState
+ */
+ History.getStateString = function(passedState){
+ // Prepare
+ var State, cleanedState, str;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Clean
+ cleanedState = {
+ data: State.data,
+ title: passedState.title,
+ url: passedState.url
+ };
+
+ // Fetch
+ str = JSON.stringify(cleanedState);
+
+ // Return
+ return str;
+ };
+
+ /**
+ * Get a State's ID
+ * @param {State} passedState
+ * @return {String} id
+ */
+ History.getStateId = function(passedState){
+ // Prepare
+ var State, id;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Fetch
+ id = State.id;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getHashByState(State)
+ * Creates a Hash for the State Object
+ * @param {State} passedState
+ * @return {String} hash
+ */
+ History.getHashByState = function(passedState){
+ // Prepare
+ var State, hash;
+
+ // Fetch
+ State = History.normalizeState(passedState);
+
+ // Hash
+ hash = State.hash;
+
+ // Return
+ return hash;
+ };
+
+ /**
+ * History.extractId(url_or_hash)
+ * Get a State ID by it's URL or Hash
+ * @param {string} url_or_hash
+ * @return {string} id
+ */
+ History.extractId = function ( url_or_hash ) {
+ // Prepare
+ var id,parts,url, tmp;
+
+ // Extract
+
+ // If the URL has a #, use the id from before the #
+ if (url_or_hash.indexOf('#') != -1)
+ {
+ tmp = url_or_hash.split("#")[0];
+ }
+ else
+ {
+ tmp = url_or_hash;
+ }
+
+ parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
+ url = parts ? (parts[1]||url_or_hash) : url_or_hash;
+ id = parts ? String(parts[2]||'') : '';
+
+ // Return
+ return id||false;
+ };
+
+ /**
+ * History.isTraditionalAnchor
+ * Checks to see if the url is a traditional anchor or not
+ * @param {String} url_or_hash
+ * @return {Boolean}
+ */
+ History.isTraditionalAnchor = function(url_or_hash){
+ // Check
+ var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
+ // Return
+ return isTraditional;
+ };
+
+ /**
+ * History.extractState
+ * Get a State by it's URL or Hash
+ * @param {String} url_or_hash
+ * @return {State|null}
+ */
+ History.extractState = function(url_or_hash,create){
+ // Prepare
+ var State = null, id, url;
+ create = create||false;
+
+ // Fetch SUID
+ id = History.extractId(url_or_hash);
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Fetch SUID returned no State
+ if ( !State ) {
+ // Fetch URL
+ url = History.getFullUrl(url_or_hash);
+
+ // Check URL
+ id = History.getIdByUrl(url)||false;
+ if ( id ) {
+ State = History.getStateById(id);
+ }
+
+ // Create State
+ if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
+ State = History.createStateObject(null,null,url);
+ }
+ }
+
+ // Return
+ return State;
+ };
+
+ /**
+ * History.getIdByUrl()
+ * Get a State ID by a State URL
+ */
+ History.getIdByUrl = function(url){
+ // Fetch
+ var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
+
+ // Return
+ return id;
+ };
+
+ /**
+ * History.getLastSavedState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastSavedState = function(){
+ return History.savedStates[History.savedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.getLastStoredState()
+ * Get an object containing the data, title and url of the current state
+ * @return {Object} State
+ */
+ History.getLastStoredState = function(){
+ return History.storedStates[History.storedStates.length-1]||undefined;
+ };
+
+ /**
+ * History.hasUrlDuplicate
+ * Checks if a Url will have a url conflict
+ * @param {Object} newState
+ * @return {Boolean} hasDuplicate
+ */
+ History.hasUrlDuplicate = function(newState) {
+ // Prepare
+ var hasDuplicate = false,
+ oldState;
+
+ // Fetch
+ oldState = History.extractState(newState.url);
+
+ // Check
+ hasDuplicate = oldState && oldState.id !== newState.id;
+
+ // Return
+ return hasDuplicate;
+ };
+
+ /**
+ * History.storeState
+ * Store a State
+ * @param {Object} newState
+ * @return {Object} newState
+ */
+ History.storeState = function(newState){
+ // Store the State
+ History.urlToId[newState.url] = newState.id;
+
+ // Push the State
+ History.storedStates.push(History.cloneObject(newState));
+
+ // Return newState
+ return newState;
+ };
+
+ /**
+ * History.isLastSavedState(newState)
+ * Tests to see if the state is the last state
+ * @param {Object} newState
+ * @return {boolean} isLast
+ */
+ History.isLastSavedState = function(newState){
+ // Prepare
+ var isLast = false,
+ newId, oldState, oldId;
+
+ // Check
+ if ( History.savedStates.length ) {
+ newId = newState.id;
+ oldState = History.getLastSavedState();
+ oldId = oldState.id;
+
+ // Check
+ isLast = (newId === oldId);
+ }
+
+ // Return
+ return isLast;
+ };
+
+ /**
+ * History.saveState
+ * Push a State
+ * @param {Object} newState
+ * @return {boolean} changed
+ */
+ History.saveState = function(newState){
+ // Check Hash
+ if ( History.isLastSavedState(newState) ) {
+ return false;
+ }
+
+ // Push the State
+ History.savedStates.push(History.cloneObject(newState));
+
+ // Return true
+ return true;
+ };
+
+ /**
+ * History.getStateByIndex()
+ * Gets a state by the index
+ * @param {integer} index
+ * @return {Object}
+ */
+ History.getStateByIndex = function(index){
+ // Prepare
+ var State = null;
+
+ // Handle
+ if ( typeof index === 'undefined' ) {
+ // Get the last inserted
+ State = History.savedStates[History.savedStates.length-1];
+ }
+ else if ( index < 0 ) {
+ // Get from the end
+ State = History.savedStates[History.savedStates.length+index];
+ }
+ else {
+ // Get from the beginning
+ State = History.savedStates[index];
+ }
+
+ // Return State
+ return State;
+ };
+
+ /**
+ * History.getCurrentIndex()
+ * Gets the current index
+ * @return (integer)
+ */
+ History.getCurrentIndex = function(){
+ // Prepare
+ var index = null;
+
+ // No states saved
+ if(History.savedStates.length < 1) {
+ index = 0;
+ }
+ else {
+ index = History.savedStates.length-1;
+ }
+ return index;
+ };
+
+ // ====================================================================
+ // Hash Helpers
+
+ /**
+ * History.getHash()
+ * @param {Location=} location
+ * Gets the current document hash
+ * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
+ * @return {string}
+ */
+ History.getHash = function(doc){
+ var url = History.getLocationHref(doc),
+ hash;
+ hash = History.getHashByUrl(url);
+ return hash;
+ };
+
+ /**
+ * History.unescapeHash()
+ * normalize and Unescape a Hash
+ * @param {String} hash
+ * @return {string}
+ */
+ History.unescapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Unescape hash
+ result = decodeURIComponent(result);
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.normalizeHash()
+ * normalize a hash across browsers
+ * @return {string}
+ */
+ History.normalizeHash = function(hash){
+ // Prepare
+ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.setHash(hash)
+ * Sets the document hash
+ * @param {string} hash
+ * @return {History}
+ */
+ History.setHash = function(hash,queue){
+ // Prepare
+ var State, pageUrl;
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.setHash: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.setHash,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Log
+ //History.debug('History.setHash: called',hash);
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Check if hash is a state
+ State = History.extractState(hash,true);
+ if ( State && !History.emulated.pushState ) {
+ // Hash is a state so skip the setHash
+ //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
+
+ // PushState
+ History.pushState(State.data,State.title,State.url,false);
+ }
+ else if ( History.getHash() !== hash ) {
+ // Hash is a proper hash, so apply it
+
+ // Handle browser bugs
+ if ( History.bugs.setHash ) {
+ // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
+
+ // Fetch the base page
+ pageUrl = History.getPageUrl();
+
+ // Safari hash apply
+ History.pushState(null,null,pageUrl+'#'+hash,false);
+ }
+ else {
+ // Normal hash apply
+ document.location.hash = hash;
+ }
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.escape()
+ * normalize and Escape a Hash
+ * @return {string}
+ */
+ History.escapeHash = function(hash){
+ // Prepare
+ var result = History.normalizeHash(hash);
+
+ // Escape hash
+ result = window.encodeURIComponent(result);
+
+ // IE6 Escape Bug
+ if ( !History.bugs.hashEscape ) {
+ // Restore common parts
+ result = result
+ .replace(/\%21/g,'!')
+ .replace(/\%26/g,'&')
+ .replace(/\%3D/g,'=')
+ .replace(/\%3F/g,'?');
+ }
+
+ // Return result
+ return result;
+ };
+
+ /**
+ * History.getHashByUrl(url)
+ * Extracts the Hash from a URL
+ * @param {string} url
+ * @return {string} url
+ */
+ History.getHashByUrl = function(url){
+ // Extract the hash
+ var hash = String(url)
+ .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
+ ;
+
+ // Unescape hash
+ hash = History.unescapeHash(hash);
+
+ // Return hash
+ return hash;
+ };
+
+ /**
+ * History.setTitle(title)
+ * Applies the title to the document
+ * @param {State} newState
+ * @return {Boolean}
+ */
+ History.setTitle = function(newState){
+ // Prepare
+ var title = newState.title,
+ firstState;
+
+ // Initial
+ if ( !title ) {
+ firstState = History.getStateByIndex(0);
+ if ( firstState && firstState.url === newState.url ) {
+ title = firstState.title||History.options.initialTitle;
+ }
+ }
+
+ // Apply
+ try {
+ document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
+ }
+ catch ( Exception ) { }
+ document.title = title;
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Queueing
+
+ /**
+ * History.queues
+ * The list of queues to use
+ * First In, First Out
+ */
+ History.queues = [];
+
+ /**
+ * History.busy(value)
+ * @param {boolean} value [optional]
+ * @return {boolean} busy
+ */
+ History.busy = function(value){
+ // Apply
+ if ( typeof value !== 'undefined' ) {
+ //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
+ History.busy.flag = value;
+ }
+ // Default
+ else if ( typeof History.busy.flag === 'undefined' ) {
+ History.busy.flag = false;
+ }
+
+ // Queue
+ if ( !History.busy.flag ) {
+ // Execute the next item in the queue
+ clearTimeout(History.busy.timeout);
+ var fireNext = function(){
+ var i, queue, item;
+ if ( History.busy.flag ) return;
+ for ( i=History.queues.length-1; i >= 0; --i ) {
+ queue = History.queues[i];
+ if ( queue.length === 0 ) continue;
+ item = queue.shift();
+ History.fireQueueItem(item);
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+ };
+ History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
+ }
+
+ // Return
+ return History.busy.flag;
+ };
+
+ /**
+ * History.busy.flag
+ */
+ History.busy.flag = false;
+
+ /**
+ * History.fireQueueItem(item)
+ * Fire a Queue Item
+ * @param {Object} item
+ * @return {Mixed} result
+ */
+ History.fireQueueItem = function(item){
+ return item.callback.apply(item.scope||History,item.args||[]);
+ };
+
+ /**
+ * History.pushQueue(callback,args)
+ * Add an item to the queue
+ * @param {Object} item [scope,callback,args,queue]
+ */
+ History.pushQueue = function(item){
+ // Prepare the queue
+ History.queues[item.queue||0] = History.queues[item.queue||0]||[];
+
+ // Add to the queue
+ History.queues[item.queue||0].push(item);
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.queue (item,queue), (func,queue), (func), (item)
+ * Either firs the item now if not busy, or adds it to the queue
+ */
+ History.queue = function(item,queue){
+ // Prepare
+ if ( typeof item === 'function' ) {
+ item = {
+ callback: item
+ };
+ }
+ if ( typeof queue !== 'undefined' ) {
+ item.queue = queue;
+ }
+
+ // Handle
+ if ( History.busy() ) {
+ History.pushQueue(item);
+ } else {
+ History.fireQueueItem(item);
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.clearQueue()
+ * Clears the Queue
+ */
+ History.clearQueue = function(){
+ History.busy.flag = false;
+ History.queues = [];
+ return History;
+ };
+
+
+ // ====================================================================
+ // IE Bug Fix
+
+ /**
+ * History.stateChanged
+ * States whether or not the state has changed since the last double check was initialised
+ */
+ History.stateChanged = false;
+
+ /**
+ * History.doubleChecker
+ * Contains the timeout used for the double checks
+ */
+ History.doubleChecker = false;
+
+ /**
+ * History.doubleCheckComplete()
+ * Complete a double check
+ * @return {History}
+ */
+ History.doubleCheckComplete = function(){
+ // Update
+ History.stateChanged = true;
+
+ // Clear
+ History.doubleCheckClear();
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheckClear()
+ * Clear a double check
+ * @return {History}
+ */
+ History.doubleCheckClear = function(){
+ // Clear
+ if ( History.doubleChecker ) {
+ clearTimeout(History.doubleChecker);
+ History.doubleChecker = false;
+ }
+
+ // Chain
+ return History;
+ };
+
+ /**
+ * History.doubleCheck()
+ * Create a double check
+ * @return {History}
+ */
+ History.doubleCheck = function(tryAgain){
+ // Reset
+ History.stateChanged = false;
+ History.doubleCheckClear();
+
+ // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
+ // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
+ if ( History.bugs.ieDoubleCheck ) {
+ // Apply Check
+ History.doubleChecker = setTimeout(
+ function(){
+ History.doubleCheckClear();
+ if ( !History.stateChanged ) {
+ //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
+ // Re-Attempt
+ tryAgain();
+ }
+ return true;
+ },
+ History.options.doubleCheckInterval
+ );
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // Safari Bug Fix
+
+ /**
+ * History.safariStatePoll()
+ * Poll the current state
+ * @return {History}
+ */
+ History.safariStatePoll = function(){
+ // Poll the URL
+
+ // Get the Last State which has the new URL
+ var
+ urlState = History.extractState(History.getLocationHref()),
+ newState;
+
+ // Check for a difference
+ if ( !History.isLastSavedState(urlState) ) {
+ newState = urlState;
+ }
+ else {
+ return;
+ }
+
+ // Check if we have a state with that url
+ // If not create it
+ if ( !newState ) {
+ //History.debug('History.safariStatePoll: new');
+ newState = History.createStateObject();
+ }
+
+ // Apply the New State
+ //History.debug('History.safariStatePoll: trigger');
+ History.Adapter.trigger(window,'popstate');
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // State Aliases
+
+ /**
+ * History.back(queue)
+ * Send the browser history back one item
+ * @param {Integer} queue [optional]
+ */
+ History.back = function(queue){
+ //History.debug('History.back: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.back: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.back,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.back(false);
+ });
+
+ // Go back
+ history.go(-1);
+
+ // End back closure
+ return true;
+ };
+
+ /**
+ * History.forward(queue)
+ * Send the browser history forward one item
+ * @param {Integer} queue [optional]
+ */
+ History.forward = function(queue){
+ //History.debug('History.forward: called', arguments);
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.forward: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.forward,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Fix certain browser bugs that prevent the state from changing
+ History.doubleCheck(function(){
+ History.forward(false);
+ });
+
+ // Go forward
+ history.go(1);
+
+ // End forward closure
+ return true;
+ };
+
+ /**
+ * History.go(index,queue)
+ * Send the browser history back or forward index times
+ * @param {Integer} queue [optional]
+ */
+ History.go = function(index,queue){
+ //History.debug('History.go: called', arguments);
+
+ // Prepare
+ var i;
+
+ // Handle
+ if ( index > 0 ) {
+ // Forward
+ for ( i=1; i<=index; ++i ) {
+ History.forward(queue);
+ }
+ }
+ else if ( index < 0 ) {
+ // Backward
+ for ( i=-1; i>=index; --i ) {
+ History.back(queue);
+ }
+ }
+ else {
+ throw new Error('History.go: History.go requires a positive or negative integer passed.');
+ }
+
+ // Chain
+ return History;
+ };
+
+
+ // ====================================================================
+ // HTML5 State Support
+
+ // Non-Native pushState Implementation
+ if ( History.emulated.pushState ) {
+ /*
+ * Provide Skeleton for HTML4 Browsers
+ */
+
+ // Prepare
+ var emptyFunction = function(){};
+ History.pushState = History.pushState||emptyFunction;
+ History.replaceState = History.replaceState||emptyFunction;
+ } // History.emulated.pushState
+
+ // Native pushState Implementation
+ else {
+ /*
+ * Use native HTML5 History API Implementation
+ */
+
+ /**
+ * History.onPopState(event,extra)
+ * Refresh the Current State
+ */
+ History.onPopState = function(event,extra){
+ // Prepare
+ var stateId = false, newState = false, currentHash, currentState;
+
+ // Reset the double check
+ History.doubleCheckComplete();
+
+ // Check for a Hash, and handle apporiatly
+ currentHash = History.getHash();
+ if ( currentHash ) {
+ // Expand Hash
+ currentState = History.extractState(currentHash||History.getLocationHref(),true);
+ if ( currentState ) {
+ // We were able to parse it, it must be a State!
+ // Let's forward to replaceState
+ //History.debug('History.onPopState: state anchor', currentHash, currentState);
+ History.replaceState(currentState.data, currentState.title, currentState.url, false);
+ }
+ else {
+ // Traditional Anchor
+ //History.debug('History.onPopState: traditional anchor', currentHash);
+ History.Adapter.trigger(window,'anchorchange');
+ History.busy(false);
+ }
+
+ // We don't care for hashes
+ History.expectedStateId = false;
+ return false;
+ }
+
+ // Ensure
+ stateId = History.Adapter.extractEventData('state',event,extra) || false;
+
+ // Fetch State
+ if ( stateId ) {
+ // Vanilla: Back/forward button was used
+ newState = History.getStateById(stateId);
+ }
+ else if ( History.expectedStateId ) {
+ // Vanilla: A new state was pushed, and popstate was called manually
+ newState = History.getStateById(History.expectedStateId);
+ }
+ else {
+ // Initial State
+ newState = History.extractState(History.getLocationHref());
+ }
+
+ // The State did not exist in our store
+ if ( !newState ) {
+ // Regenerate the State
+ newState = History.createStateObject(null,null,History.getLocationHref());
+ }
+
+ // Clean
+ History.expectedStateId = false;
+
+ // Check if we are the same state
+ if ( History.isLastSavedState(newState) ) {
+ // There has been no change (just the page's hash has finally propagated)
+ //History.debug('History.onPopState: no change', newState, History.savedStates);
+ History.busy(false);
+ return false;
+ }
+
+ // Store the State
+ History.storeState(newState);
+ History.saveState(newState);
+
+ // Force update of the title
+ History.setTitle(newState);
+
+ // Fire Our Event
+ History.Adapter.trigger(window,'statechange');
+ History.busy(false);
+
+ // Return true
+ return true;
+ };
+ History.Adapter.bind(window,'popstate',History.onPopState);
+
+ /**
+ * History.pushState(data,title,url)
+ * Add a new State to the history object, become it, and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.pushState = function(data,title,url,queue){
+ //History.debug('History.pushState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.pushState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.pushState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.pushState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End pushState closure
+ return true;
+ };
+
+ /**
+ * History.replaceState(data,title,url)
+ * Replace the State and trigger onpopstate
+ * We have to trigger for HTML4 compatibility
+ * @param {object} data
+ * @param {string} title
+ * @param {string} url
+ * @return {true}
+ */
+ History.replaceState = function(data,title,url,queue){
+ //History.debug('History.replaceState: called', arguments);
+
+ // Check the State
+ if ( History.getHashByUrl(url) && History.emulated.pushState ) {
+ throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
+ }
+
+ // Handle Queueing
+ if ( queue !== false && History.busy() ) {
+ // Wait + Push to Queue
+ //History.debug('History.replaceState: we must wait', arguments);
+ History.pushQueue({
+ scope: History,
+ callback: History.replaceState,
+ args: arguments,
+ queue: queue
+ });
+ return false;
+ }
+
+ // Make Busy + Continue
+ History.busy(true);
+
+ // Create the newState
+ var newState = History.createStateObject(data,title,url);
+
+ // Check it
+ if ( History.isLastSavedState(newState) ) {
+ // Won't be a change
+ History.busy(false);
+ }
+ else {
+ // Store the newState
+ History.storeState(newState);
+ History.expectedStateId = newState.id;
+
+ // Push the newState
+ history.replaceState(newState.id,newState.title,newState.url);
+
+ // Fire HTML5 Event
+ History.Adapter.trigger(window,'popstate');
+ }
+
+ // End replaceState closure
+ return true;
+ };
+
+ } // !History.emulated.pushState
+
+
+ // ====================================================================
+ // Initialise
+
+ /**
+ * Load the Store
+ */
+ if ( sessionStorage ) {
+ // Fetch
+ try {
+ History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ History.store = {};
+ }
+
+ // Normalize
+ History.normalizeStore();
+ }
+ else {
+ // Default Load
+ History.store = {};
+ History.normalizeStore();
+ }
+
+ /**
+ * Clear Intervals on exit to prevent memory leaks
+ */
+ History.Adapter.bind(window,"unload",History.clearAllIntervals);
+
+ /**
+ * Create the initial State
+ */
+ History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
+
+ /**
+ * Bind for Saving Store
+ */
+ if ( sessionStorage ) {
+ // When the page is closed
+ History.onUnload = function(){
+ // Prepare
+ var currentStore, item, currentStoreString;
+
+ // Fetch
+ try {
+ currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
+ }
+ catch ( err ) {
+ currentStore = {};
+ }
+
+ // Ensure
+ currentStore.idToState = currentStore.idToState || {};
+ currentStore.urlToId = currentStore.urlToId || {};
+ currentStore.stateToId = currentStore.stateToId || {};
+
+ // Sync
+ for ( item in History.idToState ) {
+ if ( !History.idToState.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.idToState[item] = History.idToState[item];
+ }
+ for ( item in History.urlToId ) {
+ if ( !History.urlToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.urlToId[item] = History.urlToId[item];
+ }
+ for ( item in History.stateToId ) {
+ if ( !History.stateToId.hasOwnProperty(item) ) {
+ continue;
+ }
+ currentStore.stateToId[item] = History.stateToId[item];
+ }
+
+ // Update
+ History.store = currentStore;
+ History.normalizeStore();
+
+ // In Safari, going into Private Browsing mode causes the
+ // Session Storage object to still exist but if you try and use
+ // or set any property/function of it it throws the exception
+ // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
+ // add something to storage that exceeded the quota." infinitely
+ // every second.
+ currentStoreString = JSON.stringify(currentStore);
+ try {
+ // Store
+ sessionStorage.setItem('History.store', currentStoreString);
+ }
+ catch (e) {
+ if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
+ if (sessionStorage.length) {
+ // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
+ // removing/resetting the storage can work.
+ sessionStorage.removeItem('History.store');
+ sessionStorage.setItem('History.store', currentStoreString);
+ } else {
+ // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
+ }
+ } else {
+ throw e;
+ }
+ }
+ };
+
+ // For Internet Explorer
+ History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
+
+ // For Other Browsers
+ History.Adapter.bind(window,'beforeunload',History.onUnload);
+ History.Adapter.bind(window,'unload',History.onUnload);
+
+ // Both are enabled for consistency
+ }
+
+ // Non-Native pushState Implementation
+ if ( !History.emulated.pushState ) {
+ // Be aware, the following is only for native pushState implementations
+ // If you are wanting to include something for all browsers
+ // Then include it above this if block
+
+ /**
+ * Setup Safari Fix
+ */
+ if ( History.bugs.safariPoll ) {
+ History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
+ }
+
+ /**
+ * Ensure Cross Browser Compatibility
+ */
+ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
+ /**
+ * Fix Safari HashChange Issue
+ */
+
+ // Setup Alias
+ History.Adapter.bind(window,'hashchange',function(){
+ History.Adapter.trigger(window,'popstate');
+ });
+
+ // Initialise Alias
+ if ( History.getHash() ) {
+ History.Adapter.onDomLoad(function(){
+ History.Adapter.trigger(window,'hashchange');
+ });
+ }
+ }
+
+ } // !History.emulated.pushState
+
+
+ }; // History.initCore
+
+ // Try to Initialise History
+ if (!History.options || !History.options.delayInit) {
+ History.init();
+ }
+
+})(window);
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/json2.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/json2.js
new file mode 100644
index 00000000..9317ae8b
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/scripts/uncompressed/json2.js
@@ -0,0 +1,486 @@
+/*
+ json2.js
+ 2012-10-08
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ See http://www.JSON.org/js.html
+
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
+ This file creates a global JSON object containing two methods: stringify
+ and parse.
+
+ JSON.stringify(value, replacer, space)
+ value any JavaScript value, usually an object or array.
+
+ replacer an optional parameter that determines how object
+ values are stringified for objects. It can be a
+ function or an array of strings.
+
+ space an optional parameter that specifies the indentation
+ of nested structures. If it is omitted, the text will
+ be packed without extra whitespace. If it is a number,
+ it will specify the number of spaces to indent at each
+ level. If it is a string (such as '\t' or ' '),
+ it contains the characters used to indent at each level.
+
+ This method produces a JSON text from a JavaScript value.
+
+ When an object value is found, if the object contains a toJSON
+ method, its toJSON method will be called and the result will be
+ stringified. A toJSON method does not serialize: it returns the
+ value represented by the name/value pair that should be serialized,
+ or undefined if nothing should be serialized. The toJSON method
+ will be passed the key associated with the value, and this will be
+ bound to the value
+
+ For example, this would serialize Dates as ISO strings.
+
+ Date.prototype.toJSON = function (key) {
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ return this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z';
+ };
+
+ You can provide an optional replacer method. It will be passed the
+ key and value of each member, with this bound to the containing
+ object. The value that is returned from your method will be
+ serialized. If your method returns undefined, then the member will
+ be excluded from the serialization.
+
+ If the replacer parameter is an array of strings, then it will be
+ used to select the members to be serialized. It filters the results
+ such that only members with keys listed in the replacer array are
+ stringified.
+
+ Values that do not have JSON representations, such as undefined or
+ functions, will not be serialized. Such values in objects will be
+ dropped; in arrays they will be replaced with null. You can use
+ a replacer function to replace those with JSON values.
+ JSON.stringify(undefined) returns undefined.
+
+ The optional space parameter produces a stringification of the
+ value that is filled with line breaks and indentation to make it
+ easier to read.
+
+ If the space parameter is a non-empty string, then that string will
+ be used for indentation. If the space parameter is a number, then
+ the indentation will be that many spaces.
+
+ Example:
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
+ // text is '["e",{"pluribus":"unum"}]'
+
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+ text = JSON.stringify([new Date()], function (key, value) {
+ return this[key] instanceof Date ?
+ 'Date(' + this[key] + ')' : value;
+ });
+ // text is '["Date(---current time---)"]'
+
+
+ JSON.parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = JSON.parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
+ }
+ }
+ return value;
+ });
+
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+ var d;
+ if (typeof value === 'string' &&
+ value.slice(0, 5) === 'Date(' &&
+ value.slice(-1) === ')') {
+ d = new Date(value.slice(5, -1));
+ if (d) {
+ return d;
+ }
+ }
+ return value;
+ });
+
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+*/
+
+/*jslint evil: true, regexp: true */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
+ test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.
+
+if (typeof JSON !== 'object') {
+ JSON = {};
+}
+
+(function () {
+ 'use strict';
+
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ if (typeof Date.prototype.toJSON !== 'function') {
+
+ Date.prototype.toJSON = function (key) {
+
+ return isFinite(this.valueOf())
+ ? this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z'
+ : null;
+ };
+
+ String.prototype.toJSON =
+ Number.prototype.toJSON =
+ Boolean.prototype.toJSON = function (key) {
+ return this.valueOf();
+ };
+ }
+
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+ gap,
+ indent,
+ meta = { // table of character substitutions
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ rep;
+
+
+ function quote(string) {
+
+// If the string contains no control characters, no quote characters, and no
+// backslash characters, then we can safely slap some quotes around it.
+// Otherwise we must also replace the offending characters with safe escape
+// sequences.
+
+ escapable.lastIndex = 0;
+ return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
+ var c = meta[a];
+ return typeof c === 'string'
+ ? c
+ : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"' : '"' + string + '"';
+ }
+
+
+ function str(key, holder) {
+
+// Produce a string from holder[key].
+
+ var i, // The loop counter.
+ k, // The member key.
+ v, // The member value.
+ length,
+ mind = gap,
+ partial,
+ value = holder[key];
+
+// If the value has a toJSON method, call it to obtain a replacement value.
+
+ if (value && typeof value === 'object' &&
+ typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+
+// If we were called with a replacer function, then call the replacer to
+// obtain a replacement value.
+
+ if (typeof rep === 'function') {
+ value = rep.call(holder, key, value);
+ }
+
+// What happens next depends on the value's type.
+
+ switch (typeof value) {
+ case 'string':
+ return quote(value);
+
+ case 'number':
+
+// JSON numbers must be finite. Encode non-finite numbers as null.
+
+ return isFinite(value) ? String(value) : 'null';
+
+ case 'boolean':
+ case 'null':
+
+// If the value is a boolean or null, convert it to a string. Note:
+// typeof null does not produce 'null'. The case is included here in
+// the remote chance that this gets fixed someday.
+
+ return String(value);
+
+// If the type is 'object', we might be dealing with an object or an array or
+// null.
+
+ case 'object':
+
+// Due to a specification blunder in ECMAScript, typeof null is 'object',
+// so watch out for that case.
+
+ if (!value) {
+ return 'null';
+ }
+
+// Make an array to hold the partial results of stringifying this object value.
+
+ gap += indent;
+ partial = [];
+
+// Is the value an array?
+
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
+
+// The value is an array. Stringify every element. Use null as a placeholder
+// for non-JSON values.
+
+ length = value.length;
+ for (i = 0; i < length; i += 1) {
+ partial[i] = str(i, value) || 'null';
+ }
+
+// Join all of the elements together, separated with commas, and wrap them in
+// brackets.
+
+ v = partial.length === 0
+ ? '[]'
+ : gap
+ ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
+ : '[' + partial.join(',') + ']';
+ gap = mind;
+ return v;
+ }
+
+// If the replacer is an array, use it to select the members to be stringified.
+
+ if (rep && typeof rep === 'object') {
+ length = rep.length;
+ for (i = 0; i < length; i += 1) {
+ if (typeof rep[i] === 'string') {
+ k = rep[i];
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ } else {
+
+// Otherwise, iterate through all of the keys in the object.
+
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = str(k, value);
+ if (v) {
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
+ }
+ }
+ }
+ }
+
+// Join all of the member texts together, separated with commas,
+// and wrap them in braces.
+
+ v = partial.length === 0
+ ? '{}'
+ : gap
+ ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
+ : '{' + partial.join(',') + '}';
+ gap = mind;
+ return v;
+ }
+ }
+
+// If the JSON object does not yet have a stringify method, give it one.
+
+ if (typeof JSON.stringify !== 'function') {
+ JSON.stringify = function (value, replacer, space) {
+
+// The stringify method takes a value and an optional replacer, and an optional
+// space parameter, and returns a JSON text. The replacer can be a function
+// that can replace values, or an array of strings that will select the keys.
+// A default replacer method can be provided. Use of the space parameter can
+// produce text that is more easily readable.
+
+ var i;
+ gap = '';
+ indent = '';
+
+// If the space parameter is a number, make an indent string containing that
+// many spaces.
+
+ if (typeof space === 'number') {
+ for (i = 0; i < space; i += 1) {
+ indent += ' ';
+ }
+
+// If the space parameter is a string, it will be used as the indent string.
+
+ } else if (typeof space === 'string') {
+ indent = space;
+ }
+
+// If there is a replacer, it must be a function or an array.
+// Otherwise, throw an error.
+
+ rep = replacer;
+ if (replacer && typeof replacer !== 'function' &&
+ (typeof replacer !== 'object' ||
+ typeof replacer.length !== 'number')) {
+ throw new Error('JSON.stringify');
+ }
+
+// Make a fake root object containing our value under the key of ''.
+// Return the result of stringifying the value.
+
+ return str('', {'': value});
+ };
+ }
+
+
+// If the JSON object does not yet have a parse method, give it one.
+
+ if (typeof JSON.parse !== 'function') {
+ JSON.parse = function (text, reviver) {
+
+// The parse method takes a text and an optional reviver function, and returns
+// a JavaScript value if the text is a valid JSON text.
+
+ var j;
+
+ function walk(holder, key) {
+
+// The walk method is used to recursively walk the resulting structure so
+// that modifications can be made.
+
+ var k, v, value = holder[key];
+ if (value && typeof value === 'object') {
+ for (k in value) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
+ v = walk(value, k);
+ if (v !== undefined) {
+ value[k] = v;
+ } else {
+ delete value[k];
+ }
+ }
+ }
+ }
+ return reviver.call(holder, key, value);
+ }
+
+
+// Parsing happens in four stages. In the first stage, we replace certain
+// Unicode characters with escape sequences. JavaScript handles many characters
+// incorrectly, either silently deleting them, or treating them as line endings.
+
+ text = String(text);
+ cx.lastIndex = 0;
+ if (cx.test(text)) {
+ text = text.replace(cx, function (a) {
+ return '\\u' +
+ ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ });
+ }
+
+// In the second stage, we run the text against regular expressions that look
+// for non-JSON patterns. We are especially concerned with '()' and 'new'
+// because they can cause invocation, and '=' because it can cause mutation.
+// But just to be safe, we want to reject all unexpected forms.
+
+// We split the second stage into 4 regexp operations in order to work around
+// crippling inefficiencies in IE's and Safari's regexp engines. First we
+// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
+// replace all simple value tokens with ']' characters. Third, we delete all
+// open brackets that follow a colon or comma or that begin the text. Finally,
+// we look to see that the remaining characters are only whitespace or ']' or
+// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
+
+ if (/^[\],:{}\s]*$/
+ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
+
+// In the third stage we use the eval function to compile the text into a
+// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
+// in JavaScript: it can begin a block or an object literal. We wrap the text
+// in parens to eliminate the ambiguity.
+
+ j = eval('(' + text + ')');
+
+// In the optional fourth stage, we recursively walk the new structure, passing
+// each name/value pair to a reviver function for possible transformation.
+
+ return typeof reviver === 'function'
+ ? walk({'': j}, '')
+ : j;
+ }
+
+// If the text is not JSON parseable, then a SyntaxError is thrown.
+
+ throw new SyntaxError('JSON.parse');
+ };
+ }
+}());
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests.src/_header.php b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests.src/_header.php
new file mode 100644
index 00000000..9b085101
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests.src/_header.php
@@ -0,0 +1,22 @@
+
+
+
+ History.js Test Suite
+
+
+
+ History.js Test Suite
+ HTML5 Browsers must pass the HTML4+HTML5 tests
+ HTML4 Browsers must pass the HTML4 tests and should fail the HTML5 tests
+ ';
+ foreach ( $adapters as $adapter ) :
+ echo '';
+ # Url
+ $url = "${browser}.${adapter}.html";
+
+ # Title
+ $Browser = ucwords($browser);
+ $Adapter = ucwords($adapter);
+ $title = "History.js ${Browser} ${Adapter} Test Suite";
+
+ # Render
+ ?>
=$title?> ';
+ endforeach;
+ echo '
';
+ endforeach;
+ ?>
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests.src/each.php b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests.src/each.php
new file mode 100644
index 00000000..22f7b683
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests.src/each.php
@@ -0,0 +1,51 @@
+
+
+
+
+
+
+
+ =$title?>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests.src/index.php b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests.src/index.php
new file mode 100644
index 00000000..44495d3e
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests.src/index.php
@@ -0,0 +1,23 @@
+Tests
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/.htaccess b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/.htaccess
new file mode 100644
index 00000000..2f7dbdde
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/.htaccess
@@ -0,0 +1,13 @@
+Options +FollowSymlinks
+RewriteEngine On
+
+# Clean Adapter
+RewriteCond %{REQUEST_FILENAME} !-f
+RewriteCond %{REQUEST_FILENAME} !-d
+RewriteRule ([^\.]+)$ $1.html [NC,L,QSA]
+
+# Can someone smarter than me make it so:
+# http://localhost/history.js/tests/uncompressed-html5-persistant-jquery
+# Does not redirect to:
+# http://localhost/history.js/tests/uncompressed-html5-persistant-jquery.html
+# But still accesses that url
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.dojo.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.dojo.html
new file mode 100644
index 00000000..af5f4d8b
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.dojo.html
@@ -0,0 +1,55 @@
+
+
+
+
+
+
+
+ History.js HTML4+HTML5 Dojo Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.extjs.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.extjs.html
new file mode 100644
index 00000000..e82577a8
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.extjs.html
@@ -0,0 +1,55 @@
+
+
+
+
+
+
+
+ History.js HTML4+HTML5 ExtJS Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.jquery.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.jquery.html
new file mode 100644
index 00000000..a99b9569
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.jquery.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+ History.js HTML4+HTML5 Jquery Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.mootools.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.mootools.html
new file mode 100644
index 00000000..792f9752
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.mootools.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+ History.js HTML4+HTML5 Mootools Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.native.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.native.html
new file mode 100644
index 00000000..c4fd8522
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.native.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+ History.js HTML4+HTML5 Native Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.right.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.right.html
new file mode 100644
index 00000000..ae4fb036
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.right.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+ History.js HTML4+HTML5 Right Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.zepto.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.zepto.html
new file mode 100644
index 00000000..71a6b7c9
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html4+html5.zepto.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+ History.js HTML4+HTML5 Zepto Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.dojo.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.dojo.html
new file mode 100644
index 00000000..3e222753
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.dojo.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+ History.js HTML5 Dojo Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.extjs.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.extjs.html
new file mode 100644
index 00000000..2446b72c
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.extjs.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+ History.js HTML5 ExtJS Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.jquery.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.jquery.html
new file mode 100644
index 00000000..977b8fed
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.jquery.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+ History.js HTML5 Jquery Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.mootools.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.mootools.html
new file mode 100644
index 00000000..30ee7892
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.mootools.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+ History.js HTML5 Mootools Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.native.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.native.html
new file mode 100644
index 00000000..8ffc4c34
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.native.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+ History.js HTML5 Native Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.right.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.right.html
new file mode 100644
index 00000000..7a2c08b5
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.right.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+ History.js HTML5 Right Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.zepto.html b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.zepto.html
new file mode 100644
index 00000000..d6657091
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/html5.zepto.html
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+ History.js HTML5 Zepto Test Suite
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ test markup
+ back forward
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/image.php b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/image.php
new file mode 100644
index 00000000..5e7bfc9e
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/image.php
@@ -0,0 +1,3 @@
+
+
+
+ History.js Test Suite
+
+
+
+ History.js Test Suite
+ HTML5 Browsers must pass the HTML4+HTML5 tests, HTML4 Browsers must pass the HTML4 tests and should fail the HTML5 tests.
+
+
+
HTML 4+5
+
+
+
+
+
+
+
+
+
+
+
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/tests.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/tests.js
new file mode 100644
index 00000000..9dfc7382
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/tests/tests.js
@@ -0,0 +1,254 @@
+(function(){
+
+var
+ History = window.History,
+ document = window.document,
+ test = window.test,
+ deepEqual = window.deepEqual;
+
+// Check
+if ( !History.enabled ) {
+ throw new Error('History.js is disabled');
+}
+
+// Prepare
+History.options.debug = false;
+
+// Variables
+var
+ States = {
+ // Home
+ 0: {
+ 'url': document.location.href.replace(/#.*$/,''),
+ 'title': ''
+ },
+ // One
+ 1: {
+ 'data': {
+ 'state': 1,
+ 'rand': Math.random()
+ },
+ 'title': 'State 1',
+ 'url': '?state=1'
+ },
+ // Two
+ 2: {
+ 'data': {
+ 'state': 2,
+ 'rand': Math.random()
+ },
+ 'title': 'State 2',
+ 'url': '?state=2&asd=%20asd%2520asd'
+ },
+ // Three
+ 3: {
+ 'url': '?state=3'
+ },
+ // Four
+ 4: {
+ 'data': {
+ 'state': 4,
+ 'trick': true,
+ 'rand': Math.random()
+ },
+ 'title': 'State 4',
+ 'url': '?state=3'
+ },
+ // Log
+ 5: {
+ 'url': '?state=1#log'
+ },
+ // Six
+ 6: {
+ 'data': {
+ 'state': 6,
+ 'rand': Math.random()
+ },
+ 'url': 'six.html'
+ },
+ // Seven
+ 7: {
+ 'url': 'seven'
+ },
+ // Eight
+ 8: {
+ 'url': '/eight'
+ }
+ },
+ stateOrder = [0,1,2,3,4,3,1,0,1,3,4,3,1,0,6,7,8,1,8,7,6,0],
+ currentTest = 0;
+
+// Original Title
+var title = document.title;
+
+var banner;
+
+var checkStatus = function(){
+ banner = banner || document.getElementById('qunit-banner');
+ var status = banner.className !== 'qunit-fail';
+ return status;
+};
+
+// Check State
+var checkState = function(){
+ if ( !checkStatus() ) {
+ throw new Error('A test has failed');
+ }
+
+ var
+ stateIndex = stateOrder[currentTest],
+ expectedState = History.normalizeState(States[stateIndex]),
+ actualState = History.getState(false);
+
+ ++currentTest;
+
+ document.title = title+': '+actualState.url;
+
+ var
+ testName = 'Test '+currentTest,
+ stateName = 'State '+stateIndex;
+
+ test(testName,function(){
+ History.log('Completed: '+testName +' / '+ stateName);
+ deepEqual(actualState,expectedState,stateName);
+ });
+
+ // Image Load to Stress Test Safari and Opera
+ (new Image()).src = "image.php";
+};
+
+// Check the Initial State
+checkState();
+
+// State Change
+History.Adapter.bind(window,'statechange',checkState);
+
+// Log
+var addLog = function(){
+ var args = arguments;
+ History.queue(function(){
+ History.log.apply(History,args);
+ });
+};
+
+// Dom Load
+History.Adapter.onDomLoad(function(){
+ setTimeout(function(){
+
+ // ----------------------------------------------------------------------
+ // Test State Functionality: Adding
+
+ // Test 2 / State 1 (0 -> 1)
+ // Tests HTML4 -> HTML5 Graceful Upgrade
+ addLog('Test 2',History.queues.length,History.busy.flag);
+ History.setHash(History.getHashByState(States[1]));
+
+ // Test 3 / State 2 (1 -> 2)
+ addLog('Test 3',History.queues.length,History.busy.flag);
+ History.pushState(States[2].data, States[2].title, States[2].url);
+
+ // Test 3-2 / State 2 (2 -> 2) / No Change
+ addLog('Test 3-2',History.queues.length,History.busy.flag);
+ History.pushState(States[2].data, States[2].title, States[2].url);
+
+ // Test 3-3 / State 2 (2 -> 2) / No Change
+ addLog('Test 3-3',History.queues.length,History.busy.flag);
+ History.replaceState(States[2].data, States[2].title, States[2].url);
+
+ // Test 4 / State 3 (2 -> 3)
+ addLog('Test 4',History.queues.length,History.busy.flag);
+ History.replaceState(States[3].data, States[3].title, States[3].url);
+
+ // Test 5 / State 4 (3 -> 4)
+ addLog('Test 5',History.queues.length,History.busy.flag);
+ History.pushState(States[4].data, States[4].title, States[4].url);
+
+ // ----------------------------------------------------------------------
+ // Test State Functionality: Traversing
+
+ // Test 6 / State 3 (4 -> 3)
+ // Test 7 / State 1 (3 -> 2 -> 1)
+ addLog('Test 6,7',History.queues.length,History.busy.flag);
+ History.go(-2);
+
+ // Test 8 / State 0 (1 -> 0)
+ // Tests Default State
+ addLog('Test 8',History.queues.length,History.busy.flag);
+ History.back();
+
+ // Test 9 / State 1 (0 -> 1)
+ // Test 10 / State 3 (1 -> 2 -> 3)
+ addLog('Test 9,10',History.queues.length,History.busy.flag);
+ History.go(2);
+
+ // Test 11 / State 4 (3 -> 4)
+ addLog('Test 11',History.queues.length,History.busy.flag);
+ History.forward();
+
+ // Test 12 / State 3 (4 -> 3)
+ addLog('Test 12',History.queues.length,History.busy.flag);
+ History.back();
+
+ // Test 13 / State 1 (3 -> 2 -> 1)
+ addLog('Test 13',History.queues.length,History.busy.flag);
+ History.back();
+
+ // ----------------------------------------------------------------------
+ // Test State Functionality: Traditional Anchors
+
+ // Test 13-2 / State 1 (1 -> #log) / No Change
+ addLog('Test 13-2',History.queues.length,History.busy.flag);
+ History.setHash('log');
+
+ // Test 13-3 / State 1 (#log -> 1) / No Change
+ addLog('Test 13-3',History.queues.length,History.busy.flag);
+ History.back();
+
+ // Test 14 / State 0 (1 -> 0)
+ addLog('Test 14',History.queues.length,History.busy.flag);
+ History.back();
+
+ // ----------------------------------------------------------------------
+ // Test URL Handling: Adding
+
+ // Test 15 / State 6 (1 -> 6)
+ // Also tests data with no title
+ addLog('Test 15',History.queues.length,History.busy.flag);
+ History.pushState(States[6].data, States[6].title, States[6].url);
+
+ // Test 16 / State 7 (6 -> 7)
+ addLog('Test 16',History.queues.length,History.busy.flag);
+ History.pushState(States[7].data, States[7].title, States[7].url);
+
+ // Test 17 / State 7 (7 -> 8)
+ addLog('Test 17',History.queues.length,History.busy.flag);
+ History.pushState(States[8].data, States[8].title, States[8].url);
+
+ // Test 18 / State 1 (8 -> 1)
+ // Should be /eight?state=1
+ addLog('Test 18',History.queues.length,History.busy.flag);
+ History.pushState(States[1].data, States[1].title, States[1].url);
+
+ // ----------------------------------------------------------------------
+ // Test URL Handling: Traversing
+
+ // Test 19 / State 8 (1 -> 8)
+ addLog('Test 19',History.queues.length,History.busy.flag);
+ History.back();
+
+ // Test 20 / State 7 (8 -> 7)
+ addLog('Test 20',History.queues.length,History.busy.flag);
+ History.back();
+
+ // Test 21 / State 6 (7 -> 6)
+ addLog('Test 21',History.queues.length,History.busy.flag);
+ History.back();
+
+ // Test 22 / State 0 (6 -> 0)
+ addLog('Test 22',History.queues.length,History.busy.flag);
+ History.back();
+
+ },1000); // wait for test one to complete
+});
+
+})();
diff --git a/sites/all/themes/gui/materiobasetheme/bower_components/history.js/vendor/dojo.js b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/vendor/dojo.js
new file mode 100644
index 00000000..f66b95f4
--- /dev/null
+++ b/sites/all/themes/gui/materiobasetheme/bower_components/history.js/vendor/dojo.js
@@ -0,0 +1,17737 @@
+/*
+ Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
+ Available via Academic Free License >= 2.1 OR the modified BSD license.
+ see: http://dojotoolkit.org/license for details
+*/
+
+/*
+ This is an optimized version of Dojo, built for deployment and not for
+ development. To get sources and documentation, please visit:
+
+ http://dojotoolkit.org
+*/
+
+(function(
+ userConfig,
+ defaultConfig
+){
+ // summary:
+ // This is the "source loader" and is the entry point for Dojo during development. You may also load Dojo with
+ // any AMD-compliant loader via the package main module dojo/main.
+ // description:
+ // This is the "source loader" for Dojo. It provides an AMD-compliant loader that can be configured
+ // to operate in either synchronous or asynchronous modes. After the loader is defined, dojo is loaded
+ // IAW the package main module dojo/main. In the event you wish to use a foreign loader, you may load dojo as a package
+ // via the package main module dojo/main and this loader is not required; see dojo/package.json for details.
+ //
+ // In order to keep compatibility with the v1.x line, this loader includes additional machinery that enables
+ // the dojo.provide, dojo.require et al API. This machinery is loaded by default, but may be dynamically removed
+ // via the has.js API and statically removed via the build system.
+ //
+ // This loader includes sniffing machinery to determine the environment; the following environments are supported:
+ //
+ // - browser
+ // - node.js
+ // - rhino
+ //
+ // This is the so-called "source loader". As such, it includes many optional features that may be discadred by
+ // building a customized verion with the build system.
+
+ // Design and Implementation Notes
+ //
+ // This is a dojo-specific adaption of bdLoad, donated to the dojo foundation by Altoviso LLC.
+ //
+ // This function defines an AMD-compliant (http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition)
+ // loader that can be configured to operate in either synchronous or asynchronous modes.
+ //
+ // Since this machinery implements a loader, it does not have the luxury of using a load system and/or
+ // leveraging a utility library. This results in an unpleasantly long file; here is a road map of the contents:
+ //
+ // 1. Small library for use implementing the loader.
+ // 2. Define the has.js API; this is used throughout the loader to bracket features.
+ // 3. Define the node.js and rhino sniffs and sniff.
+ // 4. Define the loader's data.
+ // 5. Define the configuration machinery.
+ // 6. Define the script element sniffing machinery and sniff for configuration data.
+ // 7. Configure the loader IAW the provided user, default, and sniffing data.
+ // 8. Define the global require function.
+ // 9. Define the module resolution machinery.
+ // 10. Define the module and plugin module definition machinery
+ // 11. Define the script injection machinery.
+ // 12. Define the window load detection.
+ // 13. Define the logging API.
+ // 14. Define the tracing API.
+ // 16. Define the AMD define function.
+ // 17. Define the dojo v1.x provide/require machinery--so called "legacy" modes.
+ // 18. Publish global variables.
+ //
+ // Language and Acronyms and Idioms
+ //
+ // moduleId: a CJS module identifier, (used for public APIs)
+ // mid: moduleId (used internally)
+ // packageId: a package identifier (used for public APIs)
+ // pid: packageId (used internally); the implied system or default package has pid===""
+ // pack: package is used internally to reference a package object (since javascript has reserved words including "package")
+ // prid: plugin resource identifier
+ // The integer constant 1 is used in place of true and 0 in place of false.
+
+ // define a minimal library to help build the loader
+ var noop = function(){
+ },
+
+ isEmpty = function(it){
+ for(var p in it){
+ return 0;
+ }
+ return 1;
+ },
+
+ toString = {}.toString,
+
+ isFunction = function(it){
+ return toString.call(it) == "[object Function]";
+ },
+
+ isString = function(it){
+ return toString.call(it) == "[object String]";
+ },
+
+ isArray = function(it){
+ return toString.call(it) == "[object Array]";
+ },
+
+ forEach = function(vector, callback){
+ if(vector){
+ for(var i = 0; i < vector.length;){
+ callback(vector[i++]);
+ }
+ }
+ },
+
+ mix = function(dest, src){
+ for(var p in src){
+ dest[p] = src[p];
+ }
+ return dest;
+ },
+
+ makeError = function(error, info){
+ return mix(new Error(error), {src:"dojoLoader", info:info});
+ },
+
+ uidSeed = 1,
+
+ uid = function(){
+ // Returns a unique indentifier (within the lifetime of the document) of the form /_d+/.
+ return "_" + uidSeed++;
+ },
+
+ // FIXME: how to doc window.require() api
+
+ // this will be the global require function; define it immediately so we can start hanging things off of it
+ req = function(
+ config, //(object, optional) hash of configuration properties
+ dependencies, //(array of commonjs.moduleId, optional) list of modules to be loaded before applying callback
+ callback //(function, optional) lamda expression to apply to module values implied by dependencies
+ ){
+ return contextRequire(config, dependencies, callback, 0, req);
+ },
+
+ // the loader uses the has.js API to control feature inclusion/exclusion; define then use throughout
+ global = this,
+
+ doc = global.document,
+
+ element = doc && doc.createElement("DiV"),
+
+ has = req.has = function(name){
+ return isFunction(hasCache[name]) ? (hasCache[name] = hasCache[name](global, doc, element)) : hasCache[name];
+ },
+
+ hasCache = has.cache = defaultConfig.hasCache;
+
+ has.add = function(name, test, now, force){
+ (hasCache[name]===undefined || force) && (hasCache[name] = test);
+ return now && has(name);
+ };
+
+ 0 && has.add("host-node", userConfig.has && "host-node" in userConfig.has ?
+ userConfig.has["host-node"] :
+ (typeof process == "object" && process.versions && process.versions.node && process.versions.v8));
+ if( 0 ){
+ // fixup the default config for node.js environment
+ require("./_base/configNode.js").config(defaultConfig);
+ // remember node's require (with respect to baseUrl==dojo's root)
+ defaultConfig.loaderPatch.nodeRequire = require;
+ }
+
+ 0 && has.add("host-rhino", userConfig.has && "host-rhino" in userConfig.has ?
+ userConfig.has["host-rhino"] :
+ (typeof load == "function" && (typeof Packages == "function" || typeof Packages == "object")));
+ if( 0 ){
+ // owing to rhino's lame feature that hides the source of the script, give the user a way to specify the baseUrl...
+ for(var baseUrl = userConfig.baseUrl || ".", arg, rhinoArgs = this.arguments, i = 0; i < rhinoArgs.length;){
+ arg = (rhinoArgs[i++] + "").split("=");
+ if(arg[0] == "baseUrl"){
+ baseUrl = arg[1];
+ break;
+ }
+ }
+ load(baseUrl + "/_base/configRhino.js");
+ rhinoDojoConfig(defaultConfig, baseUrl, rhinoArgs);
+ }
+
+ // userConfig has tests override defaultConfig has tests; do this after the environment detection because
+ // the environment detection usually sets some has feature values in the hasCache.
+ for(var p in userConfig.has){
+ has.add(p, userConfig.has[p], 0, 1);
+ }
+
+ //
+ // define the loader data
+ //
+
+ // the loader will use these like symbols if the loader has the traceApi; otherwise
+ // define magic numbers so that modules can be provided as part of defaultConfig
+ var requested = 1,
+ arrived = 2,
+ nonmodule = 3,
+ executing = 4,
+ executed = 5;
+
+ if( 0 ){
+ // these make debugging nice; but using strings for symbols is a gross rookie error; don't do it for production code
+ requested = "requested";
+ arrived = "arrived";
+ nonmodule = "not-a-module";
+ executing = "executing";
+ executed = "executed";
+ }
+
+ var legacyMode = 0,
+ sync = "sync",
+ xd = "xd",
+ syncExecStack = [],
+ dojoRequirePlugin = 0,
+ checkDojoRequirePlugin = noop,
+ transformToAmd = noop,
+ getXhr;
+ if( 1 ){
+ req.isXdUrl = noop;
+
+ req.initSyncLoader = function(dojoRequirePlugin_, checkDojoRequirePlugin_, transformToAmd_){
+ // the first dojo/_base/loader loaded gets to define these variables; they are designed to work
+ // in the presense of zero to many mapped dojo/_base/loaders
+ if(!dojoRequirePlugin){
+ dojoRequirePlugin = dojoRequirePlugin_;
+ checkDojoRequirePlugin = checkDojoRequirePlugin_;
+ transformToAmd = transformToAmd_;
+ }
+
+ return {
+ sync:sync,
+ requested:requested,
+ arrived:arrived,
+ nonmodule:nonmodule,
+ executing:executing,
+ executed:executed,
+ syncExecStack:syncExecStack,
+ modules:modules,
+ execQ:execQ,
+ getModule:getModule,
+ injectModule:injectModule,
+ setArrived:setArrived,
+ signal:signal,
+ finishExec:finishExec,
+ execModule:execModule,
+ dojoRequirePlugin:dojoRequirePlugin,
+ getLegacyMode:function(){return legacyMode;},
+ guardCheckComplete:guardCheckComplete
+ };
+ };
+
+ if( 1 ){
+ // in legacy sync mode, the loader needs a minimal XHR library
+
+ var locationProtocol = location.protocol,
+ locationHost = location.host;
+ req.isXdUrl = function(url){
+ if(/^\./.test(url)){
+ // begins with a dot is always relative to page URL; therefore not xdomain
+ return false;
+ }
+ if(/^\/\//.test(url)){
+ // for v1.6- backcompat, url starting with // indicates xdomain
+ return true;
+ }
+ // get protocol and host
+ // \/+ takes care of the typical file protocol that looks like file:///drive/path/to/file
+ // locationHost is falsy if file protocol => if locationProtocol matches and is "file:", || will return false
+ var match = url.match(/^([^\/\:]+\:)\/+([^\/]+)/);
+ return match && (match[1] != locationProtocol || (locationHost && match[2] != locationHost));
+ };
+
+
+ // note: to get the file:// protocol to work in FF, you must set security.fileuri.strict_origin_policy to false in about:config
+ 1 || has.add("dojo-xhr-factory", 1);
+ has.add("dojo-force-activex-xhr", 1 && !doc.addEventListener && window.location.protocol == "file:");
+ has.add("native-xhr", typeof XMLHttpRequest != "undefined");
+ if(has("native-xhr") && !has("dojo-force-activex-xhr")){
+ getXhr = function(){
+ return new XMLHttpRequest();
+ };
+ }else{
+ // if in the browser an old IE; find an xhr
+ for(var XMLHTTP_PROGIDS = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'], progid, i = 0; i < 3;){
+ try{
+ progid = XMLHTTP_PROGIDS[i++];
+ if(new ActiveXObject(progid)){
+ // this progid works; therefore, use it from now on
+ break;
+ }
+ }catch(e){
+ // squelch; we're just trying to find a good ActiveX progid
+ // if they all fail, then progid ends up as the last attempt and that will signal the error
+ // the first time the client actually tries to exec an xhr
+ }
+ }
+ getXhr = function(){
+ return new ActiveXObject(progid);
+ };
+ }
+ req.getXhr = getXhr;
+
+ has.add("dojo-gettext-api", 1);
+ req.getText = function(url, async, onLoad){
+ var xhr = getXhr();
+ xhr.open('GET', fixupUrl(url), false);
+ xhr.send(null);
+ if(xhr.status == 200 || (!location.host && !xhr.status)){
+ if(onLoad){
+ onLoad(xhr.responseText, async);
+ }
+ }else{
+ throw makeError("xhrFailed", xhr.status);
+ }
+ return xhr.responseText;
+ };
+ }
+ }else{
+ req.async = 1;
+ }
+
+ //
+ // loader eval
+ //
+ var eval_ =
+ // use the function constructor so our eval is scoped close to (but not in) in the global space with minimal pollution
+ new Function('return eval(arguments[0]);');
+
+ req.eval =
+ function(text, hint){
+ return eval_(text + "\r\n////@ sourceURL=" + hint);
+ };
+
+ //
+ // loader micro events API
+ //
+ var listenerQueues = {},
+ error = "error",
+ signal = req.signal = function(type, args){
+ var queue = listenerQueues[type];
+ // notice we run a copy of the queue; this allows listeners to add/remove
+ // other listeners without affecting this particular signal
+ forEach(queue && queue.slice(0), function(listener){
+ listener.apply(null, isArray(args) ? args : [args]);
+ });
+ },
+ on = req.on = function(type, listener){
+ // notice a queue is not created until a client actually connects
+ var queue = listenerQueues[type] || (listenerQueues[type] = []);
+ queue.push(listener);
+ return {
+ remove:function(){
+ for(var i = 0; i (alias, actual)
+ = [],
+
+ paths
+ // CommonJS paths
+ = {},
+
+ pathsMapProg
+ // list of (from-path, to-path, regex, length) derived from paths;
+ // a "program" to apply paths; see computeMapProg
+ = [],
+
+ packs
+ // a map from packageId to package configuration object; see fixupPackageInfo
+ = {},
+
+ map = req.map
+ // AMD map config variable; dojo/_base/kernel needs req.map to figure out the scope map
+ = {},
+
+ mapProgs
+ // vector of quads as described by computeMapProg; map-key is AMD map key, map-value is AMD map value
+ = [],
+
+ modules
+ // A hash:(mid) --> (module-object) the module namespace
+ //
+ // pid: the package identifier to which the module belongs (e.g., "dojo"); "" indicates the system or default package
+ // mid: the fully-resolved (i.e., mappings have been applied) module identifier without the package identifier (e.g., "dojo/io/script")
+ // url: the URL from which the module was retrieved
+ // pack: the package object of the package to which the module belongs
+ // executed: 0 => not executed; executing => in the process of tranversing deps and running factory; executed => factory has been executed
+ // deps: the dependency vector for this module (vector of modules objects)
+ // def: the factory for this module
+ // result: the result of the running the factory for this module
+ // injected: (0 | requested | arrived) the status of the module; nonmodule means the resource did not call define
+ // load: plugin load function; applicable only for plugins
+ //
+ // Modules go through several phases in creation:
+ //
+ // 1. Requested: some other module's definition or a require application contained the requested module in
+ // its dependency vector or executing code explicitly demands a module via req.require.
+ //
+ // 2. Injected: a script element has been appended to the insert-point element demanding the resource implied by the URL
+ //
+ // 3. Loaded: the resource injected in [2] has been evalated.
+ //
+ // 4. Defined: the resource contained a define statement that advised the loader about the module. Notice that some
+ // resources may just contain a bundle of code and never formally define a module via define
+ //
+ // 5. Evaluated: the module was defined via define and the loader has evaluated the factory and computed a result.
+ = {},
+
+ cacheBust
+ // query string to append to module URLs to bust browser cache
+ = "",
+
+ cache
+ // hash:(mid | url)-->(function | string)
+ //
+ // A cache of resources. The resources arrive via a config.cache object, which is a hash from either mid --> function or
+ // url --> string. The url key is distinguished from the mid key by always containing the prefix "url:". url keys as provided
+ // by config.cache always have a string value that represents the contents of the resource at the given url. mid keys as provided
+ // by configl.cache always have a function value that causes the same code to execute as if the module was script injected.
+ //
+ // Both kinds of key-value pairs are entered into cache via the function consumePendingCache, which may relocate keys as given
+ // by any mappings *iff* the config.cache was received as part of a module resource request.
+ //
+ // Further, for mid keys, the implied url is computed and the value is entered into that key as well. This allows mapped modules
+ // to retrieve cached items that may have arrived consequent to another namespace.
+ //
+ = {},
+
+ urlKeyPrefix
+ // the prefix to prepend to a URL key in the cache.
+ = "url:",
+
+ pendingCacheInsert
+ // hash:(mid)-->(function)
+ //
+ // Gives a set of cache modules pending entry into cache. When cached modules are published to the loader, they are
+ // entered into pendingCacheInsert; modules are then pressed into cache upon (1) AMD define or (2) upon receiving another
+ // independent set of cached modules. (1) is the usual case, and this case allows normalizing mids given in the pending
+ // cache for the local configuration, possibly relocating modules.
+ = {},
+
+ dojoSniffConfig
+ // map of configuration variables
+ // give the data-dojo-config as sniffed from the document (if any)
+ = {};
+
+ if( 1 ){
+ var consumePendingCacheInsert = function(referenceModule){
+ var p, item, match, now, m;
+ for(p in pendingCacheInsert){
+ item = pendingCacheInsert[p];
+ match = p.match(/^url\:(.+)/);
+ if(match){
+ cache[urlKeyPrefix + toUrl(match[1], referenceModule)] = item;
+ }else if(p=="*now"){
+ now = item;
+ }else if(p!="*noref"){
+ m = getModuleInfo(p, referenceModule);
+ cache[m.mid] = cache[urlKeyPrefix + m.url] = item;
+ }
+ }
+ if(now){
+ now(createRequire(referenceModule));
+ }
+ pendingCacheInsert = {};
+ },
+
+ escapeString = function(s){
+ return s.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, function(c){ return "\\" + c; });
+ },
+
+ computeMapProg = function(map, dest){
+ // This routine takes a map as represented by a JavaScript object and initializes dest, a vector of
+ // quads of (map-key, map-value, refex-for-map-key, length-of-map-key), sorted decreasing by length-
+ // of-map-key. The regex looks for the map-key followed by either "/" or end-of-string at the beginning
+ // of a the search source. Notice the map-value is irrelevent to the algorithm
+ dest.splice(0, dest.length);
+ for(var p in map){
+ dest.push([
+ p,
+ map[p],
+ new RegExp("^" + escapeString(p) + "(\/|$)"),
+ p.length]);
+ }
+ dest.sort(function(lhs, rhs){ return rhs[3] - lhs[3]; });
+ return dest;
+ },
+
+ fixupPackageInfo = function(packageInfo){
+ // calculate the precise (name, location, main, mappings) for a package
+ var name = packageInfo.name;
+ if(!name){
+ // packageInfo must be a string that gives the name
+ name = packageInfo;
+ packageInfo = {name:name};
+ }
+ packageInfo = mix({main:"main"}, packageInfo);
+ packageInfo.location = packageInfo.location ? packageInfo.location : name;
+
+ // packageMap is depricated in favor of AMD map
+ if(packageInfo.packageMap){
+ map[name] = packageInfo.packageMap;
+ }
+
+ if(!packageInfo.main.indexOf("./")){
+ packageInfo.main = packageInfo.main.substring(2);
+ }
+
+ // now that we've got a fully-resolved package object, push it into the configuration
+ packs[name] = packageInfo;
+ },
+
+ delayedModuleConfig
+ // module config cannot be consummed until the loader is completely initialized; therefore, all
+ // module config detected during booting is memorized and applied at the end of loader initialization
+ // TODO: this is a bit of a kludge; all config should be moved to end of loader initialization, but
+ // we'll delay this chore and do it with a final loader 1.x cleanup after the 2.x loader prototyping is complete
+ = [],
+
+
+ config = function(config, booting, referenceModule){
+ for(var p in config){
+ if(p=="waitSeconds"){
+ req.waitms = (config[p] || 0) * 1000;
+ }
+ if(p=="cacheBust"){
+ cacheBust = config[p] ? (isString(config[p]) ? config[p] : (new Date()).getTime() + "") : "";
+ }
+ if(p=="baseUrl" || p=="combo"){
+ req[p] = config[p];
+ }
+ if( 1 && p=="async"){
+ // falsy or "sync" => legacy sync loader
+ // "xd" => sync but loading xdomain tree and therefore loading asynchronously (not configurable, set automatically by the loader)
+ // "legacyAsync" => permanently in "xd" by choice
+ // "debugAtAllCosts" => trying to load everything via script injection (not implemented)
+ // otherwise, must be truthy => AMD
+ // legacyMode: sync | legacyAsync | xd | false
+ var mode = config[p];
+ req.legacyMode = legacyMode = (isString(mode) && /sync|legacyAsync/.test(mode) ? mode : (!mode ? sync : false));
+ req.async = !legacyMode;
+ }
+ if(config[p]!==hasCache){
+ // accumulate raw config info for client apps which can use this to pass their own config
+ req.rawConfig[p] = config[p];
+ p!="has" && has.add("config-"+p, config[p], 0, booting);
+ }
+ }
+
+ // make sure baseUrl exists
+ if(!req.baseUrl){
+ req.baseUrl = "./";
+ }
+ // make sure baseUrl ends with a slash
+ if(!/\/$/.test(req.baseUrl)){
+ req.baseUrl += "/";
+ }
+
+ // now do the special work for has, packages, packagePaths, paths, aliases, and cache
+
+ for(p in config.has){
+ has.add(p, config.has[p], 0, booting);
+ }
+
+ // for each package found in any packages config item, augment the packs map owned by the loader
+ forEach(config.packages, fixupPackageInfo);
+
+ // for each packagePath found in any packagePaths config item, augment the packageConfig
+ // packagePaths is depricated; remove in 2.0
+ for(baseUrl in config.packagePaths){
+ forEach(config.packagePaths[baseUrl], function(packageInfo){
+ var location = baseUrl + "/" + packageInfo;
+ if(isString(packageInfo)){
+ packageInfo = {name:packageInfo};
+ }
+ packageInfo.location = location;
+ fixupPackageInfo(packageInfo);
+ });
+ }
+
+ // notice that computeMapProg treats the dest as a reference; therefore, if/when that variable
+ // is published (see dojo-publish-privates), the published variable will always hold a valid value.
+
+ // this must come after all package processing since package processing may mutate map
+ computeMapProg(mix(map, config.map), mapProgs);
+ forEach(mapProgs, function(item){
+ item[1] = computeMapProg(item[1], []);
+ if(item[0]=="*"){
+ mapProgs.star = item[1];
+ }
+ });
+
+ // push in any paths and recompute the internal pathmap
+ computeMapProg(mix(paths, config.paths), pathsMapProg);
+
+ // aliases
+ forEach(config.aliases, function(pair){
+ if(isString(pair[0])){
+ pair[0] = new RegExp("^" + escapeString(pair[0]) + "$");
+ }
+ aliases.push(pair);
+ });
+
+ if(booting){
+ delayedModuleConfig.push({config:config.config});
+ }else{
+ for(p in config.config){
+ var module = getModule(p, referenceModule);
+ module.config = mix(module.config || {}, config.config[p]);
+ }
+ }
+
+ // push in any new cache values
+ if(config.cache){
+ consumePendingCacheInsert();
+ pendingCacheInsert = config.cache;
+ if(config.cache["*noref"]){
+ consumePendingCacheInsert();
+ }
+ }
+
+ signal("config", [config, req.rawConfig]);
+ };
+
+ //
+ // execute the various sniffs; userConfig can override and value
+ //
+
+ if(has("dojo-cdn") || 1 ){
+ // the sniff regex looks for a src attribute ending in dojo.js, optionally preceeded with a path.
+ // match[3] returns the path to dojo.js (if any) without the trailing slash. This is used for the
+ // dojo location on CDN deployments and baseUrl when either/both of these are not provided
+ // explicitly in the config data; this is the 1.6- behavior.
+
+ var scripts = doc.getElementsByTagName("script"),
+ i = 0,
+ script, dojoDir, src, match;
+ while(i < scripts.length){
+ script = scripts[i++];
+ if((src = script.getAttribute("src")) && (match = src.match(/(((.*)\/)|^)dojo\.js(\W|$)/i))){
+ // sniff dojoDir and baseUrl
+ dojoDir = match[3] || "";
+ defaultConfig.baseUrl = defaultConfig.baseUrl || dojoDir;
+
+ // sniff configuration on attribute in script element
+ src = (script.getAttribute("data-dojo-config") || script.getAttribute("djConfig"));
+ if(src){
+ dojoSniffConfig = req.eval("({ " + src + " })", "data-dojo-config");
+ }
+
+ // sniff requirejs attribute
+ if( 0 ){
+ var dataMain = script.getAttribute("data-main");
+ if(dataMain){
+ dojoSniffConfig.deps = dojoSniffConfig.deps || [dataMain];
+ }
+ }
+ break;
+ }
+ }
+ }
+
+ if( 0 ){
+ // pass down doh.testConfig from parent as if it were a data-dojo-config
+ try{
+ if(window.parent != window && window.parent.require){
+ var doh = window.parent.require("doh");
+ doh && mix(dojoSniffConfig, doh.testConfig);
+ }
+ }catch(e){}
+ }
+
+ // configure the loader; let the user override defaults
+ req.rawConfig = {};
+ config(defaultConfig, 1);
+
+ // do this before setting userConfig/sniffConfig to allow userConfig/sniff overrides
+ if(has("dojo-cdn")){
+ packs.dojo.location = dojoDir;
+ if(dojoDir){
+ dojoDir += "/";
+ }
+ packs.dijit.location = dojoDir + "../dijit/";
+ packs.dojox.location = dojoDir + "../dojox/";
+ }
+
+ config(userConfig, 1);
+ config(dojoSniffConfig, 1);
+
+ }else{
+ // no config API, assume defaultConfig has everything the loader needs...for the entire lifetime of the application
+ paths = defaultConfig.paths;
+ pathsMapProg = defaultConfig.pathsMapProg;
+ packs = defaultConfig.packs;
+ aliases = defaultConfig.aliases;
+ mapProgs = defaultConfig.mapProgs;
+ modules = defaultConfig.modules;
+ cache = defaultConfig.cache;
+ cacheBust = defaultConfig.cacheBust;
+
+ // remember the default config for other processes (e.g., dojo/config)
+ req.rawConfig = defaultConfig;
+ }
+
+
+ if( 0 ){
+ req.combo = req.combo || {add:noop};
+ var comboPending = 0,
+ combosPending = [],
+ comboPendingTimer = null;
+ }
+
+
+ // build the loader machinery iaw configuration, including has feature tests
+ var injectDependencies = function(module){
+ // checkComplete!=0 holds the idle signal; we're not idle if we're injecting dependencies
+ guardCheckComplete(function(){
+ forEach(module.deps, injectModule);
+ if( 0 && comboPending && !comboPendingTimer){
+ comboPendingTimer = setTimeout(function() {
+ comboPending = 0;
+ comboPendingTimer = null;
+ req.combo.done(function(mids, url) {
+ var onLoadCallback= function(){
+ // defQ is a vector of module definitions 1-to-1, onto mids
+ runDefQ(0, mids);
+ checkComplete();
+ };
+ combosPending.push(mids);
+ injectingModule = mids;
+ req.injectUrl(url, onLoadCallback, mids);
+ injectingModule = 0;
+ }, req);
+ }, 0);
+ }
+ });
+ },
+
+ contextRequire = function(a1, a2, a3, referenceModule, contextRequire){
+ var module, syntheticMid;
+ if(isString(a1)){
+ // signature is (moduleId)
+ module = getModule(a1, referenceModule, true);
+ if(module && module.executed){
+ return module.result;
+ }
+ throw makeError("undefinedModule", a1);
+ }
+ if(!isArray(a1)){
+ // a1 is a configuration
+ config(a1, 0, referenceModule);
+
+ // juggle args; (a2, a3) may be (dependencies, callback)
+ a1 = a2;
+ a2 = a3;
+ }
+ if(isArray(a1)){
+ // signature is (requestList [,callback])
+ if(!a1.length){
+ a2 && a2();
+ }else{
+ syntheticMid = "require*" + uid();
+
+ // resolve the request list with respect to the reference module
+ for(var mid, deps = [], i = 0; i < a1.length;){
+ mid = a1[i++];
+ deps.push(getModule(mid, referenceModule));
+ }
+
+ // construct a synthetic module to control execution of the requestList, and, optionally, callback
+ module = mix(makeModuleInfo("", syntheticMid, 0, ""), {
+ injected: arrived,
+ deps: deps,
+ def: a2 || noop,
+ require: referenceModule ? referenceModule.require : req,
+ gc: 1 //garbage collect
+ });
+ modules[module.mid] = module;
+
+ // checkComplete!=0 holds the idle signal; we're not idle if we're injecting dependencies
+ injectDependencies(module);
+
+ // try to immediately execute
+ // if already traversing a factory tree, then strict causes circular dependency to abort the execution; maybe
+ // it's possible to execute this require later after the current traversal completes and avoid the circular dependency.
+ // ...but *always* insist on immediate in synch mode
+ var strict = checkCompleteGuard && legacyMode!=sync;
+ guardCheckComplete(function(){
+ execModule(module, strict);
+ });
+ if(!module.executed){
+ // some deps weren't on board or circular dependency detected and strict; therefore, push into the execQ
+ execQ.push(module);
+ }
+ checkComplete();
+ }
+ }
+ return contextRequire;
+ },
+
+ createRequire = function(module){
+ if(!module){
+ return req;
+ }
+ var result = module.require;
+ if(!result){
+ result = function(a1, a2, a3){
+ return contextRequire(a1, a2, a3, module, result);
+ };
+ module.require = mix(result, req);
+ result.module = module;
+ result.toUrl = function(name){
+ return toUrl(name, module);
+ };
+ result.toAbsMid = function(mid){
+ return toAbsMid(mid, module);
+ };
+ if( 0 ){
+ result.undef = function(mid){
+ req.undef(mid, module);
+ };
+ }
+ if( 1 ){
+ result.syncLoadNls = function(mid){
+ var nlsModuleInfo = getModuleInfo(mid, module),
+ nlsModule = modules[nlsModuleInfo.mid];
+ if(!nlsModule || !nlsModule.executed){
+ cached = cache[nlsModuleInfo.mid] || cache[urlKeyPrefix + nlsModuleInfo.url];
+ if(cached){
+ evalModuleText(cached);
+ nlsModule = modules[nlsModuleInfo.mid];
+ }
+ }
+ return nlsModule && nlsModule.executed && nlsModule.result;
+ };
+ }
+
+ }
+ return result;
+ },
+
+ execQ =
+ // The list of modules that need to be evaluated.
+ [],
+
+ defQ =
+ // The queue of define arguments sent to loader.
+ [],
+
+ waiting =
+ // The set of modules upon which the loader is waiting for definition to arrive
+ {},
+
+ setRequested = function(module){
+ module.injected = requested;
+ waiting[module.mid] = 1;
+ if(module.url){
+ waiting[module.url] = module.pack || 1;
+ }
+ startTimer();
+ },
+
+ setArrived = function(module){
+ module.injected = arrived;
+ delete waiting[module.mid];
+ if(module.url){
+ delete waiting[module.url];
+ }
+ if(isEmpty(waiting)){
+ clearTimer();
+ 1 && legacyMode==xd && (legacyMode = sync);
+ }
+ },
+
+ execComplete = req.idle =
+ // says the loader has completed (or not) its work
+ function(){
+ return !defQ.length && isEmpty(waiting) && !execQ.length && !checkCompleteGuard;
+ },
+
+ runMapProg = function(targetMid, map){
+ // search for targetMid in map; return the map item if found; falsy otherwise
+ if(map){
+ for(var i = 0; i < map.length; i++){
+ if(map[i][2].test(targetMid)){
+ return map[i];
+ }
+ }
+ }
+ return 0;
+ },
+
+ compactPath = function(path){
+ var result = [],
+ segment, lastSegment;
+ path = path.replace(/\\/g, '/').split('/');
+ while(path.length){
+ segment = path.shift();
+ if(segment==".." && result.length && lastSegment!=".."){
+ result.pop();
+ lastSegment = result[result.length - 1];
+ }else if(segment!="."){
+ result.push(lastSegment= segment);
+ } // else ignore "."
+ }
+ return result.join("/");
+ },
+
+ makeModuleInfo = function(pid, mid, pack, url){
+ if( 1 ){
+ var xd= req.isXdUrl(url);
+ return {pid:pid, mid:mid, pack:pack, url:url, executed:0, def:0, isXd:xd, isAmd:!!(xd || (packs[pid] && packs[pid].isAmd))};
+ }else{
+ return {pid:pid, mid:mid, pack:pack, url:url, executed:0, def:0};
+ }
+ },
+
+ getModuleInfo_ = function(mid, referenceModule, packs, modules, baseUrl, mapProgs, pathsMapProg, alwaysCreate){
+ // arguments are passed instead of using lexical variables so that this function my be used independent of the loader (e.g., the builder)
+ // alwaysCreate is useful in this case so that getModuleInfo never returns references to real modules owned by the loader
+ var pid, pack, midInPackage, mapProg, mapItem, url, result, isRelative, requestedMid;
+ requestedMid = mid;
+ isRelative = /^\./.test(mid);
+ if(/(^\/)|(\:)|(\.js$)/.test(mid) || (isRelative && !referenceModule)){
+ // absolute path or protocol of .js filetype, or relative path but no reference module and therefore relative to page
+ // whatever it is, it's not a module but just a URL of some sort
+ // note: pid===0 indicates the routine is returning an unmodified mid
+
+ return makeModuleInfo(0, mid, 0, mid);
+ }else{
+ // relative module ids are relative to the referenceModule; get rid of any dots
+ mid = compactPath(isRelative ? (referenceModule.mid + "/../" + mid) : mid);
+ if(/^\./.test(mid)){
+ throw makeError("irrationalPath", mid);
+ }
+ // at this point, mid is an absolute mid
+
+ // map the mid
+ if(referenceModule){
+ mapItem = runMapProg(referenceModule.mid, mapProgs);
+ }
+ mapItem = mapItem || mapProgs.star;
+ mapItem = mapItem && runMapProg(mid, mapItem[1]);
+
+ if(mapItem){
+ mid = mapItem[1] + mid.substring(mapItem[3]);
+ }
+
+ match = mid.match(/^([^\/]+)(\/(.+))?$/);
+ pid = match ? match[1] : "";
+ if((pack = packs[pid])){
+ mid = pid + "/" + (midInPackage = (match[3] || pack.main));
+ }else{
+ pid = "";
+ }
+
+ // search aliases
+ var candidateLength = 0,
+ candidate = 0;
+ forEach(aliases, function(pair){
+ var match = mid.match(pair[0]);
+ if(match && match.length>candidateLength){
+ candidate = isFunction(pair[1]) ? mid.replace(pair[0], pair[1]) : pair[1];
+ }
+ });
+ if(candidate){
+ return getModuleInfo_(candidate, 0, packs, modules, baseUrl, mapProgs, pathsMapProg, alwaysCreate);
+ }
+
+ result = modules[mid];
+ if(result){
+ return alwaysCreate ? makeModuleInfo(result.pid, result.mid, result.pack, result.url) : modules[mid];
+ }
+ }
+ // get here iff the sought-after module does not yet exist; therefore, we need to compute the URL given the
+ // fully resolved (i.e., all relative indicators and package mapping resolved) module id
+
+ // note: pid!==0 indicates the routine is returning a url that has .js appended unmodified mid
+ mapItem = runMapProg(mid, pathsMapProg);
+ if(mapItem){
+ url = mapItem[1] + mid.substring(mapItem[3]);
+ }else if(pid){
+ url = pack.location + "/" + midInPackage;
+ }else if(has("config-tlmSiblingOfDojo")){
+ url = "../" + mid;
+ }else{
+ url = mid;
+ }
+ // if result is not absolute, add baseUrl
+ if(!(/(^\/)|(\:)/.test(url))){
+ url = baseUrl + url;
+ }
+ url += ".js";
+ return makeModuleInfo(pid, mid, pack, compactPath(url));
+ },
+
+ getModuleInfo = function(mid, referenceModule){
+ return getModuleInfo_(mid, referenceModule, packs, modules, req.baseUrl, mapProgs, pathsMapProg);
+ },
+
+ resolvePluginResourceId = function(plugin, prid, referenceModule){
+ return plugin.normalize ? plugin.normalize(prid, function(mid){return toAbsMid(mid, referenceModule);}) : toAbsMid(prid, referenceModule);
+ },
+
+ dynamicPluginUidGenerator = 0,
+
+ getModule = function(mid, referenceModule, immediate){
+ // compute and optionally construct (if necessary) the module implied by the mid with respect to referenceModule
+ var match, plugin, prid, result;
+ match = mid.match(/^(.+?)\!(.*)$/);
+ if(match){
+ // name was !
+ plugin = getModule(match[1], referenceModule, immediate);
+
+ if( 1 && legacyMode == sync && !plugin.executed){
+ injectModule(plugin);
+ if(plugin.injected===arrived && !plugin.executed){
+ guardCheckComplete(function(){
+ execModule(plugin);
+ });
+ }
+ if(plugin.executed){
+ promoteModuleToPlugin(plugin);
+ }else{
+ // we are in xdomain mode for some reason
+ execQ.unshift(plugin);
+ }
+ }
+
+
+
+ if(plugin.executed === executed && !plugin.load){
+ // executed the module not knowing it was a plugin
+ promoteModuleToPlugin(plugin);
+ }
+
+ // if the plugin has not been loaded, then can't resolve the prid and must assume this plugin is dynamic until we find out otherwise
+ if(plugin.load){
+ prid = resolvePluginResourceId(plugin, match[2], referenceModule);
+ mid = (plugin.mid + "!" + (plugin.dynamic ? ++dynamicPluginUidGenerator + "!" : "") + prid);
+ }else{
+ prid = match[2];
+ mid = plugin.mid + "!" + (++dynamicPluginUidGenerator) + "!waitingForPlugin";
+ }
+ result = {plugin:plugin, mid:mid, req:createRequire(referenceModule), prid:prid};
+ }else{
+ result = getModuleInfo(mid, referenceModule);
+ }
+ return modules[result.mid] || (!immediate && (modules[result.mid] = result));
+ },
+
+ toAbsMid = req.toAbsMid = function(mid, referenceModule){
+ return getModuleInfo(mid, referenceModule).mid;
+ },
+
+ toUrl = req.toUrl = function(name, referenceModule){
+ var moduleInfo = getModuleInfo(name+"/x", referenceModule),
+ url= moduleInfo.url;
+ return fixupUrl(moduleInfo.pid===0 ?
+ // if pid===0, then name had a protocol or absolute path; either way, toUrl is the identify function in such cases
+ name :
+ // "/x.js" since getModuleInfo automatically appends ".js" and we appended "/x" to make name look likde a module id
+ url.substring(0, url.length-5)
+ );
+ },
+
+ nonModuleProps = {
+ injected: arrived,
+ executed: executed,
+ def: nonmodule,
+ result: nonmodule
+ },
+
+ makeCjs = function(mid){
+ return modules[mid] = mix({mid:mid}, nonModuleProps);
+ },
+
+ cjsRequireModule = makeCjs("require"),
+ cjsExportsModule = makeCjs("exports"),
+ cjsModuleModule = makeCjs("module"),
+
+ runFactory = function(module, args){
+ req.trace("loader-run-factory", [module.mid]);
+ var factory = module.def,
+ result;
+ 1 && syncExecStack.unshift(module);
+ if(has("config-dojo-loader-catches")){
+ try{
+ result= isFunction(factory) ? factory.apply(null, args) : factory;
+ }catch(e){
+ signal(error, module.result = makeError("factoryThrew", [module, e]));
+ }
+ }else{
+ result= isFunction(factory) ? factory.apply(null, args) : factory;
+ }
+ module.result = result===undefined && module.cjs ? module.cjs.exports : result;
+ 1 && syncExecStack.shift(module);
+ },
+
+ abortExec = {},
+
+ defOrder = 0,
+
+ promoteModuleToPlugin = function(pluginModule){
+ var plugin = pluginModule.result;
+ pluginModule.dynamic = plugin.dynamic;
+ pluginModule.normalize = plugin.normalize;
+ pluginModule.load = plugin.load;
+ return pluginModule;
+ },
+
+ resolvePluginLoadQ = function(plugin){
+ // plugins is a newly executed module that has a loadQ waiting to run
+
+ // step 1: traverse the loadQ and fixup the mid and prid; remember the map from original mid to new mid
+ // recall the original mid was created before the plugin was on board and therefore it was impossible to
+ // compute the final mid; accordingly, prid may or may not change, but the mid will definitely change
+ var map = {};
+ forEach(plugin.loadQ, function(pseudoPluginResource){
+ // manufacture and insert the real module in modules
+ var prid = resolvePluginResourceId(plugin, pseudoPluginResource.prid, pseudoPluginResource.req.module),
+ mid = plugin.dynamic ? pseudoPluginResource.mid.replace(/waitingForPlugin$/, prid) : (plugin.mid + "!" + prid),
+ pluginResource = mix(mix({}, pseudoPluginResource), {mid:mid, prid:prid, injected:0});
+ if(!modules[mid]){
+ // create a new (the real) plugin resource and inject it normally now that the plugin is on board
+ injectPlugin(modules[mid] = pluginResource);
+ } // else this was a duplicate request for the same (plugin, rid) for a nondynamic plugin
+
+ // pluginResource is really just a placeholder with the wrong mid (because we couldn't calculate it until the plugin was on board)
+ // mark is as arrived and delete it from modules; the real module was requested above
+ map[pseudoPluginResource.mid] = modules[mid];
+ setArrived(pseudoPluginResource);
+ delete modules[pseudoPluginResource.mid];
+ });
+ plugin.loadQ = 0;
+
+ // step2: replace all references to any placeholder modules with real modules
+ var substituteModules = function(module){
+ for(var replacement, deps = module.deps || [], i = 0; i")]);
+ return (!module.def || strict) ? abortExec : (module.cjs && module.cjs.exports);
+ }
+ // at this point the module is either not executed or fully executed
+
+
+ if(!module.executed){
+ if(!module.def){
+ return abortExec;
+ }
+ var mid = module.mid,
+ deps = module.deps || [],
+ arg, argResult,
+ args = [],
+ i = 0;
+
+ if( 0 ){
+ circleTrace.push(mid);
+ req.trace("loader-exec-module", ["exec", circleTrace.length, mid]);
+ }
+
+ // for circular dependencies, assume the first module encountered was executed OK
+ // modules that circularly depend on a module that has not run its factory will get
+ // the premade cjs.exports===module.result. They can take a reference to this object and/or
+ // add properties to it. When the module finally runs its factory, the factory can
+ // read/write/replace this object. Notice that so long as the object isn't replaced, any
+ // reference taken earlier while walking the deps list is still valid.
+ module.executed = executing;
+ while(i < deps.length){
+ arg = deps[i++];
+ argResult = ((arg === cjsRequireModule) ? createRequire(module) :
+ ((arg === cjsExportsModule) ? module.cjs.exports :
+ ((arg === cjsModuleModule) ? module.cjs :
+ execModule(arg, strict))));
+ if(argResult === abortExec){
+ module.executed = 0;
+ req.trace("loader-exec-module", ["abort", mid]);
+ 0 && circleTrace.pop();
+ return abortExec;
+ }
+ args.push(argResult);
+ }
+ runFactory(module, args);
+ finishExec(module);
+ 0 && circleTrace.pop();
+ }
+ // at this point the module is guaranteed fully executed
+
+ return module.result;
+ },
+
+
+ checkCompleteGuard = 0,
+
+ guardCheckComplete = function(proc){
+ try{
+ checkCompleteGuard++;
+ proc();
+ }finally{
+ checkCompleteGuard--;
+ }
+ if(execComplete()){
+ signal("idle", []);
+ }
+ },
+
+ checkComplete = function(){
+ // keep going through the execQ as long as at least one factory is executed
+ // plugins, recursion, cached modules all make for many execution path possibilities
+ if(checkCompleteGuard){
+ return;
+ }
+ guardCheckComplete(function(){
+ checkDojoRequirePlugin();
+ for(var currentDefOrder, module, i = 0; i < execQ.length;){
+ currentDefOrder = defOrder;
+ module = execQ[i];
+ execModule(module);
+ if(currentDefOrder!=defOrder){
+ // defOrder was bumped one or more times indicating something was executed (note, this indicates
+ // the execQ was modified, maybe a lot (for example a later module causes an earlier module to execute)
+ checkDojoRequirePlugin();
+ i = 0;
+ }else{
+ // nothing happened; check the next module in the exec queue
+ i++;
+ }
+ }
+ });
+ };
+
+
+ if( 0 ){
+ req.undef = function(moduleId, referenceModule){
+ // In order to reload a module, it must be undefined (this routine) and then re-requested.
+ // This is useful for testing frameworks (at least).
+ var module = getModule(moduleId, referenceModule);
+ setArrived(module);
+ delete modules[module.mid];
+ };
+ }
+
+ if( 1 ){
+ if(has("dojo-loader-eval-hint-url")===undefined){
+ has.add("dojo-loader-eval-hint-url", 1);
+ }
+
+ var fixupUrl= function(url){
+ url += ""; // make sure url is a Javascript string (some paths may be a Java string)
+ return url + (cacheBust ? ((/\?/.test(url) ? "&" : "?") + cacheBust) : "");
+ },
+
+ injectPlugin = function(
+ module
+ ){
+ // injects the plugin module given by module; may have to inject the plugin itself
+ var plugin = module.plugin;
+
+ if(plugin.executed === executed && !plugin.load){
+ // executed the module not knowing it was a plugin
+ promoteModuleToPlugin(plugin);
+ }
+
+ var onLoad = function(def){
+ module.result = def;
+ setArrived(module);
+ finishExec(module);
+ checkComplete();
+ };
+
+ if(plugin.load){
+ plugin.load(module.prid, module.req, onLoad);
+ }else if(plugin.loadQ){
+ plugin.loadQ.push(module);
+ }else{
+ // the unshift instead of push is important: we don't want plugins to execute as
+ // dependencies of some other module because this may cause circles when the plugin
+ // loadQ is run; also, generally, we want plugins to run early since they may load
+ // several other modules and therefore can potentially unblock many modules
+ plugin.loadQ = [module];
+ execQ.unshift(plugin);
+ injectModule(plugin);
+ }
+ },
+
+ // for IE, injecting a module may result in a recursive execution if the module is in the cache
+
+ cached = 0,
+
+ injectingModule = 0,
+
+ injectingCachedModule = 0,
+
+ evalModuleText = function(text, module){
+ // see def() for the injectingCachedModule bracket; it simply causes a short, safe curcuit
+ if(has("config-stripStrict")){
+ text = text.replace(/"use strict"/g, '');
+ }
+ injectingCachedModule = 1;
+ if(has("config-dojo-loader-catches")){
+ try{
+ if(text===cached){
+ cached.call(null);
+ }else{
+ req.eval(text, has("dojo-loader-eval-hint-url") ? module.url : module.mid);
+ }
+ }catch(e){
+ signal(error, makeError("evalModuleThrew", module));
+ }
+ }else{
+ if(text===cached){
+ cached.call(null);
+ }else{
+ req.eval(text, has("dojo-loader-eval-hint-url") ? module.url : module.mid);
+ }
+ }
+ injectingCachedModule = 0;
+ },
+
+ injectModule = function(module){
+ // Inject the module. In the browser environment, this means appending a script element into
+ // the document; in other environments, it means loading a file.
+ //
+ // If in synchronous mode, then get the module synchronously if it's not xdomainLoading.
+
+ var mid = module.mid,
+ url = module.url;
+ if(module.executed || module.injected || waiting[mid] || (module.url && ((module.pack && waiting[module.url]===module.pack) || waiting[module.url]==1))){
+ return;
+ }
+ setRequested(module);
+
+ if( 0 ){
+ var viaCombo = 0;
+ if(module.plugin && module.plugin.isCombo){
+ // a combo plugin; therefore, must be handled by combo service
+ // the prid should have already been converted to a URL (if required by the plugin) during
+ // the normalze process; in any event, there is no way for the loader to know how to
+ // to the conversion; therefore the third argument is zero
+ req.combo.add(module.plugin.mid, module.prid, 0, req);
+ viaCombo = 1;
+ }else if(!module.plugin){
+ viaCombo = req.combo.add(0, module.mid, module.url, req);
+ }
+ if(viaCombo){
+ comboPending= 1;
+ return;
+ }
+ }
+
+ if(module.plugin){
+ injectPlugin(module);
+ return;
+ } // else a normal module (not a plugin)
+
+
+ var onLoadCallback = function(){
+ runDefQ(module);
+ if(module.injected !== arrived){
+ // the script that contained the module arrived and has been executed yet
+ // nothing was added to the defQ (so it wasn't an AMD module) and the module
+ // wasn't marked as arrived by dojo.provide (so it wasn't a v1.6- module);
+ // therefore, it must not have been a module; adjust state accordingly
+ setArrived(module);
+ mix(module, nonModuleProps);
+ req.trace("loader-define-nonmodule", [module.url]);
+ }
+
+ if( 1 && legacyMode){
+ // must call checkComplete even in for sync loader because we may be in xdomainLoading mode;
+ // but, if xd loading, then don't call checkComplete until out of the current sync traversal
+ // in order to preserve order of execution of the dojo.required modules
+ !syncExecStack.length && checkComplete();
+ }else{
+ checkComplete();
+ }
+ };
+ cached = cache[mid] || cache[urlKeyPrefix + module.url];
+ if(cached){
+ req.trace("loader-inject", ["cache", module.mid, url]);
+ evalModuleText(cached, module);
+ onLoadCallback();
+ return;
+ }
+ if( 1 && legacyMode){
+ if(module.isXd){
+ // switch to async mode temporarily; if current legacyMode!=sync, then is must be one of {legacyAsync, xd, false}
+ legacyMode==sync && (legacyMode = xd);
+ // fall through and load via script injection
+ }else if(module.isAmd && legacyMode!=sync){
+ // fall through and load via script injection
+ }else{
+ // mode may be sync, xd/legacyAsync, or async; module may be AMD or legacy; but module is always located on the same domain
+ var xhrCallback = function(text){
+ if(legacyMode==sync){
+ // the top of syncExecStack gives the current synchronously executing module; the loader needs
+ // to know this if it has to switch to async loading in the middle of evaluating a legacy module
+ // this happens when a modules dojo.require's a module that must be loaded async because it's xdomain
+ // (using unshift/shift because there is no back() methods for Javascript arrays)
+ syncExecStack.unshift(module);
+ evalModuleText(text, module);
+ syncExecStack.shift();
+
+ // maybe the module was an AMD module
+ runDefQ(module);
+
+ // legacy modules never get to defineModule() => cjs and injected never set; also evaluation implies executing
+ if(!module.cjs){
+ setArrived(module);
+ finishExec(module);
+ }
+
+ if(module.finish){
+ // while synchronously evaluating this module, dojo.require was applied referencing a module
+ // that had to be loaded async; therefore, the loader stopped answering all dojo.require
+ // requests so they could be answered completely in the correct sequence; module.finish gives
+ // the list of dojo.requires that must be re-applied once all target modules are available;
+ // make a synthetic module to execute the dojo.require's in the correct order
+
+ // compute a guarnateed-unique mid for the synthetic finish module; remember the finish vector; remove it from the reference module
+ // TODO: can we just leave the module.finish...what's it hurting?
+ var finishMid = mid + "*finish",
+ finish = module.finish;
+ delete module.finish;
+
+ def(finishMid, ["dojo", ("dojo/require!" + finish.join(",")).replace(/\./g, "/")], function(dojo){
+ forEach(finish, function(mid){ dojo.require(mid); });
+ });
+ // unshift, not push, which causes the current traversal to be reattempted from the top
+ execQ.unshift(getModule(finishMid));
+ }
+ onLoadCallback();
+ }else{
+ text = transformToAmd(module, text);
+ if(text){
+ evalModuleText(text, module);
+ onLoadCallback();
+ }else{
+ // if transformToAmd returned falsy, then the module was already AMD and it can be script-injected
+ // do so to improve debugability(even though it means another download...which probably won't happen with a good browser cache)
+ injectingModule = module;
+ req.injectUrl(fixupUrl(url), onLoadCallback, module);
+ injectingModule = 0;
+ }
+ }
+ };
+
+ req.trace("loader-inject", ["xhr", module.mid, url, legacyMode!=sync]);
+ if(has("config-dojo-loader-catches")){
+ try{
+ req.getText(url, legacyMode!=sync, xhrCallback);
+ }catch(e){
+ signal(error, makeError("xhrInjectFailed", [module, e]));
+ }
+ }else{
+ req.getText(url, legacyMode!=sync, xhrCallback);
+ }
+ return;
+ }
+ } // else async mode or fell through in xdomain loading mode; either way, load by script injection
+ req.trace("loader-inject", ["script", module.mid, url]);
+ injectingModule = module;
+ req.injectUrl(fixupUrl(url), onLoadCallback, module);
+ injectingModule = 0;
+ },
+
+ defineModule = function(module, deps, def){
+ req.trace("loader-define-module", [module.mid, deps]);
+
+ if( 0 && module.plugin && module.plugin.isCombo){
+ // the module is a plugin resource loaded by the combo service
+ // note: check for module.plugin should be enough since normal plugin resources should
+ // not follow this path; module.plugin.isCombo is future-proofing belt and suspenders
+ module.result = isFunction(def) ? def() : def;
+ setArrived(module);
+ finishExec(module);
+ return module;
+ };
+
+ var mid = module.mid;
+ if(module.injected === arrived){
+ signal(error, makeError("multipleDefine", module));
+ return module;
+ }
+ mix(module, {
+ deps: deps,
+ def: def,
+ cjs: {
+ id: module.mid,
+ uri: module.url,
+ exports: (module.result = {}),
+ setExports: function(exports){
+ module.cjs.exports = exports;
+ },
+ config:function(){
+ return module.config;
+ }
+ }
+ });
+
+ // resolve deps with respect to this module
+ for(var i = 0; i < deps.length; i++){
+ deps[i] = getModule(deps[i], module);
+ }
+
+ if( 1 && legacyMode && !waiting[mid]){
+ // the module showed up without being asked for; it was probably in a
+ //
+ return new NodeList(); // dojo/NodeList
+ };
+ =====*/
+
+ // the query that is returned from this module is slightly different than dojo.query,
+ // because dojo.query has to maintain backwards compatibility with returning a
+ // true array which has performance problems. The query returned from the module
+ // does not use true arrays, but rather inherits from Array, making it much faster to
+ // instantiate.
+ dojo.query = queryForEngine(defaultEngine, function(array){
+ // call it without the new operator to invoke the back-compat behavior that returns a true array
+ return NodeList(array); // dojo/NodeList
+ });
+
+ query.load = function(id, parentRequire, loaded){
+ // summary:
+ // can be used as AMD plugin to conditionally load new query engine
+ // example:
+ // | require(["dojo/query!custom"], function(qsa){
+ // | // loaded selector/custom.js as engine
+ // | qsa("#foobar").forEach(...);
+ // | });
+ loader.load(id, parentRequire, function(engine){
+ loaded(queryForEngine(engine, NodeList));
+ });
+ };
+
+ dojo._filterQueryResult = query._filterResult = function(nodes, selector, root){
+ return new NodeList(query.filter(nodes, selector, root));
+ };
+ dojo.NodeList = query.NodeList = NodeList;
+ return query;
+});
+
+},
+'dojo/has':function(){
+define(["require", "module"], function(require, module){
+ // module:
+ // dojo/has
+ // summary:
+ // Defines the has.js API and several feature tests used by dojo.
+ // description:
+ // This module defines the has API as described by the project has.js with the following additional features:
+ //
+ // - the has test cache is exposed at has.cache.
+ // - the method has.add includes a forth parameter that controls whether or not existing tests are replaced
+ // - the loader's has cache may be optionally copied into this module's has cahce.
+ //
+ // This module adopted from https://github.com/phiggins42/has.js; thanks has.js team!
+
+ // try to pull the has implementation from the loader; both the dojo loader and bdLoad provide one
+ // if using a foreign loader, then the has cache may be initialized via the config object for this module
+ // WARNING: if a foreign loader defines require.has to be something other than the has.js API, then this implementation fail
+ var has = require.has || function(){};
+ if(! 1 ){
+ var
+ isBrowser =
+ // the most fundamental decision: are we in the browser?
+ typeof window != "undefined" &&
+ typeof location != "undefined" &&
+ typeof document != "undefined" &&
+ window.location == location && window.document == document,
+
+ // has API variables
+ global = this,
+ doc = isBrowser && document,
+ element = doc && doc.createElement("DiV"),
+ cache = (module.config && module.config()) || {};
+
+ has = function(name){
+ // summary:
+ // Return the current value of the named feature.
+ //
+ // name: String|Integer
+ // The name (if a string) or identifier (if an integer) of the feature to test.
+ //
+ // description:
+ // Returns the value of the feature named by name. The feature must have been
+ // previously added to the cache by has.add.
+
+ return typeof cache[name] == "function" ? (cache[name] = cache[name](global, doc, element)) : cache[name]; // Boolean
+ };
+
+ has.cache = cache;
+
+ has.add = function(name, test, now, force){
+ // summary:
+ // Register a new feature test for some named feature.
+ // name: String|Integer
+ // The name (if a string) or identifier (if an integer) of the feature to test.
+ // test: Function
+ // A test function to register. If a function, queued for testing until actually
+ // needed. The test function should return a boolean indicating
+ // the presence of a feature or bug.
+ // now: Boolean?
+ // Optional. Omit if `test` is not a function. Provides a way to immediately
+ // run the test and cache the result.
+ // force: Boolean?
+ // Optional. If the test already exists and force is truthy, then the existing
+ // test will be replaced; otherwise, add does not replace an existing test (that
+ // is, by default, the first test advice wins).
+ // example:
+ // A redundant test, testFn with immediate execution:
+ // | has.add("javascript", function(){ return true; }, true);
+ //
+ // example:
+ // Again with the redundantness. You can do this in your tests, but we should
+ // not be doing this in any internal has.js tests
+ // | has.add("javascript", true);
+ //
+ // example:
+ // Three things are passed to the testFunction. `global`, `document`, and a generic element
+ // from which to work your test should the need arise.
+ // | has.add("bug-byid", function(g, d, el){
+ // | // g == global, typically window, yadda yadda
+ // | // d == document object
+ // | // el == the generic element. a `has` element.
+ // | return false; // fake test, byid-when-form-has-name-matching-an-id is slightly longer
+ // | });
+
+ (typeof cache[name]=="undefined" || force) && (cache[name]= test);
+ return now && has(name);
+ };
+
+ // since we're operating under a loader that doesn't provide a has API, we must explicitly initialize
+ // has as it would have otherwise been initialized by the dojo loader; use has.add to the builder
+ // can optimize these away iff desired
+ 1 || has.add("host-browser", isBrowser);
+ 1 || has.add("dom", isBrowser);
+ 1 || has.add("dojo-dom-ready-api", 1);
+ 1 || has.add("dojo-sniff", 1);
+ }
+
+ if( 1 ){
+ // Common application level tests
+ has.add("dom-addeventlistener", !!document.addEventListener);
+ has.add("touch", "ontouchstart" in document);
+ // I don't know if any of these tests are really correct, just a rough guess
+ has.add("device-width", screen.availWidth || innerWidth);
+
+ // Tests for DOMNode.attributes[] behavior:
+ // - dom-attributes-explicit - attributes[] only lists explicitly user specified attributes
+ // - dom-attributes-specified-flag (IE8) - need to check attr.specified flag to skip attributes user didn't specify
+ // - Otherwise, in IE6-7. attributes[] will list hundreds of values, so need to do outerHTML to get attrs instead.
+ var form = document.createElement("form");
+ has.add("dom-attributes-explicit", form.attributes.length == 0); // W3C
+ has.add("dom-attributes-specified-flag", form.attributes.length > 0 && form.attributes.length < 40); // IE8
+ }
+
+ has.clearElement = function(element){
+ // summary:
+ // Deletes the contents of the element passed to test functions.
+ element.innerHTML= "";
+ return element;
+ };
+
+ has.normalize = function(id, toAbsMid){
+ // summary:
+ // Resolves id into a module id based on possibly-nested tenary expression that branches on has feature test value(s).
+ //
+ // toAbsMid: Function
+ // Resolves a relative module id into an absolute module id
+ var
+ tokens = id.match(/[\?:]|[^:\?]*/g), i = 0,
+ get = function(skip){
+ var term = tokens[i++];
+ if(term == ":"){
+ // empty string module name, resolves to 0
+ return 0;
+ }else{
+ // postfixed with a ? means it is a feature to branch on, the term is the name of the feature
+ if(tokens[i++] == "?"){
+ if(!skip && has(term)){
+ // matched the feature, get the first value from the options
+ return get();
+ }else{
+ // did not match, get the second value, passing over the first
+ get(true);
+ return get(skip);
+ }
+ }
+ // a module
+ return term || 0;
+ }
+ };
+ id = get();
+ return id && toAbsMid(id);
+ };
+
+ has.load = function(id, parentRequire, loaded){
+ // summary:
+ // Conditional loading of AMD modules based on a has feature test value.
+ // id: String
+ // Gives the resolved module id to load.
+ // parentRequire: Function
+ // The loader require function with respect to the module that contained the plugin resource in it's
+ // dependency list.
+ // loaded: Function
+ // Callback to loader that consumes result of plugin demand.
+
+ if(id){
+ parentRequire([id], loaded);
+ }else{
+ loaded();
+ }
+ };
+
+ return has;
+});
+
+},
+'dojo/_base/loader':function(){
+define(["./kernel", "../has", "require", "module", "./json", "./lang", "./array"], function(dojo, has, require, thisModule, json, lang, array) {
+ // module:
+ // dojo/_base/loader
+
+ // This module defines the v1.x synchronous loader API.
+
+ // signal the loader in sync mode...
+ //>>pure-amd
+
+ if (! 1 ){
+ console.error("cannot load the Dojo v1.x loader with a foreign loader");
+ return 0;
+ }
+
+ 1 || has.add("dojo-fast-sync-require", 1);
+
+
+ var makeErrorToken = function(id){
+ return {src:thisModule.id, id:id};
+ },
+
+ slashName = function(name){
+ return name.replace(/\./g, "/");
+ },
+
+ buildDetectRe = /\/\/>>built/,
+
+ dojoRequireCallbacks = [],
+ dojoRequireModuleStack = [],
+
+ dojoRequirePlugin = function(mid, require, loaded){
+ dojoRequireCallbacks.push(loaded);
+ array.forEach(mid.split(","), function(mid){
+ var module = getModule(mid, require.module);
+ dojoRequireModuleStack.push(module);
+ injectModule(module);
+ });
+ checkDojoRequirePlugin();
+ },
+
+ checkDojoRequirePlugin = ( 1 ?
+ // This version of checkDojoRequirePlugin makes the observation that all dojoRequireCallbacks can be released
+ // when all *non-dojo/require!, dojo/loadInit!* modules are either executed, not requested, or arrived. This is
+ // the case since there are no more modules the loader is waiting for, therefore, dojo/require! must have
+ // everything it needs on board.
+ //
+ // The potential weakness of this algorithm is that dojo/require will not execute callbacks until *all* dependency
+ // trees are ready. It is possible that some trees may be ready earlier than others, and this extra wait is non-optimal.
+ // Still, for big projects, this seems better than the original algorithm below that proved slow in some cases.
+ // Note, however, the original algorithm had the potential to execute partial trees, but that potential was never enabled.
+ // There are also other optimization available with the original algorithm that have not been explored.
+ function(){
+ var module, mid;
+ for(mid in modules){
+ module = modules[mid];
+ if(module.noReqPluginCheck===undefined){
+ // tag the module as either a loadInit or require plugin or not for future reference
+ module.noReqPluginCheck = /loadInit\!/.test(mid) || /require\!/.test(mid) ? 1 : 0;
+ }
+ if(!module.executed && !module.noReqPluginCheck && module.injected==requested){
+ return;
+ }
+ }
+
+ guardCheckComplete(function(){
+ var oldCallbacks = dojoRequireCallbacks;
+ dojoRequireCallbacks = [];
+ array.forEach(oldCallbacks, function(cb){cb(1);});
+ });
+ } : (function(){
+ // Note: this is the original checkDojoRequirePlugin that is much slower than the algorithm above. However, we know it
+ // works, so we leave it here in case the algorithm above fails in some corner case.
+ //
+ // checkDojoRequirePlugin inspects all of the modules demanded by a dojo/require! dependency
+ // to see if they have arrived. The loader does not release *any* of these modules to be instantiated
+ // until *all* of these modules are on board, thereby preventing the evaluation of a module with dojo.require's
+ // that reference modules that are not available.
+ //
+ // The algorithm works by traversing the dependency graphs (remember, there can be cycles so they are not trees)
+ // of each module in the dojoRequireModuleStack array (which contains the list of modules demanded by dojo/require!).
+ // The moment a single module is discovered that is missing, the algorithm gives up and indicates that not all
+ // modules are on board. dojo/loadInit! and dojo/require! are ignored because there dependencies are inserted
+ // directly in dojoRequireModuleStack. For example, if "your/module" module depends on "dojo/require!my/module", then
+ // *both* "dojo/require!my/module" and "my/module" will be in dojoRequireModuleStack. Obviously, if "my/module"
+ // is on board, then "dojo/require!my/module" is also satisfied, so the algorithm doesn't check for "dojo/require!my/module".
+ //
+ // Note: inserting a dojo/require! dependency in the dojoRequireModuleStack achieves nothing
+ // with the current algorithm; however, having such modules present makes it possible to optimize the algorithm
+ //
+ // Note: prior versions of this algorithm had an optimization that signaled loaded on dojo/require! dependencies
+ // individually (rather than waiting for them all to be resolved). The implementation proved problematic with cycles
+ // and plugins. However, it is possible to reattach that strategy in the future.
+
+ // a set from module-id to {undefined | 1 | 0}, where...
+ // undefined => the module has not been inspected
+ // 0 => the module or at least one of its dependencies has not arrived
+ // 1 => the module is a loadInit! or require! plugin resource, or is currently being traversed (therefore, assume
+ // OK until proven otherwise), or has been completely traversed and all dependencies have arrived
+
+ var touched,
+ traverse = function(m){
+ touched[m.mid] = 1;
+ for(var t, module, deps = m.deps || [], i= 0; i a built module, always AMD
+ // extractResult==0 => no sync API
+ return 0;
+ }
+
+ // manufacture a synthetic module id that can never be a real mdule id (just like require does)
+ id = module.mid + "-*loadInit";
+
+ // construct the dojo/loadInit names vector which causes any relocated names to be defined as lexical variables under their not-relocated name
+ // the dojo/loadInit plugin assumes the first name in names is "dojo"
+
+ for(var p in getModule("dojo", module).result.scopeMap){
+ names.push(p);
+ namesAsStrings.push('"' + p + '"');
+ }
+
+ // rewrite the module as a synthetic dojo/loadInit plugin resource + the module expressed as an AMD module that depends on this synthetic resource
+ // don't have to map dojo/init since that will occur when the dependency is resolved
+ return "// xdomain rewrite of " + module.mid + "\n" +
+ "define('" + id + "',{\n" +
+ "\tnames:" + dojo.toJson(names) + ",\n" +
+ "\tdef:function(" + names.join(",") + "){" + extractResult[1] + "}" +
+ "});\n\n" +
+ "define(" + dojo.toJson(names.concat(["dojo/loadInit!"+id])) + ", function(" + names.join(",") + "){\n" + extractResult[0] + "});";
+ },
+
+ loaderVars = require.initSyncLoader(dojoRequirePlugin, checkDojoRequirePlugin, transformToAmd),
+
+ sync =
+ loaderVars.sync,
+
+ requested =
+ loaderVars.requested,
+
+ arrived =
+ loaderVars.arrived,
+
+ nonmodule =
+ loaderVars.nonmodule,
+
+ executing =
+ loaderVars.executing,
+
+ executed =
+ loaderVars.executed,
+
+ syncExecStack =
+ loaderVars.syncExecStack,
+
+ modules =
+ loaderVars.modules,
+
+ execQ =
+ loaderVars.execQ,
+
+ getModule =
+ loaderVars.getModule,
+
+ injectModule =
+ loaderVars.injectModule,
+
+ setArrived =
+ loaderVars.setArrived,
+
+ signal =
+ loaderVars.signal,
+
+ finishExec =
+ loaderVars.finishExec,
+
+ execModule =
+ loaderVars.execModule,
+
+ getLegacyMode =
+ loaderVars.getLegacyMode,
+
+ guardCheckComplete =
+ loaderVars.guardCheckComplete;
+
+ // there is exactly one dojoRequirePlugin among possibly-many dojo/_base/loader's (owing to mapping)
+ dojoRequirePlugin = loaderVars.dojoRequirePlugin;
+
+ dojo.provide = function(mid){
+ var executingModule = syncExecStack[0],
+ module = lang.mixin(getModule(slashName(mid), require.module), {
+ executed:executing,
+ result:lang.getObject(mid, true)
+ });
+ setArrived(module);
+ if(executingModule){
+ (executingModule.provides || (executingModule.provides = [])).push(function(){
+ module.result = lang.getObject(mid);
+ delete module.provides;
+ module.executed!==executed && finishExec(module);
+ });
+ }// else dojo.provide called not consequent to loading; therefore, give up trying to publish module value to loader namespace
+ return module.result;
+ };
+
+ has.add("config-publishRequireResult", 1, 0, 0);
+
+ dojo.require = function(moduleName, omitModuleCheck) {
+ // summary:
+ // loads a Javascript module from the appropriate URI
+ //
+ // moduleName: String
+ // module name to load, using periods for separators,
+ // e.g. "dojo.date.locale". Module paths are de-referenced by dojo's
+ // internal mapping of locations to names and are disambiguated by
+ // longest prefix. See `dojo.registerModulePath()` for details on
+ // registering new modules.
+ //
+ // omitModuleCheck: Boolean?
+ // if `true`, omitModuleCheck skips the step of ensuring that the
+ // loaded file actually defines the symbol it is referenced by.
+ // For example if it called as `dojo.require("a.b.c")` and the
+ // file located at `a/b/c.js` does not define an object `a.b.c`,
+ // and exception will be throws whereas no exception is raised
+ // when called as `dojo.require("a.b.c", true)`
+ //
+ // description:
+ // Modules are loaded via dojo.require by using one of two loaders: the normal loader
+ // and the xdomain loader. The xdomain loader is used when dojo was built with a
+ // custom build that specified loader=xdomain and the module lives on a modulePath
+ // that is a whole URL, with protocol and a domain. The versions of Dojo that are on
+ // the Google and AOL CDNs use the xdomain loader.
+ //
+ // If the module is loaded via the xdomain loader, it is an asynchronous load, since
+ // the module is added via a dynamically created script tag. This
+ // means that dojo.require() can return before the module has loaded. However, this
+ // should only happen in the case where you do dojo.require calls in the top-level
+ // HTML page, or if you purposely avoid the loader checking for dojo.require
+ // dependencies in your module by using a syntax like dojo["require"] to load the module.
+ //
+ // Sometimes it is useful to not have the loader detect the dojo.require calls in the
+ // module so that you can dynamically load the modules as a result of an action on the
+ // page, instead of right at module load time.
+ //
+ // Also, for script blocks in an HTML page, the loader does not pre-process them, so
+ // it does not know to download the modules before the dojo.require calls occur.
+ //
+ // So, in those two cases, when you want on-the-fly module loading or for script blocks
+ // in the HTML page, special care must be taken if the dojo.required code is loaded
+ // asynchronously. To make sure you can execute code that depends on the dojo.required
+ // modules, be sure to add the code that depends on the modules in a dojo.addOnLoad()
+ // callback. dojo.addOnLoad waits for all outstanding modules to finish loading before
+ // executing.
+ //
+ // This type of syntax works with both xdomain and normal loaders, so it is good
+ // practice to always use this idiom for on-the-fly code loading and in HTML script
+ // blocks. If at some point you change loaders and where the code is loaded from,
+ // it will all still work.
+ //
+ // More on how dojo.require
+ // `dojo.require("A.B")` first checks to see if symbol A.B is
+ // defined. If it is, it is simply returned (nothing to do).
+ //
+ // If it is not defined, it will look for `A/B.js` in the script root
+ // directory.
+ //
+ // `dojo.require` throws an exception if it cannot find a file
+ // to load, or if the symbol `A.B` is not defined after loading.
+ //
+ // It returns the object `A.B`, but note the caveats above about on-the-fly loading and
+ // HTML script blocks when the xdomain loader is loading a module.
+ //
+ // `dojo.require()` does nothing about importing symbols into
+ // the current namespace. It is presumed that the caller will
+ // take care of that.
+ //
+ // example:
+ // To use dojo.require in conjunction with dojo.ready:
+ //
+ // | dojo.require("foo");
+ // | dojo.require("bar");
+ // | dojo.addOnLoad(function(){
+ // | //you can now safely do something with foo and bar
+ // | });
+ //
+ // example:
+ // For example, to import all symbols into a local block, you might write:
+ //
+ // | with (dojo.require("A.B")) {
+ // | ...
+ // | }
+ //
+ // And to import just the leaf symbol to a local variable:
+ //
+ // | var B = dojo.require("A.B");
+ // | ...
+ //
+ // returns:
+ // the required namespace object
+ function doRequire(mid, omitModuleCheck){
+ var module = getModule(slashName(mid), require.module);
+ if(syncExecStack.length && syncExecStack[0].finish){
+ // switched to async loading in the middle of evaluating a legacy module; stop
+ // applying dojo.require so the remaining dojo.requires are applied in order
+ syncExecStack[0].finish.push(mid);
+ return undefined;
+ }
+
+ // recall module.executed has values {0, executing, executed}; therefore, truthy indicates executing or executed
+ if(module.executed){
+ return module.result;
+ }
+ omitModuleCheck && (module.result = nonmodule);
+
+ // rcg...why here and in two lines??
+ var currentMode = getLegacyMode();
+
+ // recall, in sync mode to inject is to *eval* the module text
+ // if the module is a legacy module, this is the same as executing
+ // but if the module is an AMD module, this means defining, not executing
+ injectModule(module);
+ // the inject may have changed the mode
+ currentMode = getLegacyMode();
+
+ // in sync mode to dojo.require is to execute
+ if(module.executed!==executed && module.injected===arrived){
+ // the module was already here before injectModule was called probably finishing up a xdomain
+ // load, but maybe a module given to the loader directly rather than having the loader retrieve it
+
+ loaderVars.guardCheckComplete(function(){
+ execModule(module);
+ });
+ }
+ if(module.executed){
+ return module.result;
+ }
+
+ if(currentMode==sync){
+ // the only way to get here is in sync mode and dojo.required a module that
+ // * was loaded async in the injectModule application a few lines up
+ // * was an AMD module that had deps that are being loaded async and therefore couldn't execute
+ if(module.cjs){
+ // the module was an AMD module; unshift, not push, which causes the current traversal to be reattempted from the top
+ execQ.unshift(module);
+ }else{
+ // the module was a legacy module
+ syncExecStack.length && (syncExecStack[0].finish= [mid]);
+ }
+ }else{
+ // the loader wasn't in sync mode on entry; probably async mode; therefore, no expectation of getting
+ // the module value synchronously; make sure it gets executed though
+ execQ.push(module);
+ }
+
+ return undefined;
+ }
+
+ var result = doRequire(moduleName, omitModuleCheck);
+ if(has("config-publishRequireResult") && !lang.exists(moduleName) && result!==undefined){
+ lang.setObject(moduleName, result);
+ }
+ return result;
+ };
+
+ dojo.loadInit = function(f) {
+ f();
+ };
+
+ dojo.registerModulePath = function(/*String*/moduleName, /*String*/prefix){
+ // summary:
+ // Maps a module name to a path
+ // description:
+ // An unregistered module is given the default path of ../[module],
+ // relative to Dojo root. For example, module acme is mapped to
+ // ../acme. If you want to use a different module name, use
+ // dojo.registerModulePath.
+ // example:
+ // If your dojo.js is located at this location in the web root:
+ // | /myapp/js/dojo/dojo/dojo.js
+ // and your modules are located at:
+ // | /myapp/js/foo/bar.js
+ // | /myapp/js/foo/baz.js
+ // | /myapp/js/foo/thud/xyzzy.js
+ // Your application can tell Dojo to locate the "foo" namespace by calling:
+ // | dojo.registerModulePath("foo", "../../foo");
+ // At which point you can then use dojo.require() to load the
+ // modules (assuming they provide() the same things which are
+ // required). The full code might be:
+ // |
+ // |
+
+ var paths = {};
+ paths[moduleName.replace(/\./g, "/")] = prefix;
+ require({paths:paths});
+ };
+
+ dojo.platformRequire = function(/*Object*/modMap){
+ // summary:
+ // require one or more modules based on which host environment
+ // Dojo is currently operating in
+ // description:
+ // This method takes a "map" of arrays which one can use to
+ // optionally load dojo modules. The map is indexed by the
+ // possible dojo.name_ values, with two additional values:
+ // "default" and "common". The items in the "default" array will
+ // be loaded if none of the other items have been choosen based on
+ // dojo.name_, set by your host environment. The items in the
+ // "common" array will *always* be loaded, regardless of which
+ // list is chosen.
+ // example:
+ // | dojo.platformRequire({
+ // | browser: [
+ // | "foo.sample", // simple module
+ // | "foo.test",
+ // | ["foo.bar.baz", true] // skip object check in _loadModule (dojo.require)
+ // | ],
+ // | default: [ "foo.sample._base" ],
+ // | common: [ "important.module.common" ]
+ // | });
+
+ var result = (modMap.common || []).concat(modMap[dojo._name] || modMap["default"] || []),
+ temp;
+ while(result.length){
+ if(lang.isArray(temp = result.shift())){
+ dojo.require.apply(dojo, temp);
+ }else{
+ dojo.require(temp);
+ }
+ }
+ };
+
+ dojo.requireIf = dojo.requireAfterIf = function(/*Boolean*/ condition, /*String*/ moduleName, /*Boolean?*/omitModuleCheck){
+ // summary:
+ // If the condition is true then call `dojo.require()` for the specified
+ // resource
+ //
+ // example:
+ // | dojo.requireIf(dojo.isBrowser, "my.special.Module");
+
+ if(condition){
+ dojo.require(moduleName, omitModuleCheck);
+ }
+ };
+
+ dojo.requireLocalization = function(/*String*/moduleName, /*String*/bundleName, /*String?*/locale){
+ require(["../i18n"], function(i18n){
+ i18n.getLocalization(moduleName, bundleName, locale);
+ });
+ };
+
+ return {
+ // summary:
+ // This module defines the v1.x synchronous loader API.
+
+ extractLegacyApiApplications:extractLegacyApiApplications,
+ require:dojoRequirePlugin,
+ loadInit:dojoLoadInitPlugin
+ };
+});
+
+},
+'dojo/json':function(){
+define(["./has"], function(has){
+ "use strict";
+ var hasJSON = typeof JSON != "undefined";
+ has.add("json-parse", hasJSON); // all the parsers work fine
+ // Firefox 3.5/Gecko 1.9 fails to use replacer in stringify properly https://bugzilla.mozilla.org/show_bug.cgi?id=509184
+ has.add("json-stringify", hasJSON && JSON.stringify({a:0}, function(k,v){return v||1;}) == '{"a":1}');
+
+ /*=====
+ return {
+ // summary:
+ // Functions to parse and serialize JSON
+
+ parse: function(str, strict){
+ // summary:
+ // Parses a [JSON](http://json.org) string to return a JavaScript object.
+ // description:
+ // This function follows [native JSON API](https://developer.mozilla.org/en/JSON)
+ // Throws for invalid JSON strings. This delegates to eval() if native JSON
+ // support is not available. By default this will evaluate any valid JS expression.
+ // With the strict parameter set to true, the parser will ensure that only
+ // valid JSON strings are parsed (otherwise throwing an error). Without the strict
+ // parameter, the content passed to this method must come
+ // from a trusted source.
+ // str:
+ // a string literal of a JSON item, for instance:
+ // `'{ "foo": [ "bar", 1, { "baz": "thud" } ] }'`
+ // strict:
+ // When set to true, this will ensure that only valid, secure JSON is ever parsed.
+ // Make sure this is set to true for untrusted content. Note that on browsers/engines
+ // without native JSON support, setting this to true will run slower.
+ },
+ stringify: function(value, replacer, spacer){
+ // summary:
+ // Returns a [JSON](http://json.org) serialization of an object.
+ // description:
+ // Returns a [JSON](http://json.org) serialization of an object.
+ // This function follows [native JSON API](https://developer.mozilla.org/en/JSON)
+ // Note that this doesn't check for infinite recursion, so don't do that!
+ // value:
+ // A value to be serialized.
+ // replacer:
+ // A replacer function that is called for each value and can return a replacement
+ // spacer:
+ // A spacer string to be used for pretty printing of JSON
+ // example:
+ // simple serialization of a trivial object
+ // | define(["dojo/json"], function(JSON){
+ // | var jsonStr = JSON.stringify({ howdy: "stranger!", isStrange: true });
+ // | doh.is('{"howdy":"stranger!","isStrange":true}', jsonStr);
+ }
+ };
+ =====*/
+
+ if(has("json-stringify")){
+ return JSON;
+ }else{
+ var escapeString = function(/*String*/str){
+ // summary:
+ // Adds escape sequences for non-visual characters, double quote and
+ // backslash and surrounds with double quotes to form a valid string
+ // literal.
+ return ('"' + str.replace(/(["\\])/g, '\\$1') + '"').
+ replace(/[\f]/g, "\\f").replace(/[\b]/g, "\\b").replace(/[\n]/g, "\\n").
+ replace(/[\t]/g, "\\t").replace(/[\r]/g, "\\r"); // string
+ };
+ return {
+ parse: has("json-parse") ? JSON.parse : function(str, strict){
+ if(strict && !/^([\s\[\{]*(?:"(?:\\.|[^"])+"|-?\d[\d\.]*(?:[Ee][+-]?\d+)?|null|true|false|)[\s\]\}]*(?:,|:|$))+$/.test(str)){
+ throw new SyntaxError("Invalid characters in JSON");
+ }
+ return eval('(' + str + ')');
+ },
+ stringify: function(value, replacer, spacer){
+ var undef;
+ if(typeof replacer == "string"){
+ spacer = replacer;
+ replacer = null;
+ }
+ function stringify(it, indent, key){
+ if(replacer){
+ it = replacer(key, it);
+ }
+ var val, objtype = typeof it;
+ if(objtype == "number"){
+ return isFinite(it) ? it + "" : "null";
+ }
+ if(objtype == "boolean"){
+ return it + "";
+ }
+ if(it === null){
+ return "null";
+ }
+ if(typeof it == "string"){
+ return escapeString(it);
+ }
+ if(objtype == "function" || objtype == "undefined"){
+ return undef; // undefined
+ }
+ // short-circuit for objects that support "json" serialization
+ // if they return "self" then just pass-through...
+ if(typeof it.toJSON == "function"){
+ return stringify(it.toJSON(key), indent, key);
+ }
+ if(it instanceof Date){
+ return '"{FullYear}-{Month+}-{Date}T{Hours}:{Minutes}:{Seconds}Z"'.replace(/\{(\w+)(\+)?\}/g, function(t, prop, plus){
+ var num = it["getUTC" + prop]() + (plus ? 1 : 0);
+ return num < 10 ? "0" + num : num;
+ });
+ }
+ if(it.valueOf() !== it){
+ // primitive wrapper, try again unwrapped:
+ return stringify(it.valueOf(), indent, key);
+ }
+ var nextIndent= spacer ? (indent + spacer) : "";
+ /* we used to test for DOM nodes and throw, but FF serializes them as {}, so cross-browser consistency is probably not efficiently attainable */
+
+ var sep = spacer ? " " : "";
+ var newLine = spacer ? "\n" : "";
+
+ // array
+ if(it instanceof Array){
+ var itl = it.length, res = [];
+ for(key = 0; key < itl; key++){
+ var obj = it[key];
+ val = stringify(obj, nextIndent, key);
+ if(typeof val != "string"){
+ val = "null";
+ }
+ res.push(newLine + nextIndent + val);
+ }
+ return "[" + res.join(",") + newLine + indent + "]";
+ }
+ // generic object code path
+ var output = [];
+ for(key in it){
+ var keyStr;
+ if(it.hasOwnProperty(key)){
+ if(typeof key == "number"){
+ keyStr = '"' + key + '"';
+ }else if(typeof key == "string"){
+ keyStr = escapeString(key);
+ }else{
+ // skip non-string or number keys
+ continue;
+ }
+ val = stringify(it[key], nextIndent, key);
+ if(typeof val != "string"){
+ // skip non-serializable values
+ continue;
+ }
+ // At this point, the most non-IE browsers don't get in this branch
+ // (they have native JSON), so push is definitely the way to
+ output.push(newLine + nextIndent + keyStr + ":" + sep + val);
+ }
+ }
+ return "{" + output.join(",") + newLine + indent + "}"; // String
+ }
+ return stringify(value, "", "");
+ }
+ };
+ }
+});
+
+},
+'dojo/_base/declare':function(){
+define(["./kernel", "../has", "./lang"], function(dojo, has, lang){
+ // module:
+ // dojo/_base/declare
+
+ var mix = lang.mixin, op = Object.prototype, opts = op.toString,
+ xtor = new Function, counter = 0, cname = "constructor";
+
+ function err(msg, cls){ throw new Error("declare" + (cls ? " " + cls : "") + ": " + msg); }
+
+ // C3 Method Resolution Order (see http://www.python.org/download/releases/2.3/mro/)
+ function c3mro(bases, className){
+ var result = [], roots = [{cls: 0, refs: []}], nameMap = {}, clsCount = 1,
+ l = bases.length, i = 0, j, lin, base, top, proto, rec, name, refs;
+
+ // build a list of bases naming them if needed
+ for(; i < l; ++i){
+ base = bases[i];
+ if(!base){
+ err("mixin #" + i + " is unknown. Did you use dojo.require to pull it in?", className);
+ }else if(opts.call(base) != "[object Function]"){
+ err("mixin #" + i + " is not a callable constructor.", className);
+ }
+ lin = base._meta ? base._meta.bases : [base];
+ top = 0;
+ // add bases to the name map
+ for(j = lin.length - 1; j >= 0; --j){
+ proto = lin[j].prototype;
+ if(!proto.hasOwnProperty("declaredClass")){
+ proto.declaredClass = "uniqName_" + (counter++);
+ }
+ name = proto.declaredClass;
+ if(!nameMap.hasOwnProperty(name)){
+ nameMap[name] = {count: 0, refs: [], cls: lin[j]};
+ ++clsCount;
+ }
+ rec = nameMap[name];
+ if(top && top !== rec){
+ rec.refs.push(top);
+ ++top.count;
+ }
+ top = rec;
+ }
+ ++top.count;
+ roots[0].refs.push(top);
+ }
+
+ // remove classes without external references recursively
+ while(roots.length){
+ top = roots.pop();
+ result.push(top.cls);
+ --clsCount;
+ // optimization: follow a single-linked chain
+ while(refs = top.refs, refs.length == 1){
+ top = refs[0];
+ if(!top || --top.count){
+ // branch or end of chain => do not end to roots
+ top = 0;
+ break;
+ }
+ result.push(top.cls);
+ --clsCount;
+ }
+ if(top){
+ // branch
+ for(i = 0, l = refs.length; i < l; ++i){
+ top = refs[i];
+ if(!--top.count){
+ roots.push(top);
+ }
+ }
+ }
+ }
+ if(clsCount){
+ err("can't build consistent linearization", className);
+ }
+
+ // calculate the superclass offset
+ base = bases[0];
+ result[0] = base ?
+ base._meta && base === result[result.length - base._meta.bases.length] ?
+ base._meta.bases.length : 1 : 0;
+
+ return result;
+ }
+
+ function inherited(args, a, f){
+ var name, chains, bases, caller, meta, base, proto, opf, pos,
+ cache = this._inherited = this._inherited || {};
+
+ // crack arguments
+ if(typeof args == "string"){
+ name = args;
+ args = a;
+ a = f;
+ }
+ f = 0;
+
+ caller = args.callee;
+ name = name || caller.nom;
+ if(!name){
+ err("can't deduce a name to call inherited()", this.declaredClass);
+ }
+
+ meta = this.constructor._meta;
+ bases = meta.bases;
+
+ pos = cache.p;
+ if(name != cname){
+ // method
+ if(cache.c !== caller){
+ // cache bust
+ pos = 0;
+ base = bases[0];
+ meta = base._meta;
+ if(meta.hidden[name] !== caller){
+ // error detection
+ chains = meta.chains;
+ if(chains && typeof chains[name] == "string"){
+ err("calling chained method with inherited: " + name, this.declaredClass);
+ }
+ // find caller
+ do{
+ meta = base._meta;
+ proto = base.prototype;
+ if(meta && (proto[name] === caller && proto.hasOwnProperty(name) || meta.hidden[name] === caller)){
+ break;
+ }
+ }while(base = bases[++pos]); // intentional assignment
+ pos = base ? pos : -1;
+ }
+ }
+ // find next
+ base = bases[++pos];
+ if(base){
+ proto = base.prototype;
+ if(base._meta && proto.hasOwnProperty(name)){
+ f = proto[name];
+ }else{
+ opf = op[name];
+ do{
+ proto = base.prototype;
+ f = proto[name];
+ if(f && (base._meta ? proto.hasOwnProperty(name) : f !== opf)){
+ break;
+ }
+ }while(base = bases[++pos]); // intentional assignment
+ }
+ }
+ f = base && f || op[name];
+ }else{
+ // constructor
+ if(cache.c !== caller){
+ // cache bust
+ pos = 0;
+ meta = bases[0]._meta;
+ if(meta && meta.ctor !== caller){
+ // error detection
+ chains = meta.chains;
+ if(!chains || chains.constructor !== "manual"){
+ err("calling chained constructor with inherited", this.declaredClass);
+ }
+ // find caller
+ while(base = bases[++pos]){ // intentional assignment
+ meta = base._meta;
+ if(meta && meta.ctor === caller){
+ break;
+ }
+ }
+ pos = base ? pos : -1;
+ }
+ }
+ // find next
+ while(base = bases[++pos]){ // intentional assignment
+ meta = base._meta;
+ f = meta ? meta.ctor : base;
+ if(f){
+ break;
+ }
+ }
+ f = base && f;
+ }
+
+ // cache the found super method
+ cache.c = f;
+ cache.p = pos;
+
+ // now we have the result
+ if(f){
+ return a === true ? f : f.apply(this, a || args);
+ }
+ // intentionally no return if a super method was not found
+ }
+
+ function getInherited(name, args){
+ if(typeof name == "string"){
+ return this.__inherited(name, args, true);
+ }
+ return this.__inherited(name, true);
+ }
+
+ function inherited__debug(args, a1, a2){
+ var f = this.getInherited(args, a1);
+ if(f){ return f.apply(this, a2 || a1 || args); }
+ // intentionally no return if a super method was not found
+ }
+
+ var inheritedImpl = dojo.config.isDebug ? inherited__debug : inherited;
+
+ // emulation of "instanceof"
+ function isInstanceOf(cls){
+ var bases = this.constructor._meta.bases;
+ for(var i = 0, l = bases.length; i < l; ++i){
+ if(bases[i] === cls){
+ return true;
+ }
+ }
+ return this instanceof cls;
+ }
+
+ function mixOwn(target, source){
+ // add props adding metadata for incoming functions skipping a constructor
+ for(var name in source){
+ if(name != cname && source.hasOwnProperty(name)){
+ target[name] = source[name];
+ }
+ }
+ if(has("bug-for-in-skips-shadowed")){
+ for(var extraNames= lang._extraNames, i= extraNames.length; i;){
+ name = extraNames[--i];
+ if(name != cname && source.hasOwnProperty(name)){
+ target[name] = source[name];
+ }
+ }
+ }
+ }
+
+ // implementation of safe mixin function
+ function safeMixin(target, source){
+ // summary:
+ // Mix in properties skipping a constructor and decorating functions
+ // like it is done by declare().
+ // target: Object
+ // Target object to accept new properties.
+ // source: Object
+ // Source object for new properties.
+ // description:
+ // This function is used to mix in properties like lang.mixin does,
+ // but it skips a constructor property and decorates functions like
+ // declare() does.
+ //
+ // It is meant to be used with classes and objects produced with
+ // declare. Functions mixed in with dojo.safeMixin can use
+ // this.inherited() like normal methods.
+ //
+ // This function is used to implement extend() method of a constructor
+ // produced with declare().
+ //
+ // example:
+ // | var A = declare(null, {
+ // | m1: function(){
+ // | console.log("A.m1");
+ // | },
+ // | m2: function(){
+ // | console.log("A.m2");
+ // | }
+ // | });
+ // | var B = declare(A, {
+ // | m1: function(){
+ // | this.inherited(arguments);
+ // | console.log("B.m1");
+ // | }
+ // | });
+ // | B.extend({
+ // | m2: function(){
+ // | this.inherited(arguments);
+ // | console.log("B.m2");
+ // | }
+ // | });
+ // | var x = new B();
+ // | dojo.safeMixin(x, {
+ // | m1: function(){
+ // | this.inherited(arguments);
+ // | console.log("X.m1");
+ // | },
+ // | m2: function(){
+ // | this.inherited(arguments);
+ // | console.log("X.m2");
+ // | }
+ // | });
+ // | x.m2();
+ // | // prints:
+ // | // A.m1
+ // | // B.m1
+ // | // X.m1
+
+ var name, t;
+ // add props adding metadata for incoming functions skipping a constructor
+ for(name in source){
+ t = source[name];
+ if((t !== op[name] || !(name in op)) && name != cname){
+ if(opts.call(t) == "[object Function]"){
+ // non-trivial function method => attach its name
+ t.nom = name;
+ }
+ target[name] = t;
+ }
+ }
+ if(has("bug-for-in-skips-shadowed")){
+ for(var extraNames= lang._extraNames, i= extraNames.length; i;){
+ name = extraNames[--i];
+ t = source[name];
+ if((t !== op[name] || !(name in op)) && name != cname){
+ if(opts.call(t) == "[object Function]"){
+ // non-trivial function method => attach its name
+ t.nom = name;
+ }
+ target[name] = t;
+ }
+ }
+ }
+ return target;
+ }
+
+ function extend(source){
+ declare.safeMixin(this.prototype, source);
+ return this;
+ }
+
+ function createSubclass(mixins){
+ return declare([this].concat(mixins));
+ }
+
+ // chained constructor compatible with the legacy declare()
+ function chainedConstructor(bases, ctorSpecial){
+ return function(){
+ var a = arguments, args = a, a0 = a[0], f, i, m,
+ l = bases.length, preArgs;
+
+ if(!(this instanceof a.callee)){
+ // not called via new, so force it
+ return applyNew(a);
+ }
+
+ //this._inherited = {};
+ // perform the shaman's rituals of the original declare()
+ // 1) call two types of the preamble
+ if(ctorSpecial && (a0 && a0.preamble || this.preamble)){
+ // full blown ritual
+ preArgs = new Array(bases.length);
+ // prepare parameters
+ preArgs[0] = a;
+ for(i = 0;;){
+ // process the preamble of the 1st argument
+ a0 = a[0];
+ if(a0){
+ f = a0.preamble;
+ if(f){
+ a = f.apply(this, a) || a;
+ }
+ }
+ // process the preamble of this class
+ f = bases[i].prototype;
+ f = f.hasOwnProperty("preamble") && f.preamble;
+ if(f){
+ a = f.apply(this, a) || a;
+ }
+ // one peculiarity of the preamble:
+ // it is called if it is not needed,
+ // e.g., there is no constructor to call
+ // let's watch for the last constructor
+ // (see ticket #9795)
+ if(++i == l){
+ break;
+ }
+ preArgs[i] = a;
+ }
+ }
+ // 2) call all non-trivial constructors using prepared arguments
+ for(i = l - 1; i >= 0; --i){
+ f = bases[i];
+ m = f._meta;
+ f = m ? m.ctor : f;
+ if(f){
+ f.apply(this, preArgs ? preArgs[i] : a);
+ }
+ }
+ // 3) continue the original ritual: call the postscript
+ f = this.postscript;
+ if(f){
+ f.apply(this, args);
+ }
+ };
+ }
+
+
+ // chained constructor compatible with the legacy declare()
+ function singleConstructor(ctor, ctorSpecial){
+ return function(){
+ var a = arguments, t = a, a0 = a[0], f;
+
+ if(!(this instanceof a.callee)){
+ // not called via new, so force it
+ return applyNew(a);
+ }
+
+ //this._inherited = {};
+ // perform the shaman's rituals of the original declare()
+ // 1) call two types of the preamble
+ if(ctorSpecial){
+ // full blown ritual
+ if(a0){
+ // process the preamble of the 1st argument
+ f = a0.preamble;
+ if(f){
+ t = f.apply(this, t) || t;
+ }
+ }
+ f = this.preamble;
+ if(f){
+ // process the preamble of this class
+ f.apply(this, t);
+ // one peculiarity of the preamble:
+ // it is called even if it is not needed,
+ // e.g., there is no constructor to call
+ // let's watch for the last constructor
+ // (see ticket #9795)
+ }
+ }
+ // 2) call a constructor
+ if(ctor){
+ ctor.apply(this, a);
+ }
+ // 3) continue the original ritual: call the postscript
+ f = this.postscript;
+ if(f){
+ f.apply(this, a);
+ }
+ };
+ }
+
+ // plain vanilla constructor (can use inherited() to call its base constructor)
+ function simpleConstructor(bases){
+ return function(){
+ var a = arguments, i = 0, f, m;
+
+ if(!(this instanceof a.callee)){
+ // not called via new, so force it
+ return applyNew(a);
+ }
+
+ //this._inherited = {};
+ // perform the shaman's rituals of the original declare()
+ // 1) do not call the preamble
+ // 2) call the top constructor (it can use this.inherited())
+ for(; f = bases[i]; ++i){ // intentional assignment
+ m = f._meta;
+ f = m ? m.ctor : f;
+ if(f){
+ f.apply(this, a);
+ break;
+ }
+ }
+ // 3) call the postscript
+ f = this.postscript;
+ if(f){
+ f.apply(this, a);
+ }
+ };
+ }
+
+ function chain(name, bases, reversed){
+ return function(){
+ var b, m, f, i = 0, step = 1;
+ if(reversed){
+ i = bases.length - 1;
+ step = -1;
+ }
+ for(; b = bases[i]; i += step){ // intentional assignment
+ m = b._meta;
+ f = (m ? m.hidden : b.prototype)[name];
+ if(f){
+ f.apply(this, arguments);
+ }
+ }
+ };
+ }
+
+ // forceNew(ctor)
+ // return a new object that inherits from ctor.prototype but
+ // without actually running ctor on the object.
+ function forceNew(ctor){
+ // create object with correct prototype using a do-nothing
+ // constructor
+ xtor.prototype = ctor.prototype;
+ var t = new xtor;
+ xtor.prototype = null; // clean up
+ return t;
+ }
+
+ // applyNew(args)
+ // just like 'new ctor()' except that the constructor and its arguments come
+ // from args, which must be an array or an arguments object
+ function applyNew(args){
+ // create an object with ctor's prototype but without
+ // calling ctor on it.
+ var ctor = args.callee, t = forceNew(ctor);
+ // execute the real constructor on the new object
+ ctor.apply(t, args);
+ return t;
+ }
+
+ function declare(className, superclass, props){
+ // summary:
+ // Create a feature-rich constructor from compact notation.
+ // className: String?
+ // The optional name of the constructor (loosely, a "class")
+ // stored in the "declaredClass" property in the created prototype.
+ // It will be used as a global name for a created constructor.
+ // superclass: Function|Function[]
+ // May be null, a Function, or an Array of Functions. This argument
+ // specifies a list of bases (the left-most one is the most deepest
+ // base).
+ // props: Object
+ // An object whose properties are copied to the created prototype.
+ // Add an instance-initialization function by making it a property
+ // named "constructor".
+ // returns: dojo/_base/declare.__DeclareCreatedObject
+ // New constructor function.
+ // description:
+ // Create a constructor using a compact notation for inheritance and
+ // prototype extension.
+ //
+ // Mixin ancestors provide a type of multiple inheritance.
+ // Prototypes of mixin ancestors are copied to the new class:
+ // changes to mixin prototypes will not affect classes to which
+ // they have been mixed in.
+ //
+ // Ancestors can be compound classes created by this version of
+ // declare(). In complex cases all base classes are going to be
+ // linearized according to C3 MRO algorithm
+ // (see http://www.python.org/download/releases/2.3/mro/ for more
+ // details).
+ //
+ // "className" is cached in "declaredClass" property of the new class,
+ // if it was supplied. The immediate super class will be cached in
+ // "superclass" property of the new class.
+ //
+ // Methods in "props" will be copied and modified: "nom" property
+ // (the declared name of the method) will be added to all copied
+ // functions to help identify them for the internal machinery. Be
+ // very careful, while reusing methods: if you use the same
+ // function under different names, it can produce errors in some
+ // cases.
+ //
+ // It is possible to use constructors created "manually" (without
+ // declare()) as bases. They will be called as usual during the
+ // creation of an instance, their methods will be chained, and even
+ // called by "this.inherited()".
+ //
+ // Special property "-chains-" governs how to chain methods. It is
+ // a dictionary, which uses method names as keys, and hint strings
+ // as values. If a hint string is "after", this method will be
+ // called after methods of its base classes. If a hint string is
+ // "before", this method will be called before methods of its base
+ // classes.
+ //
+ // If "constructor" is not mentioned in "-chains-" property, it will
+ // be chained using the legacy mode: using "after" chaining,
+ // calling preamble() method before each constructor, if available,
+ // and calling postscript() after all constructors were executed.
+ // If the hint is "after", it is chained as a regular method, but
+ // postscript() will be called after the chain of constructors.
+ // "constructor" cannot be chained "before", but it allows
+ // a special hint string: "manual", which means that constructors
+ // are not going to be chained in any way, and programmer will call
+ // them manually using this.inherited(). In the latter case
+ // postscript() will be called after the construction.
+ //
+ // All chaining hints are "inherited" from base classes and
+ // potentially can be overridden. Be very careful when overriding
+ // hints! Make sure that all chained methods can work in a proposed
+ // manner of chaining.
+ //
+ // Once a method was chained, it is impossible to unchain it. The
+ // only exception is "constructor". You don't need to define a
+ // method in order to supply a chaining hint.
+ //
+ // If a method is chained, it cannot use this.inherited() because
+ // all other methods in the hierarchy will be called automatically.
+ //
+ // Usually constructors and initializers of any kind are chained
+ // using "after" and destructors of any kind are chained as
+ // "before". Note that chaining assumes that chained methods do not
+ // return any value: any returned value will be discarded.
+ //
+ // example:
+ // | declare("my.classes.bar", my.classes.foo, {
+ // | // properties to be added to the class prototype
+ // | someValue: 2,
+ // | // initialization function
+ // | constructor: function(){
+ // | this.myComplicatedObject = new ReallyComplicatedObject();
+ // | },
+ // | // other functions
+ // | someMethod: function(){
+ // | doStuff();
+ // | }
+ // | });
+ //
+ // example:
+ // | var MyBase = declare(null, {
+ // | // constructor, properties, and methods go here
+ // | // ...
+ // | });
+ // | var MyClass1 = declare(MyBase, {
+ // | // constructor, properties, and methods go here
+ // | // ...
+ // | });
+ // | var MyClass2 = declare(MyBase, {
+ // | // constructor, properties, and methods go here
+ // | // ...
+ // | });
+ // | var MyDiamond = declare([MyClass1, MyClass2], {
+ // | // constructor, properties, and methods go here
+ // | // ...
+ // | });
+ //
+ // example:
+ // | var F = function(){ console.log("raw constructor"); };
+ // | F.prototype.method = function(){
+ // | console.log("raw method");
+ // | };
+ // | var A = declare(F, {
+ // | constructor: function(){
+ // | console.log("A.constructor");
+ // | },
+ // | method: function(){
+ // | console.log("before calling F.method...");
+ // | this.inherited(arguments);
+ // | console.log("...back in A");
+ // | }
+ // | });
+ // | new A().method();
+ // | // will print:
+ // | // raw constructor
+ // | // A.constructor
+ // | // before calling F.method...
+ // | // raw method
+ // | // ...back in A
+ //
+ // example:
+ // | var A = declare(null, {
+ // | "-chains-": {
+ // | destroy: "before"
+ // | }
+ // | });
+ // | var B = declare(A, {
+ // | constructor: function(){
+ // | console.log("B.constructor");
+ // | },
+ // | destroy: function(){
+ // | console.log("B.destroy");
+ // | }
+ // | });
+ // | var C = declare(B, {
+ // | constructor: function(){
+ // | console.log("C.constructor");
+ // | },
+ // | destroy: function(){
+ // | console.log("C.destroy");
+ // | }
+ // | });
+ // | new C().destroy();
+ // | // prints:
+ // | // B.constructor
+ // | // C.constructor
+ // | // C.destroy
+ // | // B.destroy
+ //
+ // example:
+ // | var A = declare(null, {
+ // | "-chains-": {
+ // | constructor: "manual"
+ // | }
+ // | });
+ // | var B = declare(A, {
+ // | constructor: function(){
+ // | // ...
+ // | // call the base constructor with new parameters
+ // | this.inherited(arguments, [1, 2, 3]);
+ // | // ...
+ // | }
+ // | });
+ //
+ // example:
+ // | var A = declare(null, {
+ // | "-chains-": {
+ // | m1: "before"
+ // | },
+ // | m1: function(){
+ // | console.log("A.m1");
+ // | },
+ // | m2: function(){
+ // | console.log("A.m2");
+ // | }
+ // | });
+ // | var B = declare(A, {
+ // | "-chains-": {
+ // | m2: "after"
+ // | },
+ // | m1: function(){
+ // | console.log("B.m1");
+ // | },
+ // | m2: function(){
+ // | console.log("B.m2");
+ // | }
+ // | });
+ // | var x = new B();
+ // | x.m1();
+ // | // prints:
+ // | // B.m1
+ // | // A.m1
+ // | x.m2();
+ // | // prints:
+ // | // A.m2
+ // | // B.m2
+
+ // crack parameters
+ if(typeof className != "string"){
+ props = superclass;
+ superclass = className;
+ className = "";
+ }
+ props = props || {};
+
+ var proto, i, t, ctor, name, bases, chains, mixins = 1, parents = superclass;
+
+ // build a prototype
+ if(opts.call(superclass) == "[object Array]"){
+ // C3 MRO
+ bases = c3mro(superclass, className);
+ t = bases[0];
+ mixins = bases.length - t;
+ superclass = bases[mixins];
+ }else{
+ bases = [0];
+ if(superclass){
+ if(opts.call(superclass) == "[object Function]"){
+ t = superclass._meta;
+ bases = bases.concat(t ? t.bases : superclass);
+ }else{
+ err("base class is not a callable constructor.", className);
+ }
+ }else if(superclass !== null){
+ err("unknown base class. Did you use dojo.require to pull it in?", className);
+ }
+ }
+ if(superclass){
+ for(i = mixins - 1;; --i){
+ proto = forceNew(superclass);
+ if(!i){
+ // stop if nothing to add (the last base)
+ break;
+ }
+ // mix in properties
+ t = bases[i];
+ (t._meta ? mixOwn : mix)(proto, t.prototype);
+ // chain in new constructor
+ ctor = new Function;
+ ctor.superclass = superclass;
+ ctor.prototype = proto;
+ superclass = proto.constructor = ctor;
+ }
+ }else{
+ proto = {};
+ }
+ // add all properties
+ declare.safeMixin(proto, props);
+ // add constructor
+ t = props.constructor;
+ if(t !== op.constructor){
+ t.nom = cname;
+ proto.constructor = t;
+ }
+
+ // collect chains and flags
+ for(i = mixins - 1; i; --i){ // intentional assignment
+ t = bases[i]._meta;
+ if(t && t.chains){
+ chains = mix(chains || {}, t.chains);
+ }
+ }
+ if(proto["-chains-"]){
+ chains = mix(chains || {}, proto["-chains-"]);
+ }
+
+ // build ctor
+ t = !chains || !chains.hasOwnProperty(cname);
+ bases[0] = ctor = (chains && chains.constructor === "manual") ? simpleConstructor(bases) :
+ (bases.length == 1 ? singleConstructor(props.constructor, t) : chainedConstructor(bases, t));
+
+ // add meta information to the constructor
+ ctor._meta = {bases: bases, hidden: props, chains: chains,
+ parents: parents, ctor: props.constructor};
+ ctor.superclass = superclass && superclass.prototype;
+ ctor.extend = extend;
+ ctor.createSubclass = createSubclass;
+ ctor.prototype = proto;
+ proto.constructor = ctor;
+
+ // add "standard" methods to the prototype
+ proto.getInherited = getInherited;
+ proto.isInstanceOf = isInstanceOf;
+ proto.inherited = inheritedImpl;
+ proto.__inherited = inherited;
+
+ // add name if specified
+ if(className){
+ proto.declaredClass = className;
+ lang.setObject(className, ctor);
+ }
+
+ // build chains and add them to the prototype
+ if(chains){
+ for(name in chains){
+ if(proto[name] && typeof chains[name] == "string" && name != cname){
+ t = proto[name] = chain(name, bases, chains[name] === "after");
+ t.nom = name;
+ }
+ }
+ }
+ // chained methods do not return values
+ // no need to chain "invisible" functions
+
+ return ctor; // Function
+ }
+
+ /*=====
+ declare.__DeclareCreatedObject = {
+ // summary:
+ // dojo/_base/declare() returns a constructor `C`. `new C()` returns an Object with the following
+ // methods, in addition to the methods and properties specified via the arguments passed to declare().
+
+ inherited: function(name, args, newArgs){
+ // summary:
+ // Calls a super method.
+ // name: String?
+ // The optional method name. Should be the same as the caller's
+ // name. Usually "name" is specified in complex dynamic cases, when
+ // the calling method was dynamically added, undecorated by
+ // declare(), and it cannot be determined.
+ // args: Arguments
+ // The caller supply this argument, which should be the original
+ // "arguments".
+ // newArgs: Object?
+ // If "true", the found function will be returned without
+ // executing it.
+ // If Array, it will be used to call a super method. Otherwise
+ // "args" will be used.
+ // returns:
+ // Whatever is returned by a super method, or a super method itself,
+ // if "true" was specified as newArgs.
+ // description:
+ // This method is used inside method of classes produced with
+ // declare() to call a super method (next in the chain). It is
+ // used for manually controlled chaining. Consider using the regular
+ // chaining, because it is faster. Use "this.inherited()" only in
+ // complex cases.
+ //
+ // This method cannot me called from automatically chained
+ // constructors including the case of a special (legacy)
+ // constructor chaining. It cannot be called from chained methods.
+ //
+ // If "this.inherited()" cannot find the next-in-chain method, it
+ // does nothing and returns "undefined". The last method in chain
+ // can be a default method implemented in Object, which will be
+ // called last.
+ //
+ // If "name" is specified, it is assumed that the method that
+ // received "args" is the parent method for this call. It is looked
+ // up in the chain list and if it is found the next-in-chain method
+ // is called. If it is not found, the first-in-chain method is
+ // called.
+ //
+ // If "name" is not specified, it will be derived from the calling
+ // method (using a methoid property "nom").
+ //
+ // example:
+ // | var B = declare(A, {
+ // | method1: function(a, b, c){
+ // | this.inherited(arguments);
+ // | },
+ // | method2: function(a, b){
+ // | return this.inherited(arguments, [a + b]);
+ // | }
+ // | });
+ // | // next method is not in the chain list because it is added
+ // | // manually after the class was created.
+ // | B.prototype.method3 = function(){
+ // | console.log("This is a dynamically-added method.");
+ // | this.inherited("method3", arguments);
+ // | };
+ // example:
+ // | var B = declare(A, {
+ // | method: function(a, b){
+ // | var super = this.inherited(arguments, true);
+ // | // ...
+ // | if(!super){
+ // | console.log("there is no super method");
+ // | return 0;
+ // | }
+ // | return super.apply(this, arguments);
+ // | }
+ // | });
+ return {}; // Object
+ },
+
+ getInherited: function(name, args){
+ // summary:
+ // Returns a super method.
+ // name: String?
+ // The optional method name. Should be the same as the caller's
+ // name. Usually "name" is specified in complex dynamic cases, when
+ // the calling method was dynamically added, undecorated by
+ // declare(), and it cannot be determined.
+ // args: Arguments
+ // The caller supply this argument, which should be the original
+ // "arguments".
+ // returns:
+ // Returns a super method (Function) or "undefined".
+ // description:
+ // This method is a convenience method for "this.inherited()".
+ // It uses the same algorithm but instead of executing a super
+ // method, it returns it, or "undefined" if not found.
+ //
+ // example:
+ // | var B = declare(A, {
+ // | method: function(a, b){
+ // | var super = this.getInherited(arguments);
+ // | // ...
+ // | if(!super){
+ // | console.log("there is no super method");
+ // | return 0;
+ // | }
+ // | return super.apply(this, arguments);
+ // | }
+ // | });
+ return {}; // Object
+ },
+
+ isInstanceOf: function(cls){
+ // summary:
+ // Checks the inheritance chain to see if it is inherited from this
+ // class.
+ // cls: Function
+ // Class constructor.
+ // returns:
+ // "true", if this object is inherited from this class, "false"
+ // otherwise.
+ // description:
+ // This method is used with instances of classes produced with
+ // declare() to determine of they support a certain interface or
+ // not. It models "instanceof" operator.
+ //
+ // example:
+ // | var A = declare(null, {
+ // | // constructor, properties, and methods go here
+ // | // ...
+ // | });
+ // | var B = declare(null, {
+ // | // constructor, properties, and methods go here
+ // | // ...
+ // | });
+ // | var C = declare([A, B], {
+ // | // constructor, properties, and methods go here
+ // | // ...
+ // | });
+ // | var D = declare(A, {
+ // | // constructor, properties, and methods go here
+ // | // ...
+ // | });
+ // |
+ // | var a = new A(), b = new B(), c = new C(), d = new D();
+ // |
+ // | console.log(a.isInstanceOf(A)); // true
+ // | console.log(b.isInstanceOf(A)); // false
+ // | console.log(c.isInstanceOf(A)); // true
+ // | console.log(d.isInstanceOf(A)); // true
+ // |
+ // | console.log(a.isInstanceOf(B)); // false
+ // | console.log(b.isInstanceOf(B)); // true
+ // | console.log(c.isInstanceOf(B)); // true
+ // | console.log(d.isInstanceOf(B)); // false
+ // |
+ // | console.log(a.isInstanceOf(C)); // false
+ // | console.log(b.isInstanceOf(C)); // false
+ // | console.log(c.isInstanceOf(C)); // true
+ // | console.log(d.isInstanceOf(C)); // false
+ // |
+ // | console.log(a.isInstanceOf(D)); // false
+ // | console.log(b.isInstanceOf(D)); // false
+ // | console.log(c.isInstanceOf(D)); // false
+ // | console.log(d.isInstanceOf(D)); // true
+ return {}; // Object
+ },
+
+ extend: function(source){
+ // summary:
+ // Adds all properties and methods of source to constructor's
+ // prototype, making them available to all instances created with
+ // constructor. This method is specific to constructors created with
+ // declare().
+ // source: Object
+ // Source object which properties are going to be copied to the
+ // constructor's prototype.
+ // description:
+ // Adds source properties to the constructor's prototype. It can
+ // override existing properties.
+ //
+ // This method is similar to dojo.extend function, but it is specific
+ // to constructors produced by declare(). It is implemented
+ // using dojo.safeMixin, and it skips a constructor property,
+ // and properly decorates copied functions.
+ //
+ // example:
+ // | var A = declare(null, {
+ // | m1: function(){},
+ // | s1: "Popokatepetl"
+ // | });
+ // | A.extend({
+ // | m1: function(){},
+ // | m2: function(){},
+ // | f1: true,
+ // | d1: 42
+ // | });
+ }
+ };
+ =====*/
+
+ // For back-compat, remove for 2.0
+ dojo.safeMixin = declare.safeMixin = safeMixin;
+ dojo.declare = declare;
+
+ return declare;
+});
+
+},
+'dojo/dom':function(){
+define(["./sniff", "./_base/lang", "./_base/window"],
+ function(has, lang, win){
+ // module:
+ // dojo/dom
+
+ // FIXME: need to add unit tests for all the semi-public methods
+
+ if(has("ie") <= 7){
+ try{
+ document.execCommand("BackgroundImageCache", false, true);
+ }catch(e){
+ // sane browsers don't have cache "issues"
+ }
+ }
+
+ // =============================
+ // DOM Functions
+ // =============================
+
+ // the result object
+ var dom = {
+ // summary:
+ // This module defines the core dojo DOM API.
+ };
+
+ if(has("ie")){
+ dom.byId = function(id, doc){
+ if(typeof id != "string"){
+ return id;
+ }
+ var _d = doc || win.doc, te = id && _d.getElementById(id);
+ // attributes.id.value is better than just id in case the
+ // user has a name=id inside a form
+ if(te && (te.attributes.id.value == id || te.id == id)){
+ return te;
+ }else{
+ var eles = _d.all[id];
+ if(!eles || eles.nodeName){
+ eles = [eles];
+ }
+ // if more than 1, choose first with the correct id
+ var i = 0;
+ while((te = eles[i++])){
+ if((te.attributes && te.attributes.id && te.attributes.id.value == id) || te.id == id){
+ return te;
+ }
+ }
+ }
+ };
+ }else{
+ dom.byId = function(id, doc){
+ // inline'd type check.
+ // be sure to return null per documentation, to match IE branch.
+ return ((typeof id == "string") ? (doc || win.doc).getElementById(id) : id) || null; // DOMNode
+ };
+ }
+ /*=====
+ dom.byId = function(id, doc){
+ // summary:
+ // Returns DOM node with matching `id` attribute or falsy value (ex: null or undefined)
+ // if not found. If `id` is a DomNode, this function is a no-op.
+ //
+ // id: String|DOMNode
+ // A string to match an HTML id attribute or a reference to a DOM Node
+ //
+ // doc: Document?
+ // Document to work in. Defaults to the current value of
+ // dojo.doc. Can be used to retrieve
+ // node references from other documents.
+ //
+ // example:
+ // Look up a node by ID:
+ // | var n = dojo.byId("foo");
+ //
+ // example:
+ // Check if a node exists, and use it.
+ // | var n = dojo.byId("bar");
+ // | if(n){ doStuff() ... }
+ //
+ // example:
+ // Allow string or DomNode references to be passed to a custom function:
+ // | var foo = function(nodeOrId){
+ // | nodeOrId = dojo.byId(nodeOrId);
+ // | // ... more stuff
+ // | }
+ };
+ =====*/
+
+ dom.isDescendant = function(/*DOMNode|String*/ node, /*DOMNode|String*/ ancestor){
+ // summary:
+ // Returns true if node is a descendant of ancestor
+ // node: DOMNode|String
+ // string id or node reference to test
+ // ancestor: DOMNode|String
+ // string id or node reference of potential parent to test against
+ //
+ // example:
+ // Test is node id="bar" is a descendant of node id="foo"
+ // | if(dojo.isDescendant("bar", "foo")){ ... }
+
+ try{
+ node = dom.byId(node);
+ ancestor = dom.byId(ancestor);
+ while(node){
+ if(node == ancestor){
+ return true; // Boolean
+ }
+ node = node.parentNode;
+ }
+ }catch(e){ /* squelch, return false */ }
+ return false; // Boolean
+ };
+
+
+ // TODO: do we need this function in the base?
+
+ dom.setSelectable = function(/*DOMNode|String*/ node, /*Boolean*/ selectable){
+ // summary:
+ // Enable or disable selection on a node
+ // node: DOMNode|String
+ // id or reference to node
+ // selectable: Boolean
+ // state to put the node in. false indicates unselectable, true
+ // allows selection.
+ // example:
+ // Make the node id="bar" unselectable
+ // | dojo.setSelectable("bar");
+ // example:
+ // Make the node id="bar" selectable
+ // | dojo.setSelectable("bar", true);
+
+ node = dom.byId(node);
+ if(has("mozilla")){
+ node.style.MozUserSelect = selectable ? "" : "none";
+ }else if(has("khtml") || has("webkit")){
+ node.style.KhtmlUserSelect = selectable ? "auto" : "none";
+ }else if(has("ie")){
+ var v = (node.unselectable = selectable ? "" : "on"),
+ cs = node.getElementsByTagName("*"), i = 0, l = cs.length;
+ for(; i < l; ++i){
+ cs.item(i).unselectable = v;
+ }
+ }
+ //FIXME: else? Opera?
+ };
+
+ return dom;
+});
+
+},
+'dojo/_base/browser':function(){
+if(require.has){
+ require.has.add("config-selectorEngine", "acme");
+}
+define([
+ "../ready",
+ "./kernel",
+ "./connect", // until we decide if connect is going back into non-browser environments
+ "./unload",
+ "./window",
+ "./event",
+ "./html",
+ "./NodeList",
+ "../query",
+ "./xhr",
+ "./fx"], function(dojo){
+
+ // module:
+ // dojo/_base/browser
+
+ /*=====
+ return {
+ // summary:
+ // This module causes the browser-only base modules to be loaded.
+ };
+ =====*/
+
+ return dojo;
+});
+
+},
+'dojo/selector/acme':function(){
+define([
+ "../dom", "../sniff", "../_base/array", "../_base/lang", "../_base/window"
+], function(dom, has, array, lang, win){
+
+ // module:
+ // dojo/selector/acme
+
+/*
+ acme architectural overview:
+
+ acme is a relatively full-featured CSS3 query library. It is
+ designed to take any valid CSS3 selector and return the nodes matching
+ the selector. To do this quickly, it processes queries in several
+ steps, applying caching where profitable.
+
+ The steps (roughly in reverse order of the way they appear in the code):
+ 1.) check to see if we already have a "query dispatcher"
+ - if so, use that with the given parameterization. Skip to step 4.
+ 2.) attempt to determine which branch to dispatch the query to:
+ - JS (optimized DOM iteration)
+ - native (FF3.1+, Safari 3.1+, IE 8+)
+ 3.) tokenize and convert to executable "query dispatcher"
+ - this is where the lion's share of the complexity in the
+ system lies. In the DOM version, the query dispatcher is
+ assembled as a chain of "yes/no" test functions pertaining to
+ a section of a simple query statement (".blah:nth-child(odd)"
+ but not "div div", which is 2 simple statements). Individual
+ statement dispatchers are cached (to prevent re-definition)
+ as are entire dispatch chains (to make re-execution of the
+ same query fast)
+ 4.) the resulting query dispatcher is called in the passed scope
+ (by default the top-level document)
+ - for DOM queries, this results in a recursive, top-down
+ evaluation of nodes based on each simple query section
+ - for native implementations, this may mean working around spec
+ bugs. So be it.
+ 5.) matched nodes are pruned to ensure they are unique (if necessary)
+*/
+
+
+ ////////////////////////////////////////////////////////////////////////
+ // Toolkit aliases
+ ////////////////////////////////////////////////////////////////////////
+
+ // if you are extracting acme for use in your own system, you will
+ // need to provide these methods and properties. No other porting should be
+ // necessary, save for configuring the system to use a class other than
+ // dojo/NodeList as the return instance instantiator
+ var trim = lang.trim;
+ var each = array.forEach;
+
+ var getDoc = function(){ return win.doc; };
+ // NOTE(alex): the spec is idiotic. CSS queries should ALWAYS be case-sensitive, but nooooooo
+ var cssCaseBug = (getDoc().compatMode) == "BackCompat";
+
+ ////////////////////////////////////////////////////////////////////////
+ // Global utilities
+ ////////////////////////////////////////////////////////////////////////
+
+
+ var specials = ">~+";
+
+ // global thunk to determine whether we should treat the current query as
+ // case sensitive or not. This switch is flipped by the query evaluator
+ // based on the document passed as the context to search.
+ var caseSensitive = false;
+
+ // how high?
+ var yesman = function(){ return true; };
+
+ ////////////////////////////////////////////////////////////////////////
+ // Tokenizer
+ ////////////////////////////////////////////////////////////////////////
+
+ var getQueryParts = function(query){
+ // summary:
+ // state machine for query tokenization
+ // description:
+ // instead of using a brittle and slow regex-based CSS parser,
+ // acme implements an AST-style query representation. This
+ // representation is only generated once per query. For example,
+ // the same query run multiple times or under different root nodes
+ // does not re-parse the selector expression but instead uses the
+ // cached data structure. The state machine implemented here
+ // terminates on the last " " (space) character and returns an
+ // ordered array of query component structures (or "parts"). Each
+ // part represents an operator or a simple CSS filtering
+ // expression. The structure for parts is documented in the code
+ // below.
+
+
+ // NOTE:
+ // this code is designed to run fast and compress well. Sacrifices
+ // to readability and maintainability have been made. Your best
+ // bet when hacking the tokenizer is to put The Donnas on *really*
+ // loud (may we recommend their "Spend The Night" release?) and
+ // just assume you're gonna make mistakes. Keep the unit tests
+ // open and run them frequently. Knowing is half the battle ;-)
+ if(specials.indexOf(query.slice(-1)) >= 0){
+ // if we end with a ">", "+", or "~", that means we're implicitly
+ // searching all children, so make it explicit
+ query += " * ";
+ }else{
+ // if you have not provided a terminator, one will be provided for
+ // you...
+ query += " ";
+ }
+
+ var ts = function(/*Integer*/ s, /*Integer*/ e){
+ // trim and slice.
+
+ // take an index to start a string slice from and an end position
+ // and return a trimmed copy of that sub-string
+ return trim(query.slice(s, e));
+ };
+
+ // the overall data graph of the full query, as represented by queryPart objects
+ var queryParts = [];
+
+
+ // state keeping vars
+ var inBrackets = -1, inParens = -1, inMatchFor = -1,
+ inPseudo = -1, inClass = -1, inId = -1, inTag = -1, currentQuoteChar,
+ lc = "", cc = "", pStart;
+
+ // iteration vars
+ var x = 0, // index in the query
+ ql = query.length,
+ currentPart = null, // data structure representing the entire clause
+ _cp = null; // the current pseudo or attr matcher
+
+ // several temporary variables are assigned to this structure during a
+ // potential sub-expression match:
+ // attr:
+ // a string representing the current full attribute match in a
+ // bracket expression
+ // type:
+ // if there's an operator in a bracket expression, this is
+ // used to keep track of it
+ // value:
+ // the internals of parenthetical expression for a pseudo. for
+ // :nth-child(2n+1), value might be "2n+1"
+
+ var endTag = function(){
+ // called when the tokenizer hits the end of a particular tag name.
+ // Re-sets state variables for tag matching and sets up the matcher
+ // to handle the next type of token (tag or operator).
+ if(inTag >= 0){
+ var tv = (inTag == x) ? null : ts(inTag, x); // .toLowerCase();
+ currentPart[ (specials.indexOf(tv) < 0) ? "tag" : "oper" ] = tv;
+ inTag = -1;
+ }
+ };
+
+ var endId = function(){
+ // called when the tokenizer might be at the end of an ID portion of a match
+ if(inId >= 0){
+ currentPart.id = ts(inId, x).replace(/\\/g, "");
+ inId = -1;
+ }
+ };
+
+ var endClass = function(){
+ // called when the tokenizer might be at the end of a class name
+ // match. CSS allows for multiple classes, so we augment the
+ // current item with another class in its list
+ if(inClass >= 0){
+ currentPart.classes.push(ts(inClass + 1, x).replace(/\\/g, ""));
+ inClass = -1;
+ }
+ };
+
+ var endAll = function(){
+ // at the end of a simple fragment, so wall off the matches
+ endId();
+ endTag();
+ endClass();
+ };
+
+ var endPart = function(){
+ endAll();
+ if(inPseudo >= 0){
+ currentPart.pseudos.push({ name: ts(inPseudo + 1, x) });
+ }
+ // hint to the selector engine to tell it whether or not it
+ // needs to do any iteration. Many simple selectors don't, and
+ // we can avoid significant construction-time work by advising
+ // the system to skip them
+ currentPart.loops = (
+ currentPart.pseudos.length ||
+ currentPart.attrs.length ||
+ currentPart.classes.length );
+
+ currentPart.oquery = currentPart.query = ts(pStart, x); // save the full expression as a string
+
+
+ // otag/tag are hints to suggest to the system whether or not
+ // it's an operator or a tag. We save a copy of otag since the
+ // tag name is cast to upper-case in regular HTML matches. The
+ // system has a global switch to figure out if the current
+ // expression needs to be case sensitive or not and it will use
+ // otag or tag accordingly
+ currentPart.otag = currentPart.tag = (currentPart["oper"]) ? null : (currentPart.tag || "*");
+
+ if(currentPart.tag){
+ // if we're in a case-insensitive HTML doc, we likely want
+ // the toUpperCase when matching on element.tagName. If we
+ // do it here, we can skip the string op per node
+ // comparison
+ currentPart.tag = currentPart.tag.toUpperCase();
+ }
+
+ // add the part to the list
+ if(queryParts.length && (queryParts[queryParts.length-1].oper)){
+ // operators are always infix, so we remove them from the
+ // list and attach them to the next match. The evaluator is
+ // responsible for sorting out how to handle them.
+ currentPart.infixOper = queryParts.pop();
+ currentPart.query = currentPart.infixOper.query + " " + currentPart.query;
+ /*
+ console.debug( "swapping out the infix",
+ currentPart.infixOper,
+ "and attaching it to",
+ currentPart);
+ */
+ }
+ queryParts.push(currentPart);
+
+ currentPart = null;
+ };
+
+ // iterate over the query, character by character, building up a
+ // list of query part objects
+ for(; lc=cc, cc=query.charAt(x), x < ql; x++){
+ // cc: the current character in the match
+ // lc: the last character (if any)
+
+ // someone is trying to escape something, so don't try to match any
+ // fragments. We assume we're inside a literal.
+ if(lc == "\\"){ continue; }
+ if(!currentPart){ // a part was just ended or none has yet been created
+ // NOTE: I hate all this alloc, but it's shorter than writing tons of if's
+ pStart = x;
+ // rules describe full CSS sub-expressions, like:
+ // #someId
+ // .className:first-child
+ // but not:
+ // thinger > div.howdy[type=thinger]
+ // the indidual components of the previous query would be
+ // split into 3 parts that would be represented a structure like:
+ // [
+ // {
+ // query: "thinger",
+ // tag: "thinger",
+ // },
+ // {
+ // query: "div.howdy[type=thinger]",
+ // classes: ["howdy"],
+ // infixOper: {
+ // query: ">",
+ // oper: ">",
+ // }
+ // },
+ // ]
+ currentPart = {
+ query: null, // the full text of the part's rule
+ pseudos: [], // CSS supports multiple pseud-class matches in a single rule
+ attrs: [], // CSS supports multi-attribute match, so we need an array
+ classes: [], // class matches may be additive, e.g.: .thinger.blah.howdy
+ tag: null, // only one tag...
+ oper: null, // ...or operator per component. Note that these wind up being exclusive.
+ id: null, // the id component of a rule
+ getTag: function(){
+ return caseSensitive ? this.otag : this.tag;
+ }
+ };
+
+ // if we don't have a part, we assume we're going to start at
+ // the beginning of a match, which should be a tag name. This
+ // might fault a little later on, but we detect that and this
+ // iteration will still be fine.
+ inTag = x;
+ }
+
+ // Skip processing all quoted characters.
+ // If we are inside quoted text then currentQuoteChar stores the character that began the quote,
+ // thus that character that will end it.
+ if(currentQuoteChar){
+ if(cc == currentQuoteChar){
+ currentQuoteChar = null;
+ }
+ continue;
+ }else if (cc == "'" || cc == '"'){
+ currentQuoteChar = cc;
+ continue;
+ }
+
+ if(inBrackets >= 0){
+ // look for a the close first
+ if(cc == "]"){ // if we're in a [...] clause and we end, do assignment
+ if(!_cp.attr){
+ // no attribute match was previously begun, so we
+ // assume this is an attribute existence match in the
+ // form of [someAttributeName]
+ _cp.attr = ts(inBrackets+1, x);
+ }else{
+ // we had an attribute already, so we know that we're
+ // matching some sort of value, as in [attrName=howdy]
+ _cp.matchFor = ts((inMatchFor||inBrackets+1), x);
+ }
+ var cmf = _cp.matchFor;
+ if(cmf){
+ // try to strip quotes from the matchFor value. We want
+ // [attrName=howdy] to match the same
+ // as [attrName = 'howdy' ]
+ if( (cmf.charAt(0) == '"') || (cmf.charAt(0) == "'") ){
+ _cp.matchFor = cmf.slice(1, -1);
+ }
+ }
+ // remove backslash escapes from an attribute match, since DOM
+ // querying will get attribute values without backslashes
+ if(_cp.matchFor){
+ _cp.matchFor = _cp.matchFor.replace(/\\/g, "");
+ }
+
+ // end the attribute by adding it to the list of attributes.
+ currentPart.attrs.push(_cp);
+ _cp = null; // necessary?
+ inBrackets = inMatchFor = -1;
+ }else if(cc == "="){
+ // if the last char was an operator prefix, make sure we
+ // record it along with the "=" operator.
+ var addToCc = ("|~^$*".indexOf(lc) >=0 ) ? lc : "";
+ _cp.type = addToCc+cc;
+ _cp.attr = ts(inBrackets+1, x-addToCc.length);
+ inMatchFor = x+1;
+ }
+ // now look for other clause parts
+ }else if(inParens >= 0){
+ // if we're in a parenthetical expression, we need to figure
+ // out if it's attached to a pseudo-selector rule like
+ // :nth-child(1)
+ if(cc == ")"){
+ if(inPseudo >= 0){
+ _cp.value = ts(inParens+1, x);
+ }
+ inPseudo = inParens = -1;
+ }
+ }else if(cc == "#"){
+ // start of an ID match
+ endAll();
+ inId = x+1;
+ }else if(cc == "."){
+ // start of a class match
+ endAll();
+ inClass = x;
+ }else if(cc == ":"){
+ // start of a pseudo-selector match
+ endAll();
+ inPseudo = x;
+ }else if(cc == "["){
+ // start of an attribute match.
+ endAll();
+ inBrackets = x;
+ // provide a new structure for the attribute match to fill-in
+ _cp = {
+ /*=====
+ attr: null, type: null, matchFor: null
+ =====*/
+ };
+ }else if(cc == "("){
+ // we really only care if we've entered a parenthetical
+ // expression if we're already inside a pseudo-selector match
+ if(inPseudo >= 0){
+ // provide a new structure for the pseudo match to fill-in
+ _cp = {
+ name: ts(inPseudo+1, x),
+ value: null
+ };
+ currentPart.pseudos.push(_cp);
+ }
+ inParens = x;
+ }else if(
+ (cc == " ") &&
+ // if it's a space char and the last char is too, consume the
+ // current one without doing more work
+ (lc != cc)
+ ){
+ endPart();
+ }
+ }
+ return queryParts;
+ };
+
+
+ ////////////////////////////////////////////////////////////////////////
+ // DOM query infrastructure
+ ////////////////////////////////////////////////////////////////////////
+
+ var agree = function(first, second){
+ // the basic building block of the yes/no chaining system. agree(f1,
+ // f2) generates a new function which returns the boolean results of
+ // both of the passed functions to a single logical-anded result. If
+ // either are not passed, the other is used exclusively.
+ if(!first){ return second; }
+ if(!second){ return first; }
+
+ return function(){
+ return first.apply(window, arguments) && second.apply(window, arguments);
+ };
+ };
+
+ var getArr = function(i, arr){
+ // helps us avoid array alloc when we don't need it
+ var r = arr||[]; // FIXME: should this be 'new d._NodeListCtor()' ?
+ if(i){ r.push(i); }
+ return r;
+ };
+
+ var _isElement = function(n){ return (1 == n.nodeType); };
+
+ // FIXME: need to coalesce _getAttr with defaultGetter
+ var blank = "";
+ var _getAttr = function(elem, attr){
+ if(!elem){ return blank; }
+ if(attr == "class"){
+ return elem.className || blank;
+ }
+ if(attr == "for"){
+ return elem.htmlFor || blank;
+ }
+ if(attr == "style"){
+ return elem.style.cssText || blank;
+ }
+ return (caseSensitive ? elem.getAttribute(attr) : elem.getAttribute(attr, 2)) || blank;
+ };
+
+ var attrs = {
+ "*=": function(attr, value){
+ return function(elem){
+ // E[foo*="bar"]
+ // an E element whose "foo" attribute value contains
+ // the substring "bar"
+ return (_getAttr(elem, attr).indexOf(value)>=0);
+ };
+ },
+ "^=": function(attr, value){
+ // E[foo^="bar"]
+ // an E element whose "foo" attribute value begins exactly
+ // with the string "bar"
+ return function(elem){
+ return (_getAttr(elem, attr).indexOf(value)==0);
+ };
+ },
+ "$=": function(attr, value){
+ // E[foo$="bar"]
+ // an E element whose "foo" attribute value ends exactly
+ // with the string "bar"
+ return function(elem){
+ var ea = " "+_getAttr(elem, attr);
+ var lastIndex = ea.lastIndexOf(value);
+ return lastIndex > -1 && (lastIndex==(ea.length-value.length));
+ };
+ },
+ "~=": function(attr, value){
+ // E[foo~="bar"]
+ // an E element whose "foo" attribute value is a list of
+ // space-separated values, one of which is exactly equal
+ // to "bar"
+
+ // return "[contains(concat(' ',@"+attr+",' '), ' "+ value +" ')]";
+ var tval = " "+value+" ";
+ return function(elem){
+ var ea = " "+_getAttr(elem, attr)+" ";
+ return (ea.indexOf(tval)>=0);
+ };
+ },
+ "|=": function(attr, value){
+ // E[hreflang|="en"]
+ // an E element whose "hreflang" attribute has a
+ // hyphen-separated list of values beginning (from the
+ // left) with "en"
+ var valueDash = value+"-";
+ return function(elem){
+ var ea = _getAttr(elem, attr);
+ return (
+ (ea == value) ||
+ (ea.indexOf(valueDash)==0)
+ );
+ };
+ },
+ "=": function(attr, value){
+ return function(elem){
+ return (_getAttr(elem, attr) == value);
+ };
+ }
+ };
+
+ // avoid testing for node type if we can. Defining this in the negative
+ // here to avoid negation in the fast path.
+ var _noNES = (typeof getDoc().firstChild.nextElementSibling == "undefined");
+ var _ns = !_noNES ? "nextElementSibling" : "nextSibling";
+ var _ps = !_noNES ? "previousElementSibling" : "previousSibling";
+ var _simpleNodeTest = (_noNES ? _isElement : yesman);
+
+ var _lookLeft = function(node){
+ // look left
+ while(node = node[_ps]){
+ if(_simpleNodeTest(node)){ return false; }
+ }
+ return true;
+ };
+
+ var _lookRight = function(node){
+ // look right
+ while(node = node[_ns]){
+ if(_simpleNodeTest(node)){ return false; }
+ }
+ return true;
+ };
+
+ var getNodeIndex = function(node){
+ var root = node.parentNode;
+ root = root.nodeType != 7 ? root : root.nextSibling; // PROCESSING_INSTRUCTION_NODE
+ var i = 0,
+ tret = root.children || root.childNodes,
+ ci = (node["_i"]||node.getAttribute("_i")||-1),
+ cl = (root["_l"]|| (typeof root.getAttribute !== "undefined" ? root.getAttribute("_l") : -1));
+
+ if(!tret){ return -1; }
+ var l = tret.length;
+
+ // we calculate the parent length as a cheap way to invalidate the
+ // cache. It's not 100% accurate, but it's much more honest than what
+ // other libraries do
+ if( cl == l && ci >= 0 && cl >= 0 ){
+ // if it's legit, tag and release
+ return ci;
+ }
+
+ // else re-key things
+ if(has("ie") && typeof root.setAttribute !== "undefined"){
+ root.setAttribute("_l", l);
+ }else{
+ root["_l"] = l;
+ }
+ ci = -1;
+ for(var te = root["firstElementChild"]||root["firstChild"]; te; te = te[_ns]){
+ if(_simpleNodeTest(te)){
+ if(has("ie")){
+ te.setAttribute("_i", ++i);
+ }else{
+ te["_i"] = ++i;
+ }
+ if(node === te){
+ // NOTE:
+ // shortcutting the return at this step in indexing works
+ // very well for benchmarking but we avoid it here since
+ // it leads to potential O(n^2) behavior in sequential
+ // getNodexIndex operations on a previously un-indexed
+ // parent. We may revisit this at a later time, but for
+ // now we just want to get the right answer more often
+ // than not.
+ ci = i;
+ }
+ }
+ }
+ return ci;
+ };
+
+ var isEven = function(elem){
+ return !((getNodeIndex(elem)) % 2);
+ };
+
+ var isOdd = function(elem){
+ return ((getNodeIndex(elem)) % 2);
+ };
+
+ var pseudos = {
+ "checked": function(name, condition){
+ return function(elem){
+ return !!("checked" in elem ? elem.checked : elem.selected);
+ };
+ },
+ "disabled": function(name, condition){
+ return function(elem){
+ return elem.disabled;
+ };
+ },
+ "enabled": function(name, condition){
+ return function(elem){
+ return !elem.disabled;
+ };
+ },
+ "first-child": function(){ return _lookLeft; },
+ "last-child": function(){ return _lookRight; },
+ "only-child": function(name, condition){
+ return function(node){
+ return _lookLeft(node) && _lookRight(node);
+ };
+ },
+ "empty": function(name, condition){
+ return function(elem){
+ // DomQuery and jQuery get this wrong, oddly enough.
+ // The CSS 3 selectors spec is pretty explicit about it, too.
+ var cn = elem.childNodes;
+ var cnl = elem.childNodes.length;
+ // if(!cnl){ return true; }
+ for(var x=cnl-1; x >= 0; x--){
+ var nt = cn[x].nodeType;
+ if((nt === 1)||(nt == 3)){ return false; }
+ }
+ return true;
+ };
+ },
+ "contains": function(name, condition){
+ var cz = condition.charAt(0);
+ if( cz == '"' || cz == "'" ){ //remove quote
+ condition = condition.slice(1, -1);
+ }
+ return function(elem){
+ return (elem.innerHTML.indexOf(condition) >= 0);
+ };
+ },
+ "not": function(name, condition){
+ var p = getQueryParts(condition)[0];
+ var ignores = { el: 1 };
+ if(p.tag != "*"){
+ ignores.tag = 1;
+ }
+ if(!p.classes.length){
+ ignores.classes = 1;
+ }
+ var ntf = getSimpleFilterFunc(p, ignores);
+ return function(elem){
+ return (!ntf(elem));
+ };
+ },
+ "nth-child": function(name, condition){
+ var pi = parseInt;
+ // avoid re-defining function objects if we can
+ if(condition == "odd"){
+ return isOdd;
+ }else if(condition == "even"){
+ return isEven;
+ }
+ // FIXME: can we shorten this?
+ if(condition.indexOf("n") != -1){
+ var tparts = condition.split("n", 2);
+ var pred = tparts[0] ? ((tparts[0] == '-') ? -1 : pi(tparts[0])) : 1;
+ var idx = tparts[1] ? pi(tparts[1]) : 0;
+ var lb = 0, ub = -1;
+ if(pred > 0){
+ if(idx < 0){
+ idx = (idx % pred) && (pred + (idx % pred));
+ }else if(idx>0){
+ if(idx >= pred){
+ lb = idx - idx % pred;
+ }
+ idx = idx % pred;
+ }
+ }else if(pred<0){
+ pred *= -1;
+ // idx has to be greater than 0 when pred is negative;
+ // shall we throw an error here?
+ if(idx > 0){
+ ub = idx;
+ idx = idx % pred;
+ }
+ }
+ if(pred > 0){
+ return function(elem){
+ var i = getNodeIndex(elem);
+ return (i>=lb) && (ub<0 || i<=ub) && ((i % pred) == idx);
+ };
+ }else{
+ condition = idx;
+ }
+ }
+ var ncount = pi(condition);
+ return function(elem){
+ return (getNodeIndex(elem) == ncount);
+ };
+ }
+ };
+
+ var defaultGetter = (has("ie") && (has("ie") < 9 || has("quirks"))) ? function(cond){
+ var clc = cond.toLowerCase();
+ if(clc == "class"){ cond = "className"; }
+ return function(elem){
+ return (caseSensitive ? elem.getAttribute(cond) : elem[cond]||elem[clc]);
+ };
+ } : function(cond){
+ return function(elem){
+ return (elem && elem.getAttribute && elem.hasAttribute(cond));
+ };
+ };
+
+ var getSimpleFilterFunc = function(query, ignores){
+ // generates a node tester function based on the passed query part. The
+ // query part is one of the structures generated by the query parser
+ // when it creates the query AST. The "ignores" object specifies which
+ // (if any) tests to skip, allowing the system to avoid duplicating
+ // work where it may have already been taken into account by other
+ // factors such as how the nodes to test were fetched in the first
+ // place
+ if(!query){ return yesman; }
+ ignores = ignores||{};
+
+ var ff = null;
+
+ if(!("el" in ignores)){
+ ff = agree(ff, _isElement);
+ }
+
+ if(!("tag" in ignores)){
+ if(query.tag != "*"){
+ ff = agree(ff, function(elem){
+ return (elem && ((caseSensitive ? elem.tagName : elem.tagName.toUpperCase()) == query.getTag()));
+ });
+ }
+ }
+
+ if(!("classes" in ignores)){
+ each(query.classes, function(cname, idx, arr){
+ // get the class name
+ /*
+ var isWildcard = cname.charAt(cname.length-1) == "*";
+ if(isWildcard){
+ cname = cname.substr(0, cname.length-1);
+ }
+ // I dislike the regex thing, even if memoized in a cache, but it's VERY short
+ var re = new RegExp("(?:^|\\s)" + cname + (isWildcard ? ".*" : "") + "(?:\\s|$)");
+ */
+ var re = new RegExp("(?:^|\\s)" + cname + "(?:\\s|$)");
+ ff = agree(ff, function(elem){
+ return re.test(elem.className);
+ });
+ ff.count = idx;
+ });
+ }
+
+ if(!("pseudos" in ignores)){
+ each(query.pseudos, function(pseudo){
+ var pn = pseudo.name;
+ if(pseudos[pn]){
+ ff = agree(ff, pseudos[pn](pn, pseudo.value));
+ }
+ });
+ }
+
+ if(!("attrs" in ignores)){
+ each(query.attrs, function(attr){
+ var matcher;
+ var a = attr.attr;
+ // type, attr, matchFor
+ if(attr.type && attrs[attr.type]){
+ matcher = attrs[attr.type](a, attr.matchFor);
+ }else if(a.length){
+ matcher = defaultGetter(a);
+ }
+ if(matcher){
+ ff = agree(ff, matcher);
+ }
+ });
+ }
+
+ if(!("id" in ignores)){
+ if(query.id){
+ ff = agree(ff, function(elem){
+ return (!!elem && (elem.id == query.id));
+ });
+ }
+ }
+
+ if(!ff){
+ if(!("default" in ignores)){
+ ff = yesman;
+ }
+ }
+ return ff;
+ };
+
+ var _nextSibling = function(filterFunc){
+ return function(node, ret, bag){
+ while(node = node[_ns]){
+ if(_noNES && (!_isElement(node))){ continue; }
+ if(
+ (!bag || _isUnique(node, bag)) &&
+ filterFunc(node)
+ ){
+ ret.push(node);
+ }
+ break;
+ }
+ return ret;
+ };
+ };
+
+ var _nextSiblings = function(filterFunc){
+ return function(root, ret, bag){
+ var te = root[_ns];
+ while(te){
+ if(_simpleNodeTest(te)){
+ if(bag && !_isUnique(te, bag)){
+ break;
+ }
+ if(filterFunc(te)){
+ ret.push(te);
+ }
+ }
+ te = te[_ns];
+ }
+ return ret;
+ };
+ };
+
+ // get an array of child *elements*, skipping text and comment nodes
+ var _childElements = function(filterFunc){
+ filterFunc = filterFunc||yesman;
+ return function(root, ret, bag){
+ // get an array of child elements, skipping text and comment nodes
+ var te, x = 0, tret = root.children || root.childNodes;
+ while(te = tret[x++]){
+ if(
+ _simpleNodeTest(te) &&
+ (!bag || _isUnique(te, bag)) &&
+ (filterFunc(te, x))
+ ){
+ ret.push(te);
+ }
+ }
+ return ret;
+ };
+ };
+
+ // test to see if node is below root
+ var _isDescendant = function(node, root){
+ var pn = node.parentNode;
+ while(pn){
+ if(pn == root){
+ break;
+ }
+ pn = pn.parentNode;
+ }
+ return !!pn;
+ };
+
+ var _getElementsFuncCache = {};
+
+ var getElementsFunc = function(query){
+ var retFunc = _getElementsFuncCache[query.query];
+ // if we've got a cached dispatcher, just use that
+ if(retFunc){ return retFunc; }
+ // else, generate a new on
+
+ // NOTE:
+ // this function returns a function that searches for nodes and
+ // filters them. The search may be specialized by infix operators
+ // (">", "~", or "+") else it will default to searching all
+ // descendants (the " " selector). Once a group of children is
+ // found, a test function is applied to weed out the ones we
+ // don't want. Many common cases can be fast-pathed. We spend a
+ // lot of cycles to create a dispatcher that doesn't do more work
+ // than necessary at any point since, unlike this function, the
+ // dispatchers will be called every time. The logic of generating
+ // efficient dispatchers looks like this in pseudo code:
+ //
+ // # if it's a purely descendant query (no ">", "+", or "~" modifiers)
+ // if infixOperator == " ":
+ // if only(id):
+ // return def(root):
+ // return d.byId(id, root);
+ //
+ // elif id:
+ // return def(root):
+ // return filter(d.byId(id, root));
+ //
+ // elif cssClass && getElementsByClassName:
+ // return def(root):
+ // return filter(root.getElementsByClassName(cssClass));
+ //
+ // elif only(tag):
+ // return def(root):
+ // return root.getElementsByTagName(tagName);
+ //
+ // else:
+ // # search by tag name, then filter
+ // return def(root):
+ // return filter(root.getElementsByTagName(tagName||"*"));
+ //
+ // elif infixOperator == ">":
+ // # search direct children
+ // return def(root):
+ // return filter(root.children);
+ //
+ // elif infixOperator == "+":
+ // # search next sibling
+ // return def(root):
+ // return filter(root.nextElementSibling);
+ //
+ // elif infixOperator == "~":
+ // # search rightward siblings
+ // return def(root):
+ // return filter(nextSiblings(root));
+
+ var io = query.infixOper;
+ var oper = (io ? io.oper : "");
+ // the default filter func which tests for all conditions in the query
+ // part. This is potentially inefficient, so some optimized paths may
+ // re-define it to test fewer things.
+ var filterFunc = getSimpleFilterFunc(query, { el: 1 });
+ var qt = query.tag;
+ var wildcardTag = ("*" == qt);
+ var ecs = getDoc()["getElementsByClassName"];
+
+ if(!oper){
+ // if there's no infix operator, then it's a descendant query. ID
+ // and "elements by class name" variants can be accelerated so we
+ // call them out explicitly:
+ if(query.id){
+ // testing shows that the overhead of yesman() is acceptable
+ // and can save us some bytes vs. re-defining the function
+ // everywhere.
+ filterFunc = (!query.loops && wildcardTag) ?
+ yesman :
+ getSimpleFilterFunc(query, { el: 1, id: 1 });
+
+ retFunc = function(root, arr){
+ var te = dom.byId(query.id, (root.ownerDocument||root));
+ if(!te || !filterFunc(te)){ return; }
+ if(9 == root.nodeType){ // if root's a doc, we just return directly
+ return getArr(te, arr);
+ }else{ // otherwise check ancestry
+ if(_isDescendant(te, root)){
+ return getArr(te, arr);
+ }
+ }
+ };
+ }else if(
+ ecs &&
+ // isAlien check. Workaround for Prototype.js being totally evil/dumb.
+ /\{\s*\[native code\]\s*\}/.test(String(ecs)) &&
+ query.classes.length &&
+ !cssCaseBug
+ ){
+ // it's a class-based query and we've got a fast way to run it.
+
+ // ignore class and ID filters since we will have handled both
+ filterFunc = getSimpleFilterFunc(query, { el: 1, classes: 1, id: 1 });
+ var classesString = query.classes.join(" ");
+ retFunc = function(root, arr, bag){
+ var ret = getArr(0, arr), te, x=0;
+ var tret = root.getElementsByClassName(classesString);
+ while((te = tret[x++])){
+ if(filterFunc(te, root) && _isUnique(te, bag)){
+ ret.push(te);
+ }
+ }
+ return ret;
+ };
+
+ }else if(!wildcardTag && !query.loops){
+ // it's tag only. Fast-path it.
+ retFunc = function(root, arr, bag){
+ var ret = getArr(0, arr), te, x=0;
+ var tag = query.getTag(),
+ tret = tag ? root.getElementsByTagName(tag) : [];
+ while((te = tret[x++])){
+ if(_isUnique(te, bag)){
+ ret.push(te);
+ }
+ }
+ return ret;
+ };
+ }else{
+ // the common case:
+ // a descendant selector without a fast path. By now it's got
+ // to have a tag selector, even if it's just "*" so we query
+ // by that and filter
+ filterFunc = getSimpleFilterFunc(query, { el: 1, tag: 1, id: 1 });
+ retFunc = function(root, arr, bag){
+ var ret = getArr(0, arr), te, x=0;
+ // we use getTag() to avoid case sensitivity issues
+ var tag = query.getTag(),
+ tret = tag ? root.getElementsByTagName(tag) : [];
+ while((te = tret[x++])){
+ if(filterFunc(te, root) && _isUnique(te, bag)){
+ ret.push(te);
+ }
+ }
+ return ret;
+ };
+ }
+ }else{
+ // the query is scoped in some way. Instead of querying by tag we
+ // use some other collection to find candidate nodes
+ var skipFilters = { el: 1 };
+ if(wildcardTag){
+ skipFilters.tag = 1;
+ }
+ filterFunc = getSimpleFilterFunc(query, skipFilters);
+ if("+" == oper){
+ retFunc = _nextSibling(filterFunc);
+ }else if("~" == oper){
+ retFunc = _nextSiblings(filterFunc);
+ }else if(">" == oper){
+ retFunc = _childElements(filterFunc);
+ }
+ }
+ // cache it and return
+ return _getElementsFuncCache[query.query] = retFunc;
+ };
+
+ var filterDown = function(root, queryParts){
+ // NOTE:
+ // this is the guts of the DOM query system. It takes a list of
+ // parsed query parts and a root and finds children which match
+ // the selector represented by the parts
+ var candidates = getArr(root), qp, x, te, qpl = queryParts.length, bag, ret;
+
+ for(var i = 0; i < qpl; i++){
+ ret = [];
+ qp = queryParts[i];
+ x = candidates.length - 1;
+ if(x > 0){
+ // if we have more than one root at this level, provide a new
+ // hash to use for checking group membership but tell the
+ // system not to post-filter us since we will already have been
+ // guaranteed to be unique
+ bag = {};
+ ret.nozip = true;
+ }
+ var gef = getElementsFunc(qp);
+ for(var j = 0; (te = candidates[j]); j++){
+ // for every root, get the elements that match the descendant
+ // selector, adding them to the "ret" array and filtering them
+ // via membership in this level's bag. If there are more query
+ // parts, then this level's return will be used as the next
+ // level's candidates
+ gef(te, ret, bag);
+ }
+ if(!ret.length){ break; }
+ candidates = ret;
+ }
+ return ret;
+ };
+
+ ////////////////////////////////////////////////////////////////////////
+ // the query runner
+ ////////////////////////////////////////////////////////////////////////
+
+ // these are the primary caches for full-query results. The query
+ // dispatcher functions are generated then stored here for hash lookup in
+ // the future
+ var _queryFuncCacheDOM = {},
+ _queryFuncCacheQSA = {};
+
+ // this is the second level of splitting, from full-length queries (e.g.,
+ // "div.foo .bar") into simple query expressions (e.g., ["div.foo",
+ // ".bar"])
+ var getStepQueryFunc = function(query){
+ var qparts = getQueryParts(trim(query));
+
+ // if it's trivial, avoid iteration and zipping costs
+ if(qparts.length == 1){
+ // we optimize this case here to prevent dispatch further down the
+ // chain, potentially slowing things down. We could more elegantly
+ // handle this in filterDown(), but it's slower for simple things
+ // that need to be fast (e.g., "#someId").
+ var tef = getElementsFunc(qparts[0]);
+ return function(root){
+ var r = tef(root, []);
+ if(r){ r.nozip = true; }
+ return r;
+ };
+ }
+
+ // otherwise, break it up and return a runner that iterates over the parts recursively
+ return function(root){
+ return filterDown(root, qparts);
+ };
+ };
+
+ // NOTES:
+ // * we can't trust QSA for anything but document-rooted queries, so
+ // caching is split into DOM query evaluators and QSA query evaluators
+ // * caching query results is dirty and leak-prone (or, at a minimum,
+ // prone to unbounded growth). Other toolkits may go this route, but
+ // they totally destroy their own ability to manage their memory
+ // footprint. If we implement it, it should only ever be with a fixed
+ // total element reference # limit and an LRU-style algorithm since JS
+ // has no weakref support. Caching compiled query evaluators is also
+ // potentially problematic, but even on large documents the size of the
+ // query evaluators is often < 100 function objects per evaluator (and
+ // LRU can be applied if it's ever shown to be an issue).
+ // * since IE's QSA support is currently only for HTML documents and even
+ // then only in IE 8's "standards mode", we have to detect our dispatch
+ // route at query time and keep 2 separate caches. Ugg.
+
+ // we need to determine if we think we can run a given query via
+ // querySelectorAll or if we'll need to fall back on DOM queries to get
+ // there. We need a lot of information about the environment and the query
+ // to make the determination (e.g. does it support QSA, does the query in
+ // question work in the native QSA impl, etc.).
+
+ // IE QSA queries may incorrectly include comment nodes, so we throw the
+ // zipping function into "remove" comments mode instead of the normal "skip
+ // it" which every other QSA-clued browser enjoys
+ var noZip = has("ie") ? "commentStrip" : "nozip";
+
+ var qsa = "querySelectorAll";
+ var qsaAvail = !!getDoc()[qsa];
+
+ //Don't bother with n+3 type of matches, IE complains if we modify those.
+ var infixSpaceRe = /\\[>~+]|n\+\d|([^ \\])?([>~+])([^ =])?/g;
+ var infixSpaceFunc = function(match, pre, ch, post){
+ return ch ? (pre ? pre + " " : "") + ch + (post ? " " + post : "") : /*n+3*/ match;
+ };
+
+ //Don't apply the infixSpaceRe to attribute value selectors
+ var attRe = /([^[]*)([^\]]*])?/g;
+ var attFunc = function(match, nonAtt, att){
+ return nonAtt.replace(infixSpaceRe, infixSpaceFunc) + (att||"");
+ };
+ var getQueryFunc = function(query, forceDOM){
+ //Normalize query. The CSS3 selectors spec allows for omitting spaces around
+ //infix operators, >, ~ and +
+ //Do the work here since detection for spaces is used as a simple "not use QSA"
+ //test below.
+ query = query.replace(attRe, attFunc);
+
+ if(qsaAvail){
+ // if we've got a cached variant and we think we can do it, run it!
+ var qsaCached = _queryFuncCacheQSA[query];
+ if(qsaCached && !forceDOM){ return qsaCached; }
+ }
+
+ // else if we've got a DOM cached variant, assume that we already know
+ // all we need to and use it
+ var domCached = _queryFuncCacheDOM[query];
+ if(domCached){ return domCached; }
+
+ // TODO:
+ // today we're caching DOM and QSA branches separately so we
+ // recalc useQSA every time. If we had a way to tag root+query
+ // efficiently, we'd be in good shape to do a global cache.
+
+ var qcz = query.charAt(0);
+ var nospace = (-1 == query.indexOf(" "));
+
+ // byId searches are wicked fast compared to QSA, even when filtering
+ // is required
+ if( (query.indexOf("#") >= 0) && (nospace) ){
+ forceDOM = true;
+ }
+
+ var useQSA = (
+ qsaAvail && (!forceDOM) &&
+ // as per CSS 3, we can't currently start w/ combinator:
+ // http://www.w3.org/TR/css3-selectors/#w3cselgrammar
+ (specials.indexOf(qcz) == -1) &&
+ // IE's QSA impl sucks on pseudos
+ (!has("ie") || (query.indexOf(":") == -1)) &&
+
+ (!(cssCaseBug && (query.indexOf(".") >= 0))) &&
+
+ // FIXME:
+ // need to tighten up browser rules on ":contains" and "|=" to
+ // figure out which aren't good
+ // Latest webkit (around 531.21.8) does not seem to do well with :checked on option
+ // elements, even though according to spec, selected options should
+ // match :checked. So go nonQSA for it:
+ // http://bugs.dojotoolkit.org/ticket/5179
+ (query.indexOf(":contains") == -1) && (query.indexOf(":checked") == -1) &&
+ (query.indexOf("|=") == -1) // some browsers don't grok it
+ );
+
+ // TODO:
+ // if we've got a descendant query (e.g., "> .thinger" instead of
+ // just ".thinger") in a QSA-able doc, but are passed a child as a
+ // root, it should be possible to give the item a synthetic ID and
+ // trivially rewrite the query to the form "#synid > .thinger" to
+ // use the QSA branch
+
+
+ if(useQSA){
+ var tq = (specials.indexOf(query.charAt(query.length-1)) >= 0) ?
+ (query + " *") : query;
+ return _queryFuncCacheQSA[query] = function(root){
+ try{
+ // the QSA system contains an egregious spec bug which
+ // limits us, effectively, to only running QSA queries over
+ // entire documents. See:
+ // http://ejohn.org/blog/thoughts-on-queryselectorall/
+ // despite this, we can also handle QSA runs on simple
+ // selectors, but we don't want detection to be expensive
+ // so we're just checking for the presence of a space char
+ // right now. Not elegant, but it's cheaper than running
+ // the query parser when we might not need to
+ if(!((9 == root.nodeType) || nospace)){ throw ""; }
+ var r = root[qsa](tq);
+ // skip expensive duplication checks and just wrap in a NodeList
+ r[noZip] = true;
+ return r;
+ }catch(e){
+ // else run the DOM branch on this query, ensuring that we
+ // default that way in the future
+ return getQueryFunc(query, true)(root);
+ }
+ };
+ }else{
+ // DOM branch
+ var parts = query.match(/([^\s,](?:"(?:\\.|[^"])+"|'(?:\\.|[^'])+'|[^,])*)/g);
+ return _queryFuncCacheDOM[query] = ((parts.length < 2) ?
+ // if not a compound query (e.g., ".foo, .bar"), cache and return a dispatcher
+ getStepQueryFunc(query) :
+ // if it *is* a complex query, break it up into its
+ // constituent parts and return a dispatcher that will
+ // merge the parts when run
+ function(root){
+ var pindex = 0, // avoid array alloc for every invocation
+ ret = [],
+ tp;
+ while((tp = parts[pindex++])){
+ ret = ret.concat(getStepQueryFunc(tp)(root));
+ }
+ return ret;
+ }
+ );
+ }
+ };
+
+ var _zipIdx = 0;
+
+ // NOTE:
+ // this function is Moo inspired, but our own impl to deal correctly
+ // with XML in IE
+ var _nodeUID = has("ie") ? function(node){
+ if(caseSensitive){
+ // XML docs don't have uniqueID on their nodes
+ return (node.getAttribute("_uid") || node.setAttribute("_uid", ++_zipIdx) || _zipIdx);
+
+ }else{
+ return node.uniqueID;
+ }
+ } :
+ function(node){
+ return (node._uid || (node._uid = ++_zipIdx));
+ };
+
+ // determine if a node in is unique in a "bag". In this case we don't want
+ // to flatten a list of unique items, but rather just tell if the item in
+ // question is already in the bag. Normally we'd just use hash lookup to do
+ // this for us but IE's DOM is busted so we can't really count on that. On
+ // the upside, it gives us a built in unique ID function.
+ var _isUnique = function(node, bag){
+ if(!bag){ return 1; }
+ var id = _nodeUID(node);
+ if(!bag[id]){ return bag[id] = 1; }
+ return 0;
+ };
+
+ // attempt to efficiently determine if an item in a list is a dupe,
+ // returning a list of "uniques", hopefully in document order
+ var _zipIdxName = "_zipIdx";
+ var _zip = function(arr){
+ if(arr && arr.nozip){
+ return arr;
+ }
+ var ret = [];
+ if(!arr || !arr.length){ return ret; }
+ if(arr[0]){
+ ret.push(arr[0]);
+ }
+ if(arr.length < 2){ return ret; }
+
+ _zipIdx++;
+
+ // we have to fork here for IE and XML docs because we can't set
+ // expandos on their nodes (apparently). *sigh*
+ var x, te;
+ if(has("ie") && caseSensitive){
+ var szidx = _zipIdx+"";
+ arr[0].setAttribute(_zipIdxName, szidx);
+ for(x = 1; te = arr[x]; x++){
+ if(arr[x].getAttribute(_zipIdxName) != szidx){
+ ret.push(te);
+ }
+ te.setAttribute(_zipIdxName, szidx);
+ }
+ }else if(has("ie") && arr.commentStrip){
+ try{
+ for(x = 1; te = arr[x]; x++){
+ if(_isElement(te)){
+ ret.push(te);
+ }
+ }
+ }catch(e){ /* squelch */ }
+ }else{
+ if(arr[0]){ arr[0][_zipIdxName] = _zipIdx; }
+ for(x = 1; te = arr[x]; x++){
+ if(arr[x][_zipIdxName] != _zipIdx){
+ ret.push(te);
+ }
+ te[_zipIdxName] = _zipIdx;
+ }
+ }
+ return ret;
+ };
+
+ // the main executor
+ var query = function(/*String*/ query, /*String|DOMNode?*/ root){
+ // summary:
+ // Returns nodes which match the given CSS3 selector, searching the
+ // entire document by default but optionally taking a node to scope
+ // the search by. Returns an array.
+ // description:
+ // dojo.query() is the swiss army knife of DOM node manipulation in
+ // Dojo. Much like Prototype's "$$" (bling-bling) function or JQuery's
+ // "$" function, dojo.query provides robust, high-performance
+ // CSS-based node selector support with the option of scoping searches
+ // to a particular sub-tree of a document.
+ //
+ // Supported Selectors:
+ // --------------------
+ //
+ // acme supports a rich set of CSS3 selectors, including:
+ //
+ // - class selectors (e.g., `.foo`)
+ // - node type selectors like `span`
+ // - ` ` descendant selectors
+ // - `>` child element selectors
+ // - `#foo` style ID selectors
+ // - `*` universal selector
+ // - `~`, the preceded-by sibling selector
+ // - `+`, the immediately preceded-by sibling selector
+ // - attribute queries:
+ // - `[foo]` attribute presence selector
+ // - `[foo='bar']` attribute value exact match
+ // - `[foo~='bar']` attribute value list item match
+ // - `[foo^='bar']` attribute start match
+ // - `[foo$='bar']` attribute end match
+ // - `[foo*='bar']` attribute substring match
+ // - `:first-child`, `:last-child`, and `:only-child` positional selectors
+ // - `:empty` content emtpy selector
+ // - `:checked` pseudo selector
+ // - `:nth-child(n)`, `:nth-child(2n+1)` style positional calculations
+ // - `:nth-child(even)`, `:nth-child(odd)` positional selectors
+ // - `:not(...)` negation pseudo selectors
+ //
+ // Any legal combination of these selectors will work with
+ // `dojo.query()`, including compound selectors ("," delimited).
+ // Very complex and useful searches can be constructed with this
+ // palette of selectors and when combined with functions for
+ // manipulation presented by dojo/NodeList, many types of DOM
+ // manipulation operations become very straightforward.
+ //
+ // Unsupported Selectors:
+ // ----------------------
+ //
+ // While dojo.query handles many CSS3 selectors, some fall outside of
+ // what's reasonable for a programmatic node querying engine to
+ // handle. Currently unsupported selectors include:
+ //
+ // - namespace-differentiated selectors of any form
+ // - all `::` pseduo-element selectors
+ // - certain pseudo-selectors which don't get a lot of day-to-day use:
+ // - `:root`, `:lang()`, `:target`, `:focus`
+ // - all visual and state selectors:
+ // - `:root`, `:active`, `:hover`, `:visited`, `:link`,
+ // `:enabled`, `:disabled`
+ // - `:*-of-type` pseudo selectors
+ //
+ // dojo.query and XML Documents:
+ // -----------------------------
+ //
+ // `dojo.query` (as of dojo 1.2) supports searching XML documents
+ // in a case-sensitive manner. If an HTML document is served with
+ // a doctype that forces case-sensitivity (e.g., XHTML 1.1
+ // Strict), dojo.query() will detect this and "do the right
+ // thing". Case sensitivity is dependent upon the document being
+ // searched and not the query used. It is therefore possible to
+ // use case-sensitive queries on strict sub-documents (iframes,
+ // etc.) or XML documents while still assuming case-insensitivity
+ // for a host/root document.
+ //
+ // Non-selector Queries:
+ // ---------------------
+ //
+ // If something other than a String is passed for the query,
+ // `dojo.query` will return a new `dojo/NodeList` instance
+ // constructed from that parameter alone and all further
+ // processing will stop. This means that if you have a reference
+ // to a node or NodeList, you can quickly construct a new NodeList
+ // from the original by calling `dojo.query(node)` or
+ // `dojo.query(list)`.
+ //
+ // query:
+ // The CSS3 expression to match against. For details on the syntax of
+ // CSS3 selectors, see
+ // root:
+ // A DOMNode (or node id) to scope the search from. Optional.
+ // returns: Array
+ // example:
+ // search the entire document for elements with the class "foo":
+ // | dojo.query(".foo");
+ // these elements will match:
+ // |
+ // |
+ // |
+ // example:
+ // search the entire document for elements with the classes "foo" *and* "bar":
+ // | dojo.query(".foo.bar");
+ // these elements will match:
+ // |
+ // while these will not:
+ // |
+ // |
+ // example:
+ // find `` elements which are descendants of paragraphs and
+ // which have a "highlighted" class:
+ // | dojo.query("p span.highlighted");
+ // the innermost span in this fragment matches:
+ // |
+ // | ...
+ // | ...
+ // |
+ // |
+ // example:
+ // set an "odd" class on all odd table rows inside of the table
+ // `#tabular_data`, using the `>` (direct child) selector to avoid
+ // affecting any nested tables:
+ // | dojo.query("#tabular_data > tbody > tr:nth-child(odd)").addClass("odd");
+ // example:
+ // remove all elements with the class "error" from the document
+ // and store them in a list:
+ // | var errors = dojo.query(".error").orphan();
+ // example:
+ // add an onclick handler to every submit button in the document
+ // which causes the form to be sent via Ajax instead:
+ // | dojo.query("input[type='submit']").onclick(function(e){
+ // | dojo.stopEvent(e); // prevent sending the form
+ // | var btn = e.target;
+ // | dojo.xhrPost({
+ // | form: btn.form,
+ // | load: function(data){
+ // | // replace the form with the response
+ // | var div = dojo.doc.createElement("div");
+ // | dojo.place(div, btn.form, "after");
+ // | div.innerHTML = data;
+ // | dojo.style(btn.form, "display", "none");
+ // | }
+ // | });
+ // | });
+
+ root = root || getDoc();
+
+ // throw the big case sensitivity switch
+ var od = root.ownerDocument || root; // root is either Document or a node inside the document
+ caseSensitive = (od.createElement("div").tagName === "div");
+
+ // NOTE:
+ // adding "true" as the 2nd argument to getQueryFunc is useful for
+ // testing the DOM branch without worrying about the
+ // behavior/performance of the QSA branch.
+ var r = getQueryFunc(query)(root);
+
+ // FIXME:
+ // need to investigate this branch WRT #8074 and #8075
+ if(r && r.nozip){
+ return r;
+ }
+ return _zip(r); // dojo/NodeList
+ };
+ query.filter = function(/*Node[]*/ nodeList, /*String*/ filter, /*String|DOMNode?*/ root){
+ // summary:
+ // function for filtering a NodeList based on a selector, optimized for simple selectors
+ var tmpNodeList = [],
+ parts = getQueryParts(filter),
+ filterFunc =
+ (parts.length == 1 && !/[^\w#\.]/.test(filter)) ?
+ getSimpleFilterFunc(parts[0]) :
+ function(node){
+ return array.indexOf(query(filter, dom.byId(root)), node) != -1;
+ };
+ for(var x = 0, te; te = nodeList[x]; x++){
+ if(filterFunc(te)){ tmpNodeList.push(te); }
+ }
+ return tmpNodeList;
+ };
+ return query;
+});
+
+},
+'dojo/errors/RequestTimeoutError':function(){
+define("dojo/errors/RequestTimeoutError", ['./create', './RequestError'], function(create, RequestError){
+ // module:
+ // dojo/errors/RequestTimeoutError
+
+ /*=====
+ return function(){
+ // summary:
+ // TODOC
+ };
+ =====*/
+
+ return create("RequestTimeoutError", null, RequestError, {
+ dojoType: "timeout"
+ });
+});
+
+},
+'dojo/dom-style':function(){
+define("dojo/dom-style", ["./sniff", "./dom"], function(has, dom){
+ // module:
+ // dojo/dom-style
+
+ // =============================
+ // Style Functions
+ // =============================
+
+ // getComputedStyle drives most of the style code.
+ // Wherever possible, reuse the returned object.
+ //
+ // API functions below that need to access computed styles accept an
+ // optional computedStyle parameter.
+ // If this parameter is omitted, the functions will call getComputedStyle themselves.
+ // This way, calling code can access computedStyle once, and then pass the reference to
+ // multiple API functions.
+
+ // Although we normally eschew argument validation at this
+ // level, here we test argument 'node' for (duck)type,
+ // by testing nodeType, ecause 'document' is the 'parentNode' of 'body'
+ // it is frequently sent to this function even
+ // though it is not Element.
+ var getComputedStyle, style = {
+ // summary:
+ // This module defines the core dojo DOM style API.
+ };
+ if(has("webkit")){
+ getComputedStyle = function(/*DomNode*/ node){
+ var s;
+ if(node.nodeType == 1){
+ var dv = node.ownerDocument.defaultView;
+ s = dv.getComputedStyle(node, null);
+ if(!s && node.style){
+ node.style.display = "";
+ s = dv.getComputedStyle(node, null);
+ }
+ }
+ return s || {};
+ };
+ }else if(has("ie") && (has("ie") < 9 || has("quirks"))){
+ getComputedStyle = function(node){
+ // IE (as of 7) doesn't expose Element like sane browsers
+ // currentStyle can be null on IE8!
+ return node.nodeType == 1 /* ELEMENT_NODE*/ && node.currentStyle ? node.currentStyle : {};
+ };
+ }else{
+ getComputedStyle = function(node){
+ return node.nodeType == 1 /* ELEMENT_NODE*/ ?
+ node.ownerDocument.defaultView.getComputedStyle(node, null) : {};
+ };
+ }
+ style.getComputedStyle = getComputedStyle;
+ /*=====
+ style.getComputedStyle = function(node){
+ // summary:
+ // Returns a "computed style" object.
+ //
+ // description:
+ // Gets a "computed style" object which can be used to gather
+ // information about the current state of the rendered node.
+ //
+ // Note that this may behave differently on different browsers.
+ // Values may have different formats and value encodings across
+ // browsers.
+ //
+ // Note also that this method is expensive. Wherever possible,
+ // reuse the returned object.
+ //
+ // Use the dojo.style() method for more consistent (pixelized)
+ // return values.
+ //
+ // node: DOMNode
+ // A reference to a DOM node. Does NOT support taking an
+ // ID string for speed reasons.
+ // example:
+ // | dojo.getComputedStyle(dojo.byId('foo')).borderWidth;
+ //
+ // example:
+ // Reusing the returned object, avoiding multiple lookups:
+ // | var cs = dojo.getComputedStyle(dojo.byId("someNode"));
+ // | var w = cs.width, h = cs.height;
+ return; // CSS2Properties
+ };
+ =====*/
+
+ var toPixel;
+ if(!has("ie")){
+ toPixel = function(element, value){
+ // style values can be floats, client code may want
+ // to round for integer pixels.
+ return parseFloat(value) || 0;
+ };
+ }else{
+ toPixel = function(element, avalue){
+ if(!avalue){ return 0; }
+ // on IE7, medium is usually 4 pixels
+ if(avalue == "medium"){ return 4; }
+ // style values can be floats, client code may
+ // want to round this value for integer pixels.
+ if(avalue.slice && avalue.slice(-2) == 'px'){ return parseFloat(avalue); }
+ var s = element.style, rs = element.runtimeStyle, cs = element.currentStyle,
+ sLeft = s.left, rsLeft = rs.left;
+ rs.left = cs.left;
+ try{
+ // 'avalue' may be incompatible with style.left, which can cause IE to throw
+ // this has been observed for border widths using "thin", "medium", "thick" constants
+ // those particular constants could be trapped by a lookup
+ // but perhaps there are more
+ s.left = avalue;
+ avalue = s.pixelLeft;
+ }catch(e){
+ avalue = 0;
+ }
+ s.left = sLeft;
+ rs.left = rsLeft;
+ return avalue;
+ };
+ }
+ style.toPixelValue = toPixel;
+ /*=====
+ style.toPixelValue = function(node, value){
+ // summary:
+ // converts style value to pixels on IE or return a numeric value.
+ // node: DOMNode
+ // value: String
+ // returns: Number
+ };
+ =====*/
+
+ // FIXME: there opacity quirks on FF that we haven't ported over. Hrm.
+
+ var astr = "DXImageTransform.Microsoft.Alpha";
+ var af = function(n, f){
+ try{
+ return n.filters.item(astr);
+ }catch(e){
+ return f ? {} : null;
+ }
+ };
+
+ var _getOpacity =
+ has("ie") < 9 || (has("ie") && has("quirks")) ? function(node){
+ try{
+ return af(node).Opacity / 100; // Number
+ }catch(e){
+ return 1; // Number
+ }
+ } :
+ function(node){
+ return getComputedStyle(node).opacity;
+ };
+
+ var _setOpacity =
+ has("ie") < 9 || (has("ie") && has("quirks")) ? function(/*DomNode*/ node, /*Number*/ opacity){
+ var ov = opacity * 100, opaque = opacity == 1;
+ node.style.zoom = opaque ? "" : 1;
+
+ if(!af(node)){
+ if(opaque){
+ return opacity;
+ }
+ node.style.filter += " progid:" + astr + "(Opacity=" + ov + ")";
+ }else{
+ af(node, 1).Opacity = ov;
+ }
+
+ // on IE7 Alpha(Filter opacity=100) makes text look fuzzy so disable it altogether (bug #2661),
+ //but still update the opacity value so we can get a correct reading if it is read later.
+ af(node, 1).Enabled = !opaque;
+
+ if(node.tagName.toLowerCase() == "tr"){
+ for(var td = node.firstChild; td; td = td.nextSibling){
+ if(td.tagName.toLowerCase() == "td"){
+ _setOpacity(td, opacity);
+ }
+ }
+ }
+ return opacity;
+ } :
+ function(node, opacity){
+ return node.style.opacity = opacity;
+ };
+
+ var _pixelNamesCache = {
+ left: true, top: true
+ };
+ var _pixelRegExp = /margin|padding|width|height|max|min|offset/; // |border
+ function _toStyleValue(node, type, value){
+ //TODO: should we really be doing string case conversion here? Should we cache it? Need to profile!
+ type = type.toLowerCase();
+ if(has("ie")){
+ if(value == "auto"){
+ if(type == "height"){ return node.offsetHeight; }
+ if(type == "width"){ return node.offsetWidth; }
+ }
+ if(type == "fontweight"){
+ switch(value){
+ case 700: return "bold";
+ case 400:
+ default: return "normal";
+ }
+ }
+ }
+ if(!(type in _pixelNamesCache)){
+ _pixelNamesCache[type] = _pixelRegExp.test(type);
+ }
+ return _pixelNamesCache[type] ? toPixel(node, value) : value;
+ }
+
+ var _floatStyle = has("ie") ? "styleFloat" : "cssFloat",
+ _floatAliases = {"cssFloat": _floatStyle, "styleFloat": _floatStyle, "float": _floatStyle};
+
+ // public API
+
+ style.get = function getStyle(/*DOMNode|String*/ node, /*String?*/ name){
+ // summary:
+ // Accesses styles on a node.
+ // description:
+ // Getting the style value uses the computed style for the node, so the value
+ // will be a calculated value, not just the immediate node.style value.
+ // Also when getting values, use specific style names,
+ // like "borderBottomWidth" instead of "border" since compound values like
+ // "border" are not necessarily reflected as expected.
+ // If you want to get node dimensions, use `dojo.marginBox()`,
+ // `dojo.contentBox()` or `dojo.position()`.
+ // node: DOMNode|String
+ // id or reference to node to get style for
+ // name: String?
+ // the style property to get
+ // example:
+ // Passing only an ID or node returns the computed style object of
+ // the node:
+ // | dojo.getStyle("thinger");
+ // example:
+ // Passing a node and a style property returns the current
+ // normalized, computed value for that property:
+ // | dojo.getStyle("thinger", "opacity"); // 1 by default
+
+ var n = dom.byId(node), l = arguments.length, op = (name == "opacity");
+ if(l == 2 && op){
+ return _getOpacity(n);
+ }
+ name = _floatAliases[name] || name;
+ var s = style.getComputedStyle(n);
+ return (l == 1) ? s : _toStyleValue(n, name, s[name] || n.style[name]); /* CSS2Properties||String||Number */
+ };
+
+ style.set = function setStyle(/*DOMNode|String*/ node, /*String|Object*/ name, /*String?*/ value){
+ // summary:
+ // Sets styles on a node.
+ // node: DOMNode|String
+ // id or reference to node to set style for
+ // name: String|Object
+ // the style property to set in DOM-accessor format
+ // ("borderWidth", not "border-width") or an object with key/value
+ // pairs suitable for setting each property.
+ // value: String?
+ // If passed, sets value on the node for style, handling
+ // cross-browser concerns. When setting a pixel value,
+ // be sure to include "px" in the value. For instance, top: "200px".
+ // Otherwise, in some cases, some browsers will not apply the style.
+ //
+ // example:
+ // Passing a node, a style property, and a value changes the
+ // current display of the node and returns the new computed value
+ // | dojo.setStyle("thinger", "opacity", 0.5); // == 0.5
+ //
+ // example:
+ // Passing a node, an object-style style property sets each of the values in turn and returns the computed style object of the node:
+ // | dojo.setStyle("thinger", {
+ // | "opacity": 0.5,
+ // | "border": "3px solid black",
+ // | "height": "300px"
+ // | });
+ //
+ // example:
+ // When the CSS style property is hyphenated, the JavaScript property is camelCased.
+ // font-size becomes fontSize, and so on.
+ // | dojo.setStyle("thinger",{
+ // | fontSize:"14pt",
+ // | letterSpacing:"1.2em"
+ // | });
+ //
+ // example:
+ // dojo/NodeList implements .style() using the same syntax, omitting the "node" parameter, calling
+ // dojo.style() on every element of the list. See: `dojo.query()` and `dojo/NodeList`
+ // | dojo.query(".someClassName").style("visibility","hidden");
+ // | // or
+ // | dojo.query("#baz > div").style({
+ // | opacity:0.75,
+ // | fontSize:"13pt"
+ // | });
+
+ var n = dom.byId(node), l = arguments.length, op = (name == "opacity");
+ name = _floatAliases[name] || name;
+ if(l == 3){
+ return op ? _setOpacity(n, value) : n.style[name] = value; // Number
+ }
+ for(var x in name){
+ style.set(node, x, name[x]);
+ }
+ return style.getComputedStyle(n);
+ };
+
+ return style;
+});
+
+},
+'dojo/dom-geometry':function(){
+define(["./sniff", "./_base/window","./dom", "./dom-style"],
+ function(has, win, dom, style){
+ // module:
+ // dojo/dom-geometry
+
+ // the result object
+ var geom = {
+ // summary:
+ // This module defines the core dojo DOM geometry API.
+ };
+
+ // Box functions will assume this model.
+ // On IE/Opera, BORDER_BOX will be set if the primary document is in quirks mode.
+ // Can be set to change behavior of box setters.
+
+ // can be either:
+ // "border-box"
+ // "content-box" (default)
+ geom.boxModel = "content-box";
+
+ // We punt per-node box mode testing completely.
+ // If anybody cares, we can provide an additional (optional) unit
+ // that overrides existing code to include per-node box sensitivity.
+
+ // Opera documentation claims that Opera 9 uses border-box in BackCompat mode.
+ // but experiments (Opera 9.10.8679 on Windows Vista) indicate that it actually continues to use content-box.
+ // IIRC, earlier versions of Opera did in fact use border-box.
+ // Opera guys, this is really confusing. Opera being broken in quirks mode is not our fault.
+
+ if(has("ie") /*|| has("opera")*/){
+ // client code may have to adjust if compatMode varies across iframes
+ geom.boxModel = document.compatMode == "BackCompat" ? "border-box" : "content-box";
+ }
+
+ geom.getPadExtents = function getPadExtents(/*DomNode*/ node, /*Object*/ computedStyle){
+ // summary:
+ // Returns object with special values specifically useful for node
+ // fitting.
+ // description:
+ // Returns an object with `w`, `h`, `l`, `t` properties:
+ // | l/t/r/b = left/top/right/bottom padding (respectively)
+ // | w = the total of the left and right padding
+ // | h = the total of the top and bottom padding
+ // If 'node' has position, l/t forms the origin for child nodes.
+ // The w/h are used for calculating boxes.
+ // Normally application code will not need to invoke this
+ // directly, and will use the ...box... functions instead.
+ // node: DOMNode
+ // computedStyle: Object?
+ // This parameter accepts computed styles object.
+ // If this parameter is omitted, the functions will call
+ // dojo.getComputedStyle to get one. It is a better way, calling
+ // dojo.computedStyle once, and then pass the reference to this
+ // computedStyle parameter. Wherever possible, reuse the returned
+ // object of dojo/dom-style.getComputedStyle().
+
+ node = dom.byId(node);
+ var s = computedStyle || style.getComputedStyle(node), px = style.toPixelValue,
+ l = px(node, s.paddingLeft), t = px(node, s.paddingTop), r = px(node, s.paddingRight), b = px(node, s.paddingBottom);
+ return {l: l, t: t, r: r, b: b, w: l + r, h: t + b};
+ };
+
+ var none = "none";
+
+ geom.getBorderExtents = function getBorderExtents(/*DomNode*/ node, /*Object*/ computedStyle){
+ // summary:
+ // returns an object with properties useful for noting the border
+ // dimensions.
+ // description:
+ // - l/t/r/b = the sum of left/top/right/bottom border (respectively)
+ // - w = the sum of the left and right border
+ // - h = the sum of the top and bottom border
+ //
+ // The w/h are used for calculating boxes.
+ // Normally application code will not need to invoke this
+ // directly, and will use the ...box... functions instead.
+ // node: DOMNode
+ // computedStyle: Object?
+ // This parameter accepts computed styles object.
+ // If this parameter is omitted, the functions will call
+ // dojo.getComputedStyle to get one. It is a better way, calling
+ // dojo.computedStyle once, and then pass the reference to this
+ // computedStyle parameter. Wherever possible, reuse the returned
+ // object of dojo/dom-style.getComputedStyle().
+
+ node = dom.byId(node);
+ var px = style.toPixelValue, s = computedStyle || style.getComputedStyle(node),
+ l = s.borderLeftStyle != none ? px(node, s.borderLeftWidth) : 0,
+ t = s.borderTopStyle != none ? px(node, s.borderTopWidth) : 0,
+ r = s.borderRightStyle != none ? px(node, s.borderRightWidth) : 0,
+ b = s.borderBottomStyle != none ? px(node, s.borderBottomWidth) : 0;
+ return {l: l, t: t, r: r, b: b, w: l + r, h: t + b};
+ };
+
+ geom.getPadBorderExtents = function getPadBorderExtents(/*DomNode*/ node, /*Object*/ computedStyle){
+ // summary:
+ // Returns object with properties useful for box fitting with
+ // regards to padding.
+ // description:
+ // - l/t/r/b = the sum of left/top/right/bottom padding and left/top/right/bottom border (respectively)
+ // - w = the sum of the left and right padding and border
+ // - h = the sum of the top and bottom padding and border
+ //
+ // The w/h are used for calculating boxes.
+ // Normally application code will not need to invoke this
+ // directly, and will use the ...box... functions instead.
+ // node: DOMNode
+ // computedStyle: Object?
+ // This parameter accepts computed styles object.
+ // If this parameter is omitted, the functions will call
+ // dojo.getComputedStyle to get one. It is a better way, calling
+ // dojo.computedStyle once, and then pass the reference to this
+ // computedStyle parameter. Wherever possible, reuse the returned
+ // object of dojo/dom-style.getComputedStyle().
+
+ node = dom.byId(node);
+ var s = computedStyle || style.getComputedStyle(node),
+ p = geom.getPadExtents(node, s),
+ b = geom.getBorderExtents(node, s);
+ return {
+ l: p.l + b.l,
+ t: p.t + b.t,
+ r: p.r + b.r,
+ b: p.b + b.b,
+ w: p.w + b.w,
+ h: p.h + b.h
+ };
+ };
+
+ geom.getMarginExtents = function getMarginExtents(node, computedStyle){
+ // summary:
+ // returns object with properties useful for box fitting with
+ // regards to box margins (i.e., the outer-box).
+ //
+ // - l/t = marginLeft, marginTop, respectively
+ // - w = total width, margin inclusive
+ // - h = total height, margin inclusive
+ //
+ // The w/h are used for calculating boxes.
+ // Normally application code will not need to invoke this
+ // directly, and will use the ...box... functions instead.
+ // node: DOMNode
+ // computedStyle: Object?
+ // This parameter accepts computed styles object.
+ // If this parameter is omitted, the functions will call
+ // dojo.getComputedStyle to get one. It is a better way, calling
+ // dojo.computedStyle once, and then pass the reference to this
+ // computedStyle parameter. Wherever possible, reuse the returned
+ // object of dojo/dom-style.getComputedStyle().
+
+ node = dom.byId(node);
+ var s = computedStyle || style.getComputedStyle(node), px = style.toPixelValue,
+ l = px(node, s.marginLeft), t = px(node, s.marginTop), r = px(node, s.marginRight), b = px(node, s.marginBottom);
+ return {l: l, t: t, r: r, b: b, w: l + r, h: t + b};
+ };
+
+ // Box getters work in any box context because offsetWidth/clientWidth
+ // are invariant wrt box context
+ //
+ // They do *not* work for display: inline objects that have padding styles
+ // because the user agent ignores padding (it's bogus styling in any case)
+ //
+ // Be careful with IMGs because they are inline or block depending on
+ // browser and browser mode.
+
+ // Although it would be easier to read, there are not separate versions of
+ // _getMarginBox for each browser because:
+ // 1. the branching is not expensive
+ // 2. factoring the shared code wastes cycles (function call overhead)
+ // 3. duplicating the shared code wastes bytes
+
+ geom.getMarginBox = function getMarginBox(/*DomNode*/ node, /*Object*/ computedStyle){
+ // summary:
+ // returns an object that encodes the width, height, left and top
+ // positions of the node's margin box.
+ // node: DOMNode
+ // computedStyle: Object?
+ // This parameter accepts computed styles object.
+ // If this parameter is omitted, the functions will call
+ // dojo.getComputedStyle to get one. It is a better way, calling
+ // dojo.computedStyle once, and then pass the reference to this
+ // computedStyle parameter. Wherever possible, reuse the returned
+ // object of dojo/dom-style.getComputedStyle().
+
+ node = dom.byId(node);
+ var s = computedStyle || style.getComputedStyle(node), me = geom.getMarginExtents(node, s),
+ l = node.offsetLeft - me.l, t = node.offsetTop - me.t, p = node.parentNode, px = style.toPixelValue, pcs;
+ if(has("mozilla")){
+ // Mozilla:
+ // If offsetParent has a computed overflow != visible, the offsetLeft is decreased
+ // by the parent's border.
+ // We don't want to compute the parent's style, so instead we examine node's
+ // computed left/top which is more stable.
+ var sl = parseFloat(s.left), st = parseFloat(s.top);
+ if(!isNaN(sl) && !isNaN(st)){
+ l = sl;
+ t = st;
+ }else{
+ // If child's computed left/top are not parseable as a number (e.g. "auto"), we
+ // have no choice but to examine the parent's computed style.
+ if(p && p.style){
+ pcs = style.getComputedStyle(p);
+ if(pcs.overflow != "visible"){
+ l += pcs.borderLeftStyle != none ? px(node, pcs.borderLeftWidth) : 0;
+ t += pcs.borderTopStyle != none ? px(node, pcs.borderTopWidth) : 0;
+ }
+ }
+ }
+ }else if(has("opera") || (has("ie") == 8 && !has("quirks"))){
+ // On Opera and IE 8, offsetLeft/Top includes the parent's border
+ if(p){
+ pcs = style.getComputedStyle(p);
+ l -= pcs.borderLeftStyle != none ? px(node, pcs.borderLeftWidth) : 0;
+ t -= pcs.borderTopStyle != none ? px(node, pcs.borderTopWidth) : 0;
+ }
+ }
+ return {l: l, t: t, w: node.offsetWidth + me.w, h: node.offsetHeight + me.h};
+ };
+
+ geom.getContentBox = function getContentBox(node, computedStyle){
+ // summary:
+ // Returns an object that encodes the width, height, left and top
+ // positions of the node's content box, irrespective of the
+ // current box model.
+ // node: DOMNode
+ // computedStyle: Object?
+ // This parameter accepts computed styles object.
+ // If this parameter is omitted, the functions will call
+ // dojo.getComputedStyle to get one. It is a better way, calling
+ // dojo.computedStyle once, and then pass the reference to this
+ // computedStyle parameter. Wherever possible, reuse the returned
+ // object of dojo/dom-style.getComputedStyle().
+
+ // clientWidth/Height are important since the automatically account for scrollbars
+ // fallback to offsetWidth/Height for special cases (see #3378)
+ node = dom.byId(node);
+ var s = computedStyle || style.getComputedStyle(node), w = node.clientWidth, h,
+ pe = geom.getPadExtents(node, s), be = geom.getBorderExtents(node, s);
+ if(!w){
+ w = node.offsetWidth;
+ h = node.offsetHeight;
+ }else{
+ h = node.clientHeight;
+ be.w = be.h = 0;
+ }
+ // On Opera, offsetLeft includes the parent's border
+ if(has("opera")){
+ pe.l += be.l;
+ pe.t += be.t;
+ }
+ return {l: pe.l, t: pe.t, w: w - pe.w - be.w, h: h - pe.h - be.h};
+ };
+
+ // Box setters depend on box context because interpretation of width/height styles
+ // vary wrt box context.
+ //
+ // The value of boxModel is used to determine box context.
+ // boxModel can be set directly to change behavior.
+ //
+ // Beware of display: inline objects that have padding styles
+ // because the user agent ignores padding (it's a bogus setup anyway)
+ //
+ // Be careful with IMGs because they are inline or block depending on
+ // browser and browser mode.
+ //
+ // Elements other than DIV may have special quirks, like built-in
+ // margins or padding, or values not detectable via computedStyle.
+ // In particular, margins on TABLE do not seems to appear
+ // at all in computedStyle on Mozilla.
+
+ function setBox(/*DomNode*/ node, /*Number?*/ l, /*Number?*/ t, /*Number?*/ w, /*Number?*/ h, /*String?*/ u){
+ // summary:
+ // sets width/height/left/top in the current (native) box-model
+ // dimensions. Uses the unit passed in u.
+ // node:
+ // DOM Node reference. Id string not supported for performance
+ // reasons.
+ // l:
+ // left offset from parent.
+ // t:
+ // top offset from parent.
+ // w:
+ // width in current box model.
+ // h:
+ // width in current box model.
+ // u:
+ // unit measure to use for other measures. Defaults to "px".
+ u = u || "px";
+ var s = node.style;
+ if(!isNaN(l)){
+ s.left = l + u;
+ }
+ if(!isNaN(t)){
+ s.top = t + u;
+ }
+ if(w >= 0){
+ s.width = w + u;
+ }
+ if(h >= 0){
+ s.height = h + u;
+ }
+ }
+
+ function isButtonTag(/*DomNode*/ node){
+ // summary:
+ // True if the node is BUTTON or INPUT.type="button".
+ return node.tagName.toLowerCase() == "button" ||
+ node.tagName.toLowerCase() == "input" && (node.getAttribute("type") || "").toLowerCase() == "button"; // boolean
+ }
+
+ function usesBorderBox(/*DomNode*/ node){
+ // summary:
+ // True if the node uses border-box layout.
+
+ // We could test the computed style of node to see if a particular box
+ // has been specified, but there are details and we choose not to bother.
+
+ // TABLE and BUTTON (and INPUT type=button) are always border-box by default.
+ // If you have assigned a different box to either one via CSS then
+ // box functions will break.
+
+ return geom.boxModel == "border-box" || node.tagName.toLowerCase() == "table" || isButtonTag(node); // boolean
+ }
+
+ geom.setContentSize = function setContentSize(/*DomNode*/ node, /*Object*/ box, /*Object*/ computedStyle){
+ // summary:
+ // Sets the size of the node's contents, irrespective of margins,
+ // padding, or borders.
+ // node: DOMNode
+ // box: Object
+ // hash with optional "w", and "h" properties for "width", and "height"
+ // respectively. All specified properties should have numeric values in whole pixels.
+ // computedStyle: Object?
+ // This parameter accepts computed styles object.
+ // If this parameter is omitted, the functions will call
+ // dojo.getComputedStyle to get one. It is a better way, calling
+ // dojo.computedStyle once, and then pass the reference to this
+ // computedStyle parameter. Wherever possible, reuse the returned
+ // object of dojo/dom-style.getComputedStyle().
+
+ node = dom.byId(node);
+ var w = box.w, h = box.h;
+ if(usesBorderBox(node)){
+ var pb = geom.getPadBorderExtents(node, computedStyle);
+ if(w >= 0){
+ w += pb.w;
+ }
+ if(h >= 0){
+ h += pb.h;
+ }
+ }
+ setBox(node, NaN, NaN, w, h);
+ };
+
+ var nilExtents = {l: 0, t: 0, w: 0, h: 0};
+
+ geom.setMarginBox = function setMarginBox(/*DomNode*/ node, /*Object*/ box, /*Object*/ computedStyle){
+ // summary:
+ // sets the size of the node's margin box and placement
+ // (left/top), irrespective of box model. Think of it as a
+ // passthrough to setBox that handles box-model vagaries for
+ // you.
+ // node: DOMNode
+ // box: Object
+ // hash with optional "l", "t", "w", and "h" properties for "left", "right", "width", and "height"
+ // respectively. All specified properties should have numeric values in whole pixels.
+ // computedStyle: Object?
+ // This parameter accepts computed styles object.
+ // If this parameter is omitted, the functions will call
+ // dojo.getComputedStyle to get one. It is a better way, calling
+ // dojo.computedStyle once, and then pass the reference to this
+ // computedStyle parameter. Wherever possible, reuse the returned
+ // object of dojo/dom-style.getComputedStyle().
+
+ node = dom.byId(node);
+ var s = computedStyle || style.getComputedStyle(node), w = box.w, h = box.h,
+ // Some elements have special padding, margin, and box-model settings.
+ // To use box functions you may need to set padding, margin explicitly.
+ // Controlling box-model is harder, in a pinch you might set dojo/dom-geometry.boxModel.
+ pb = usesBorderBox(node) ? nilExtents : geom.getPadBorderExtents(node, s),
+ mb = geom.getMarginExtents(node, s);
+ if(has("webkit")){
+ // on Safari (3.1.2), button nodes with no explicit size have a default margin
+ // setting an explicit size eliminates the margin.
+ // We have to swizzle the width to get correct margin reading.
+ if(isButtonTag(node)){
+ var ns = node.style;
+ if(w >= 0 && !ns.width){
+ ns.width = "4px";
+ }
+ if(h >= 0 && !ns.height){
+ ns.height = "4px";
+ }
+ }
+ }
+ if(w >= 0){
+ w = Math.max(w - pb.w - mb.w, 0);
+ }
+ if(h >= 0){
+ h = Math.max(h - pb.h - mb.h, 0);
+ }
+ setBox(node, box.l, box.t, w, h);
+ };
+
+ // =============================
+ // Positioning
+ // =============================
+
+ geom.isBodyLtr = function isBodyLtr(/*Document?*/ doc){
+ // summary:
+ // Returns true if the current language is left-to-right, and false otherwise.
+ // doc: Document?
+ // Optional document to query. If unspecified, use win.doc.
+ // returns: Boolean
+
+ doc = doc || win.doc;
+ return (win.body(doc).dir || doc.documentElement.dir || "ltr").toLowerCase() == "ltr"; // Boolean
+ };
+
+ geom.docScroll = function docScroll(/*Document?*/ doc){
+ // summary:
+ // Returns an object with {node, x, y} with corresponding offsets.
+ // doc: Document?
+ // Optional document to query. If unspecified, use win.doc.
+ // returns: Object
+
+ doc = doc || win.doc;
+ var node = win.doc.parentWindow || win.doc.defaultView; // use UI window, not dojo.global window. TODO: use dojo/window::get() except for circular dependency problem
+ return "pageXOffset" in node ? {x: node.pageXOffset, y: node.pageYOffset } :
+ (node = has("quirks") ? win.body(doc) : doc.documentElement) &&
+ {x: geom.fixIeBiDiScrollLeft(node.scrollLeft || 0, doc), y: node.scrollTop || 0 };
+ };
+
+ if(has("ie")){
+ geom.getIeDocumentElementOffset = function getIeDocumentElementOffset(/*Document?*/ doc){
+ // summary:
+ // returns the offset in x and y from the document body to the
+ // visual edge of the page for IE
+ // doc: Document?
+ // Optional document to query. If unspecified, use win.doc.
+ // description:
+ // The following values in IE contain an offset:
+ // | event.clientX
+ // | event.clientY
+ // | node.getBoundingClientRect().left
+ // | node.getBoundingClientRect().top
+ // But other position related values do not contain this offset,
+ // such as node.offsetLeft, node.offsetTop, node.style.left and
+ // node.style.top. The offset is always (2, 2) in LTR direction.
+ // When the body is in RTL direction, the offset counts the width
+ // of left scroll bar's width. This function computes the actual
+ // offset.
+
+ //NOTE: assumes we're being called in an IE browser
+
+ doc = doc || win.doc;
+ var de = doc.documentElement; // only deal with HTML element here, position() handles body/quirks
+
+ if(has("ie") < 8){
+ var r = de.getBoundingClientRect(), // works well for IE6+
+ l = r.left, t = r.top;
+ if(has("ie") < 7){
+ l += de.clientLeft; // scrollbar size in strict/RTL, or,
+ t += de.clientTop; // HTML border size in strict
+ }
+ return {
+ x: l < 0 ? 0 : l, // FRAME element border size can lead to inaccurate negative values
+ y: t < 0 ? 0 : t
+ };
+ }else{
+ return {
+ x: 0,
+ y: 0
+ };
+ }
+ };
+ }
+
+ geom.fixIeBiDiScrollLeft = function fixIeBiDiScrollLeft(/*Integer*/ scrollLeft, /*Document?*/ doc){
+ // summary:
+ // In RTL direction, scrollLeft should be a negative value, but IE
+ // returns a positive one. All codes using documentElement.scrollLeft
+ // must call this function to fix this error, otherwise the position
+ // will offset to right when there is a horizontal scrollbar.
+ // scrollLeft: Number
+ // doc: Document?
+ // Optional document to query. If unspecified, use win.doc.
+ // returns: Number
+
+ // In RTL direction, scrollLeft should be a negative value, but IE
+ // returns a positive one. All codes using documentElement.scrollLeft
+ // must call this function to fix this error, otherwise the position
+ // will offset to right when there is a horizontal scrollbar.
+
+ doc = doc || win.doc;
+ var ie = has("ie");
+ if(ie && !geom.isBodyLtr(doc)){
+ var qk = has("quirks"),
+ de = qk ? win.body(doc) : doc.documentElement,
+ pwin = win.global; // TODO: use winUtils.get(doc) after resolving circular dependency b/w dom-geometry.js and dojo/window.js
+ if(ie == 6 && !qk && pwin.frameElement && de.scrollHeight > de.clientHeight){
+ scrollLeft += de.clientLeft; // workaround ie6+strict+rtl+iframe+vertical-scrollbar bug where clientWidth is too small by clientLeft pixels
+ }
+ return (ie < 8 || qk) ? (scrollLeft + de.clientWidth - de.scrollWidth) : -scrollLeft; // Integer
+ }
+ return scrollLeft; // Integer
+ };
+
+ geom.position = function(/*DomNode*/ node, /*Boolean?*/ includeScroll){
+ // summary:
+ // Gets the position and size of the passed element relative to
+ // the viewport (if includeScroll==false), or relative to the
+ // document root (if includeScroll==true).
+ //
+ // description:
+ // Returns an object of the form:
+ // `{ x: 100, y: 300, w: 20, h: 15 }`.
+ // If includeScroll==true, the x and y values will include any
+ // document offsets that may affect the position relative to the
+ // viewport.
+ // Uses the border-box model (inclusive of border and padding but
+ // not margin). Does not act as a setter.
+ // node: DOMNode|String
+ // includeScroll: Boolean?
+ // returns: Object
+
+ node = dom.byId(node);
+ var db = win.body(node.ownerDocument),
+ ret = node.getBoundingClientRect();
+ ret = {x: ret.left, y: ret.top, w: ret.right - ret.left, h: ret.bottom - ret.top};
+
+ if(has("ie")){
+ // On IE there's a 2px offset that we need to adjust for, see dojo.getIeDocumentElementOffset()
+ var offset = geom.getIeDocumentElementOffset(node.ownerDocument);
+
+ // fixes the position in IE, quirks mode
+ ret.x -= offset.x + (has("quirks") ? db.clientLeft + db.offsetLeft : 0);
+ ret.y -= offset.y + (has("quirks") ? db.clientTop + db.offsetTop : 0);
+ }
+
+ // account for document scrolling
+ // if offsetParent is used, ret value already includes scroll position
+ // so we may have to actually remove that value if !includeScroll
+ if(includeScroll){
+ var scroll = geom.docScroll(node.ownerDocument);
+ ret.x += scroll.x;
+ ret.y += scroll.y;
+ }
+
+ return ret; // Object
+ };
+
+ // random "private" functions wildly used throughout the toolkit
+
+ geom.getMarginSize = function getMarginSize(/*DomNode*/ node, /*Object*/ computedStyle){
+ // summary:
+ // returns an object that encodes the width and height of
+ // the node's margin box
+ // node: DOMNode|String
+ // computedStyle: Object?
+ // This parameter accepts computed styles object.
+ // If this parameter is omitted, the functions will call
+ // dojo.getComputedStyle to get one. It is a better way, calling
+ // dojo.computedStyle once, and then pass the reference to this
+ // computedStyle parameter. Wherever possible, reuse the returned
+ // object of dojo/dom-style.getComputedStyle().
+
+ node = dom.byId(node);
+ var me = geom.getMarginExtents(node, computedStyle || style.getComputedStyle(node));
+ var size = node.getBoundingClientRect();
+ return {
+ w: (size.right - size.left) + me.w,
+ h: (size.bottom - size.top) + me.h
+ };
+ };
+
+ geom.normalizeEvent = function(event){
+ // summary:
+ // Normalizes the geometry of a DOM event, normalizing the pageX, pageY,
+ // offsetX, offsetY, layerX, and layerX properties
+ // event: Object
+ if(!("layerX" in event)){
+ event.layerX = event.offsetX;
+ event.layerY = event.offsetY;
+ }
+ if(!has("dom-addeventlistener")){
+ // old IE version
+ // FIXME: scroll position query is duped from dojo.html to
+ // avoid dependency on that entire module. Now that HTML is in
+ // Base, we should convert back to something similar there.
+ var se = event.target;
+ var doc = (se && se.ownerDocument) || document;
+ // DO NOT replace the following to use dojo.body(), in IE, document.documentElement should be used
+ // here rather than document.body
+ var docBody = has("quirks") ? doc.body : doc.documentElement;
+ var offset = geom.getIeDocumentElementOffset(doc);
+ event.pageX = event.clientX + geom.fixIeBiDiScrollLeft(docBody.scrollLeft || 0, doc) - offset.x;
+ event.pageY = event.clientY + (docBody.scrollTop || 0) - offset.y;
+ }
+ };
+
+ // TODO: evaluate separate getters/setters for position and sizes?
+
+ return geom;
+});
+
+},
+'dojo/dom-prop':function(){
+define(["exports", "./_base/kernel", "./sniff", "./_base/lang", "./dom", "./dom-style", "./dom-construct", "./_base/connect"],
+ function(exports, dojo, has, lang, dom, style, ctr, conn){
+ // module:
+ // dojo/dom-prop
+ // summary:
+ // This module defines the core dojo DOM properties API.
+ // Indirectly depends on dojo.empty() and dojo.toDom().
+
+ // TODOC: summary not showing up in output, see https://github.com/csnover/js-doc-parse/issues/42
+
+ // =============================
+ // Element properties Functions
+ // =============================
+
+ // helper to connect events
+ var _evtHdlrMap = {}, _ctr = 0, _attrId = dojo._scopeName + "attrid";
+
+ exports.names = {
+ // properties renamed to avoid clashes with reserved words
+ "class": "className",
+ "for": "htmlFor",
+ // properties written as camelCase
+ tabindex: "tabIndex",
+ readonly: "readOnly",
+ colspan: "colSpan",
+ frameborder: "frameBorder",
+ rowspan: "rowSpan",
+ valuetype: "valueType"
+ };
+
+ exports.get = function getProp(/*DOMNode|String*/ node, /*String*/ name){
+ // summary:
+ // Gets a property on an HTML element.
+ // description:
+ // Handles normalized getting of properties on DOM nodes.
+ //
+ // node: DOMNode|String
+ // id or reference to the element to get the property on
+ // name: String
+ // the name of the property to get.
+ // returns:
+ // the value of the requested property or its default value
+ //
+ // example:
+ // | // get the current value of the "foo" property on a node
+ // | dojo.getProp(dojo.byId("nodeId"), "foo");
+ // | // or we can just pass the id:
+ // | dojo.getProp("nodeId", "foo");
+
+ node = dom.byId(node);
+ var lc = name.toLowerCase(), propName = exports.names[lc] || name;
+ return node[propName]; // Anything
+ };
+
+ exports.set = function setProp(/*DOMNode|String*/ node, /*String|Object*/ name, /*String?*/ value){
+ // summary:
+ // Sets a property on an HTML element.
+ // description:
+ // Handles normalized setting of properties on DOM nodes.
+ //
+ // When passing functions as values, note that they will not be
+ // directly assigned to slots on the node, but rather the default
+ // behavior will be removed and the new behavior will be added
+ // using `dojo.connect()`, meaning that event handler properties
+ // will be normalized and that some caveats with regards to
+ // non-standard behaviors for onsubmit apply. Namely that you
+ // should cancel form submission using `dojo.stopEvent()` on the
+ // passed event object instead of returning a boolean value from
+ // the handler itself.
+ // node: DOMNode|String
+ // id or reference to the element to set the property on
+ // name: String|Object
+ // the name of the property to set, or a hash object to set
+ // multiple properties at once.
+ // value: String?
+ // The value to set for the property
+ // returns:
+ // the DOM node
+ //
+ // example:
+ // | // use prop() to set the tab index
+ // | dojo.setProp("nodeId", "tabIndex", 3);
+ // |
+ //
+ // example:
+ // Set multiple values at once, including event handlers:
+ // | dojo.setProp("formId", {
+ // | "foo": "bar",
+ // | "tabIndex": -1,
+ // | "method": "POST",
+ // | "onsubmit": function(e){
+ // | // stop submitting the form. Note that the IE behavior
+ // | // of returning true or false will have no effect here
+ // | // since our handler is connect()ed to the built-in
+ // | // onsubmit behavior and so we need to use
+ // | // dojo.stopEvent() to ensure that the submission
+ // | // doesn't proceed.
+ // | dojo.stopEvent(e);
+ // |
+ // | // submit the form with Ajax
+ // | dojo.xhrPost({ form: "formId" });
+ // | }
+ // | });
+ //
+ // example:
+ // Style is s special case: Only set with an object hash of styles
+ // | dojo.setProp("someNode",{
+ // | id:"bar",
+ // | style:{
+ // | width:"200px", height:"100px", color:"#000"
+ // | }
+ // | });
+ //
+ // example:
+ // Again, only set style as an object hash of styles:
+ // | var obj = { color:"#fff", backgroundColor:"#000" };
+ // | dojo.setProp("someNode", "style", obj);
+ // |
+ // | // though shorter to use `dojo.style()` in this case:
+ // | dojo.style("someNode", obj);
+
+ node = dom.byId(node);
+ var l = arguments.length;
+ if(l == 2 && typeof name != "string"){ // inline'd type check
+ // the object form of setter: the 2nd argument is a dictionary
+ for(var x in name){
+ exports.set(node, x, name[x]);
+ }
+ return node; // DomNode
+ }
+ var lc = name.toLowerCase(), propName = exports.names[lc] || name;
+ if(propName == "style" && typeof value != "string"){ // inline'd type check
+ // special case: setting a style
+ style.set(node, value);
+ return node; // DomNode
+ }
+ if(propName == "innerHTML"){
+ // special case: assigning HTML
+ // the hash lists elements with read-only innerHTML on IE
+ if(has("ie") && node.tagName.toLowerCase() in {col: 1, colgroup: 1,
+ table: 1, tbody: 1, tfoot: 1, thead: 1, tr: 1, title: 1}){
+ ctr.empty(node);
+ node.appendChild(ctr.toDom(value, node.ownerDocument));
+ }else{
+ node[propName] = value;
+ }
+ return node; // DomNode
+ }
+ if(lang.isFunction(value)){
+ // special case: assigning an event handler
+ // clobber if we can
+ var attrId = node[_attrId];
+ if(!attrId){
+ attrId = _ctr++;
+ node[_attrId] = attrId;
+ }
+ if(!_evtHdlrMap[attrId]){
+ _evtHdlrMap[attrId] = {};
+ }
+ var h = _evtHdlrMap[attrId][propName];
+ if(h){
+ //h.remove();
+ conn.disconnect(h);
+ }else{
+ try{
+ delete node[propName];
+ }catch(e){}
+ }
+ // ensure that event objects are normalized, etc.
+ if(value){
+ //_evtHdlrMap[attrId][propName] = on(node, propName, value);
+ _evtHdlrMap[attrId][propName] = conn.connect(node, propName, value);
+ }else{
+ node[propName] = null;
+ }
+ return node; // DomNode
+ }
+ node[propName] = value;
+ return node; // DomNode
+ };
+});
+
+},
+'dojo/when':function(){
+define([
+ "./Deferred",
+ "./promise/Promise"
+], function(Deferred, Promise){
+ "use strict";
+
+ // module:
+ // dojo/when
+
+ return function when(valueOrPromise, callback, errback, progback){
+ // summary:
+ // Transparently applies callbacks to values and/or promises.
+ // description:
+ // Accepts promises but also transparently handles non-promises. If no
+ // callbacks are provided returns a promise, regardless of the initial
+ // value. Foreign promises are converted.
+ //
+ // If callbacks are provided and the initial value is not a promise,
+ // the callback is executed immediately with no error handling. Returns
+ // a promise if the initial value is a promise, or the result of the
+ // callback otherwise.
+ // valueOrPromise:
+ // Either a regular value or an object with a `then()` method that
+ // follows the Promises/A specification.
+ // callback: Function?
+ // Callback to be invoked when the promise is resolved, or a non-promise
+ // is received.
+ // errback: Function?
+ // Callback to be invoked when the promise is rejected.
+ // progback: Function?
+ // Callback to be invoked when the promise emits a progress update.
+ // returns: dojo/promise/Promise
+ // Promise, or if a callback is provided, the result of the callback.
+
+ var receivedPromise = valueOrPromise && typeof valueOrPromise.then === "function";
+ var nativePromise = receivedPromise && valueOrPromise instanceof Promise;
+
+ if(!receivedPromise){
+ if(callback){
+ return callback(valueOrPromise);
+ }else{
+ return new Deferred().resolve(valueOrPromise);
+ }
+ }else if(!nativePromise){
+ var deferred = new Deferred(valueOrPromise.cancel);
+ valueOrPromise.then(deferred.resolve, deferred.reject, deferred.progress);
+ valueOrPromise = deferred.promise;
+ }
+
+ if(callback || errback || progback){
+ return valueOrPromise.then(callback, errback, progback);
+ }
+ return valueOrPromise;
+ };
+});
+
+},
+'dojo/dom-attr':function(){
+define(["exports", "./sniff", "./_base/lang", "./dom", "./dom-style", "./dom-prop"],
+ function(exports, has, lang, dom, style, prop){
+ // module:
+ // dojo/dom-attr
+ // summary:
+ // This module defines the core dojo DOM attributes API.
+
+ // TODOC: summary not showing up in output see https://github.com/csnover/js-doc-parse/issues/42
+
+ // =============================
+ // Element attribute Functions
+ // =============================
+
+ // This module will be obsolete soon. Use dojo/prop instead.
+
+ // dojo.attr() should conform to http://www.w3.org/TR/DOM-Level-2-Core/
+
+ // attribute-related functions (to be obsolete soon)
+
+ var forcePropNames = {
+ innerHTML: 1,
+ className: 1,
+ htmlFor: has("ie"),
+ value: 1
+ },
+ attrNames = {
+ // original attribute names
+ classname: "class",
+ htmlfor: "for",
+ // for IE
+ tabindex: "tabIndex",
+ readonly: "readOnly"
+ };
+
+ function _hasAttr(node, name){
+ var attr = node.getAttributeNode && node.getAttributeNode(name);
+ return attr && attr.specified; // Boolean
+ }
+
+ // There is a difference in the presence of certain properties and their default values
+ // between browsers. For example, on IE "disabled" is present on all elements,
+ // but it is value is "false"; "tabIndex" of returns 0 by default on IE, yet other browsers
+ // can return -1.
+
+ exports.has = function hasAttr(/*DOMNode|String*/ node, /*String*/ name){
+ // summary:
+ // Returns true if the requested attribute is specified on the
+ // given element, and false otherwise.
+ // node: DOMNode|String
+ // id or reference to the element to check
+ // name: String
+ // the name of the attribute
+ // returns: Boolean
+ // true if the requested attribute is specified on the
+ // given element, and false otherwise
+
+ var lc = name.toLowerCase();
+ return forcePropNames[prop.names[lc] || name] || _hasAttr(dom.byId(node), attrNames[lc] || name); // Boolean
+ };
+
+ exports.get = function getAttr(/*DOMNode|String*/ node, /*String*/ name){
+ // summary:
+ // Gets an attribute on an HTML element.
+ // description:
+ // Handles normalized getting of attributes on DOM Nodes.
+ // node: DOMNode|String
+ // id or reference to the element to get the attribute on
+ // name: String
+ // the name of the attribute to get.
+ // returns:
+ // the value of the requested attribute or null if that attribute does not have a specified or
+ // default value;
+ //
+ // example:
+ // | // get the current value of the "foo" attribute on a node
+ // | dojo.getAttr(dojo.byId("nodeId"), "foo");
+ // | // or we can just pass the id:
+ // | dojo.getAttr("nodeId", "foo");
+
+ node = dom.byId(node);
+ var lc = name.toLowerCase(),
+ propName = prop.names[lc] || name,
+ forceProp = forcePropNames[propName],
+ value = node[propName]; // should we access this attribute via a property or via getAttribute()?
+
+ if(forceProp && typeof value != "undefined"){
+ // node's property
+ return value; // Anything
+ }
+ if(propName != "href" && (typeof value == "boolean" || lang.isFunction(value))){
+ // node's property
+ return value; // Anything
+ }
+ // node's attribute
+ // we need _hasAttr() here to guard against IE returning a default value
+ var attrName = attrNames[lc] || name;
+ return _hasAttr(node, attrName) ? node.getAttribute(attrName) : null; // Anything
+ };
+
+ exports.set = function setAttr(/*DOMNode|String*/ node, /*String|Object*/ name, /*String?*/ value){
+ // summary:
+ // Sets an attribute on an HTML element.
+ // description:
+ // Handles normalized setting of attributes on DOM Nodes.
+ //
+ // When passing functions as values, note that they will not be
+ // directly assigned to slots on the node, but rather the default
+ // behavior will be removed and the new behavior will be added
+ // using `dojo.connect()`, meaning that event handler properties
+ // will be normalized and that some caveats with regards to
+ // non-standard behaviors for onsubmit apply. Namely that you
+ // should cancel form submission using `dojo.stopEvent()` on the
+ // passed event object instead of returning a boolean value from
+ // the handler itself.
+ // node: DOMNode|String
+ // id or reference to the element to set the attribute on
+ // name: String|Object
+ // the name of the attribute to set, or a hash of key-value pairs to set.
+ // value: String?
+ // the value to set for the attribute, if the name is a string.
+ // returns:
+ // the DOM node
+ //
+ // example:
+ // | // use attr() to set the tab index
+ // | dojo.setAttr("nodeId", "tabIndex", 3);
+ //
+ // example:
+ // Set multiple values at once, including event handlers:
+ // | dojo.setAttr("formId", {
+ // | "foo": "bar",
+ // | "tabIndex": -1,
+ // | "method": "POST",
+ // | "onsubmit": function(e){
+ // | // stop submitting the form. Note that the IE behavior
+ // | // of returning true or false will have no effect here
+ // | // since our handler is connect()ed to the built-in
+ // | // onsubmit behavior and so we need to use
+ // | // dojo.stopEvent() to ensure that the submission
+ // | // doesn't proceed.
+ // | dojo.stopEvent(e);
+ // |
+ // | // submit the form with Ajax
+ // | dojo.xhrPost({ form: "formId" });
+ // | }
+ // | });
+ //
+ // example:
+ // Style is s special case: Only set with an object hash of styles
+ // | dojo.setAttr("someNode",{
+ // | id:"bar",
+ // | style:{
+ // | width:"200px", height:"100px", color:"#000"
+ // | }
+ // | });
+ //
+ // example:
+ // Again, only set style as an object hash of styles:
+ // | var obj = { color:"#fff", backgroundColor:"#000" };
+ // | dojo.setAttr("someNode", "style", obj);
+ // |
+ // | // though shorter to use `dojo.style()` in this case:
+ // | dojo.setStyle("someNode", obj);
+
+ node = dom.byId(node);
+ if(arguments.length == 2){ // inline'd type check
+ // the object form of setter: the 2nd argument is a dictionary
+ for(var x in name){
+ exports.set(node, x, name[x]);
+ }
+ return node; // DomNode
+ }
+ var lc = name.toLowerCase(),
+ propName = prop.names[lc] || name,
+ forceProp = forcePropNames[propName];
+ if(propName == "style" && typeof value != "string"){ // inline'd type check
+ // special case: setting a style
+ style.set(node, value);
+ return node; // DomNode
+ }
+ if(forceProp || typeof value == "boolean" || lang.isFunction(value)){
+ return prop.set(node, name, value);
+ }
+ // node's attribute
+ node.setAttribute(attrNames[lc] || name, value);
+ return node; // DomNode
+ };
+
+ exports.remove = function removeAttr(/*DOMNode|String*/ node, /*String*/ name){
+ // summary:
+ // Removes an attribute from an HTML element.
+ // node: DOMNode|String
+ // id or reference to the element to remove the attribute from
+ // name: String
+ // the name of the attribute to remove
+
+ dom.byId(node).removeAttribute(attrNames[name.toLowerCase()] || name);
+ };
+
+ exports.getNodeProp = function getNodeProp(/*DomNode|String*/ node, /*String*/ name){
+ // summary:
+ // Returns an effective value of a property or an attribute.
+ // node: DOMNode|String
+ // id or reference to the element to remove the attribute from
+ // name: String
+ // the name of the attribute
+ // returns:
+ // the value of the attribute
+
+ node = dom.byId(node);
+ var lc = name.toLowerCase(), propName = prop.names[lc] || name;
+ if((propName in node) && propName != "href"){
+ // node's property
+ return node[propName]; // Anything
+ }
+ // node's attribute
+ var attrName = attrNames[lc] || name;
+ return _hasAttr(node, attrName) ? node.getAttribute(attrName) : null; // Anything
+ };
+});
+
+},
+'dojo/dom-construct':function(){
+define(["exports", "./_base/kernel", "./sniff", "./_base/window", "./dom", "./dom-attr", "./on"],
+ function(exports, dojo, has, win, dom, attr, on){
+ // module:
+ // dojo/dom-construct
+ // summary:
+ // This module defines the core dojo DOM construction API.
+
+ // TODOC: summary not showing up in output, see https://github.com/csnover/js-doc-parse/issues/42
+
+ // support stuff for toDom()
+ var tagWrap = {
+ option: ["select"],
+ tbody: ["table"],
+ thead: ["table"],
+ tfoot: ["table"],
+ tr: ["table", "tbody"],
+ td: ["table", "tbody", "tr"],
+ th: ["table", "thead", "tr"],
+ legend: ["fieldset"],
+ caption: ["table"],
+ colgroup: ["table"],
+ col: ["table", "colgroup"],
+ li: ["ul"]
+ },
+ reTag = /<\s*([\w\:]+)/,
+ masterNode = {}, masterNum = 0,
+ masterName = "__" + dojo._scopeName + "ToDomId";
+
+ // generate start/end tag strings to use
+ // for the injection for each special tag wrap case.
+ for(var param in tagWrap){
+ if(tagWrap.hasOwnProperty(param)){
+ var tw = tagWrap[param];
+ tw.pre = param == "option" ? '
' : "<" + tw.join("><") + ">";
+ tw.post = "" + tw.reverse().join(">") + ">";
+ // the last line is destructive: it reverses the array,
+ // but we don't care at this point
+ }
+ }
+
+ function _insertBefore(/*DomNode*/ node, /*DomNode*/ ref){
+ var parent = ref.parentNode;
+ if(parent){
+ parent.insertBefore(node, ref);
+ }
+ }
+
+ function _insertAfter(/*DomNode*/ node, /*DomNode*/ ref){
+ // summary:
+ // Try to insert node after ref
+ var parent = ref.parentNode;
+ if(parent){
+ if(parent.lastChild == ref){
+ parent.appendChild(node);
+ }else{
+ parent.insertBefore(node, ref.nextSibling);
+ }
+ }
+ }
+
+ var _destroyContainer = null,
+ _destroyDoc;
+ on(window, "unload", function(){
+ _destroyContainer = null; //prevent IE leak
+ });
+
+ exports.toDom = function toDom(frag, doc){
+ // summary:
+ // instantiates an HTML fragment returning the corresponding DOM.
+ // frag: String
+ // the HTML fragment
+ // doc: DocumentNode?
+ // optional document to use when creating DOM nodes, defaults to
+ // dojo.doc if not specified.
+ // returns:
+ // Document fragment, unless it's a single node in which case it returns the node itself
+ // example:
+ // Create a table row:
+ // | var tr = dojo.toDom("First! ");
+
+ doc = doc || win.doc;
+ var masterId = doc[masterName];
+ if(!masterId){
+ doc[masterName] = masterId = ++masterNum + "";
+ masterNode[masterId] = doc.createElement("div");
+ }
+
+ // make sure the frag is a string.
+ frag += "";
+
+ // find the starting tag, and get node wrapper
+ var match = frag.match(reTag),
+ tag = match ? match[1].toLowerCase() : "",
+ master = masterNode[masterId],
+ wrap, i, fc, df;
+ if(match && tagWrap[tag]){
+ wrap = tagWrap[tag];
+ master.innerHTML = wrap.pre + frag + wrap.post;
+ for(i = wrap.length; i; --i){
+ master = master.firstChild;
+ }
+ }else{
+ master.innerHTML = frag;
+ }
+
+ // one node shortcut => return the node itself
+ if(master.childNodes.length == 1){
+ return master.removeChild(master.firstChild); // DOMNode
+ }
+
+ // return multiple nodes as a document fragment
+ df = doc.createDocumentFragment();
+ while(fc = master.firstChild){ // intentional assignment
+ df.appendChild(fc);
+ }
+ return df; // DocumentFragment
+ };
+
+ exports.place = function place(/*DOMNode|String*/ node, /*DOMNode|String*/ refNode, /*String|Number?*/ position){
+ // summary:
+ // Attempt to insert node into the DOM, choosing from various positioning options.
+ // Returns the first argument resolved to a DOM node.
+ // node: DOMNode|String
+ // id or node reference, or HTML fragment starting with "<" to place relative to refNode
+ // refNode: DOMNode|String
+ // id or node reference to use as basis for placement
+ // position: String|Number?
+ // string noting the position of node relative to refNode or a
+ // number indicating the location in the childNodes collection of refNode.
+ // Accepted string values are:
+ //
+ // - before
+ // - after
+ // - replace
+ // - only
+ // - first
+ // - last
+ //
+ // "first" and "last" indicate positions as children of refNode, "replace" replaces refNode,
+ // "only" replaces all children. position defaults to "last" if not specified
+ // returns: DOMNode
+ // Returned values is the first argument resolved to a DOM node.
+ //
+ // .place() is also a method of `dojo/NodeList`, allowing `dojo.query` node lookups.
+ // example:
+ // Place a node by string id as the last child of another node by string id:
+ // | dojo.place("someNode", "anotherNode");
+ // example:
+ // Place a node by string id before another node by string id
+ // | dojo.place("someNode", "anotherNode", "before");
+ // example:
+ // Create a Node, and place it in the body element (last child):
+ // | dojo.place("
", dojo.body());
+ // example:
+ // Put a new LI as the first child of a list by id:
+ // | dojo.place(" ", "someUl", "first");
+
+ refNode = dom.byId(refNode);
+ if(typeof node == "string"){ // inline'd type check
+ node = /^\s*hi" });
+ //
+ // example:
+ // Place a new DIV in the BODY, with no attributes set
+ // | var n = dojo.create("div", null, dojo.body());
+ //
+ // example:
+ // Create an UL, and populate it with LI's. Place the list as the first-child of a
+ // node with id="someId":
+ // | var ul = dojo.create("ul", null, "someId", "first");
+ // | var items = ["one", "two", "three", "four"];
+ // | dojo.forEach(items, function(data){
+ // | dojo.create("li", { innerHTML: data }, ul);
+ // | });
+ //
+ // example:
+ // Create an anchor, with an href. Place in BODY:
+ // | dojo.create("a", { href:"foo.html", title:"Goto FOO!" }, dojo.body());
+ //
+ // example:
+ // Create a `dojo/NodeList()` from a new element (for syntactic sugar):
+ // | dojo.query(dojo.create('div'))
+ // | .addClass("newDiv")
+ // | .onclick(function(e){ console.log('clicked', e.target) })
+ // | .place("#someNode"); // redundant, but cleaner.
+
+ var doc = win.doc;
+ if(refNode){
+ refNode = dom.byId(refNode);
+ doc = refNode.ownerDocument;
+ }
+ if(typeof tag == "string"){ // inline'd type check
+ tag = doc.createElement(tag);
+ }
+ if(attrs){ attr.set(tag, attrs); }
+ if(refNode){ exports.place(tag, refNode, pos); }
+ return tag; // DomNode
+ };
+
+ exports.empty =
+ has("ie") ? function(node){
+ node = dom.byId(node);
+ for(var c; c = node.lastChild;){ // intentional assignment
+ exports.destroy(c);
+ }
+ } :
+ function(node){
+ dom.byId(node).innerHTML = "";
+ };
+ /*=====
+ exports.empty = function(node){
+ // summary:
+ // safely removes all children of the node.
+ // node: DOMNode|String
+ // a reference to a DOM node or an id.
+ // example:
+ // Destroy node's children byId:
+ // | dojo.empty("someId");
+ //
+ // example:
+ // Destroy all nodes' children in a list by reference:
+ // | dojo.query(".someNode").forEach(dojo.empty);
+ };
+ =====*/
+
+ exports.destroy = function destroy(/*DOMNode|String*/ node){
+ // summary:
+ // Removes a node from its parent, clobbering it and all of its
+ // children.
+ //
+ // description:
+ // Removes a node from its parent, clobbering it and all of its
+ // children. Function only works with DomNodes, and returns nothing.
+ //
+ // node: DOMNode|String
+ // A String ID or DomNode reference of the element to be destroyed
+ //
+ // example:
+ // Destroy a node byId:
+ // | dojo.destroy("someId");
+ //
+ // example:
+ // Destroy all nodes in a list by reference:
+ // | dojo.query(".someNode").forEach(dojo.destroy);
+
+ node = dom.byId(node);
+ try{
+ var doc = node.ownerDocument;
+ // cannot use _destroyContainer.ownerDocument since this can throw an exception on IE
+ if(!_destroyContainer || _destroyDoc != doc){
+ _destroyContainer = doc.createElement("div");
+ _destroyDoc = doc;
+ }
+ _destroyContainer.appendChild(node.parentNode ? node.parentNode.removeChild(node) : node);
+ // NOTE: see http://trac.dojotoolkit.org/ticket/2931. This may be a bug and not a feature
+ _destroyContainer.innerHTML = "";
+ }catch(e){
+ /* squelch */
+ }
+ };
+});
+
+},
+'dojo/request/xhr':function(){
+define("dojo/request/xhr", [
+ '../errors/RequestError',
+ './watch',
+ './handlers',
+ './util',
+ '../has'/*=====,
+ '../request',
+ '../_base/declare' =====*/
+], function(RequestError, watch, handlers, util, has/*=====, request, declare =====*/){
+ has.add('native-xhr', function(){
+ // if true, the environment has a native XHR implementation
+ return typeof XMLHttpRequest !== 'undefined';
+ });
+ has.add('dojo-force-activex-xhr', function(){
+ return has('activex') && !document.addEventListener && window.location.protocol === 'file:';
+ });
+
+ has.add('native-xhr2', function(){
+ if(!has('native-xhr')){ return; }
+ var x = new XMLHttpRequest();
+ return typeof x['addEventListener'] !== 'undefined' &&
+ (typeof opera === 'undefined' || typeof x['upload'] !== 'undefined');
+ });
+
+ has.add('native-formdata', function(){
+ // if true, the environment has a native FormData implementation
+ return typeof FormData === 'function';
+ });
+
+ function handleResponse(response, error){
+ var _xhr = response.xhr;
+ response.status = response.xhr.status;
+ response.text = _xhr.responseText;
+
+ if(response.options.handleAs === 'xml'){
+ response.data = _xhr.responseXML;
+ }
+
+ if(!error){
+ try{
+ handlers(response);
+ }catch(e){
+ error = e;
+ }
+ }
+
+ if(error){
+ this.reject(error);
+ }else if(util.checkStatus(_xhr.status)){
+ this.resolve(response);
+ }else{
+ error = new RequestError('Unable to load ' + response.url + ' status: ' + _xhr.status, response);
+
+ this.reject(error);
+ }
+ }
+
+ var isValid, isReady, addListeners, cancel;
+ if(has('native-xhr2')){
+ // Any platform with XHR2 will only use the watch mechanism for timeout.
+
+ isValid = function(response){
+ // summary:
+ // Check to see if the request should be taken out of the watch queue
+ return !this.isFulfilled();
+ };
+ cancel = function(dfd, response){
+ // summary:
+ // Canceler for deferred
+ response.xhr.abort();
+ };
+ addListeners = function(_xhr, dfd, response){
+ // summary:
+ // Adds event listeners to the XMLHttpRequest object
+ function onLoad(evt){
+ dfd.handleResponse(response);
+ }
+ function onError(evt){
+ var _xhr = evt.target;
+ var error = new RequestError('Unable to load ' + response.url + ' status: ' + _xhr.status, response);
+ dfd.handleResponse(response, error);
+ }
+
+ function onProgress(evt){
+ if(evt.lengthComputable){
+ response.loaded = evt.loaded;
+ response.total = evt.total;
+ dfd.progress(response);
+ }
+ }
+
+ _xhr.addEventListener('load', onLoad, false);
+ _xhr.addEventListener('error', onError, false);
+ _xhr.addEventListener('progress', onProgress, false);
+
+ return function(){
+ _xhr.removeEventListener('load', onLoad, false);
+ _xhr.removeEventListener('error', onError, false);
+ _xhr.removeEventListener('progress', onProgress, false);
+ };
+ };
+ }else{
+ isValid = function(response){
+ return response.xhr.readyState; //boolean
+ };
+ isReady = function(response){
+ return 4 === response.xhr.readyState; //boolean
+ };
+ cancel = function(dfd, response){
+ // summary:
+ // canceller function for util.deferred call.
+ var xhr = response.xhr;
+ var _at = typeof xhr.abort;
+ if(_at === 'function' || _at === 'object' || _at === 'unknown'){
+ xhr.abort();
+ }
+ };
+ }
+
+ var undefined,
+ defaultOptions = {
+ data: null,
+ query: null,
+ sync: false,
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded'
+ }
+ };
+ function xhr(url, options, returnDeferred){
+ var response = util.parseArgs(
+ url,
+ util.deepCreate(defaultOptions, options),
+ has('native-formdata') && options && options.data && options.data instanceof FormData
+ );
+ url = response.url;
+ options = response.options;
+
+ var remover,
+ last = function(){
+ remover && remover();
+ };
+
+ //Make the Deferred object for this xhr request.
+ var dfd = util.deferred(
+ response,
+ cancel,
+ isValid,
+ isReady,
+ handleResponse,
+ last
+ );
+ var _xhr = response.xhr = xhr._create();
+
+ if(!_xhr){
+ // If XHR factory somehow returns nothings,
+ // cancel the deferred.
+ dfd.cancel(new RequestError('XHR was not created'));
+ return returnDeferred ? dfd : dfd.promise;
+ }
+
+ response.getHeader = function(headerName){
+ return this.xhr.getResponseHeader(headerName);
+ };
+
+ if(addListeners){
+ remover = addListeners(_xhr, dfd, response);
+ }
+
+ var data = options.data,
+ async = !options.sync,
+ method = options.method;
+
+ try{
+ // IE6 won't let you call apply() on the native function.
+ _xhr.open(method, url, async, options.user || undefined, options.password || undefined);
+
+ if(options.withCredentials){
+ _xhr.withCredentials = options.withCredentials;
+ }
+
+ var headers = options.headers,
+ contentType;
+ if(headers){
+ for(var hdr in headers){
+ if(hdr.toLowerCase() === 'content-type'){
+ contentType = headers[hdr];
+ }else if(headers[hdr]){
+ //Only add header if it has a value. This allows for instance, skipping
+ //insertion of X-Requested-With by specifying empty value.
+ _xhr.setRequestHeader(hdr, headers[hdr]);
+ }
+ }
+ }
+
+ if(contentType && contentType !== false){
+ _xhr.setRequestHeader('Content-Type', contentType);
+ }
+ if(!headers || !('X-Requested-With' in headers)){
+ _xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
+ }
+
+ if(util.notify){
+ util.notify.emit('send', response, dfd.promise.cancel);
+ }
+ _xhr.send(data);
+ }catch(e){
+ dfd.reject(e);
+ }
+
+ watch(dfd);
+ _xhr = null;
+
+ return returnDeferred ? dfd : dfd.promise;
+ }
+
+ /*=====
+ xhr = function(url, options){
+ // summary:
+ // Sends a request using XMLHttpRequest with the given URL and options.
+ // url: String
+ // URL to request
+ // options: dojo/request/xhr.__Options?
+ // Options for the request.
+ // returns: dojo/request.__Promise
+ };
+ xhr.__BaseOptions = declare(request.__BaseOptions, {
+ // sync: Boolean?
+ // Whether to make a synchronous request or not. Default
+ // is `false` (asynchronous).
+ // data: String|Object|FormData?
+ // Data to transfer. This is ignored for GET and DELETE
+ // requests.
+ // headers: Object?
+ // Headers to use for the request.
+ // user: String?
+ // Username to use during the request.
+ // password: String?
+ // Password to use during the request.
+ // withCredentials: Boolean?
+ // For cross-site requests, whether to send credentials
+ // or not.
+ });
+ xhr.__MethodOptions = declare(null, {
+ // method: String?
+ // The HTTP method to use to make the request. Must be
+ // uppercase. Default is `"GET"`.
+ });
+ xhr.__Options = declare([xhr.__BaseOptions, xhr.__MethodOptions]);
+
+ xhr.get = function(url, options){
+ // summary:
+ // Send an HTTP GET request using XMLHttpRequest with the given URL and options.
+ // url: String
+ // URL to request
+ // options: dojo/request/xhr.__BaseOptions?
+ // Options for the request.
+ // returns: dojo/request.__Promise
+ };
+ xhr.post = function(url, options){
+ // summary:
+ // Send an HTTP POST request using XMLHttpRequest with the given URL and options.
+ // url: String
+ // URL to request
+ // options: dojo/request/xhr.__BaseOptions?
+ // Options for the request.
+ // returns: dojo/request.__Promise
+ };
+ xhr.put = function(url, options){
+ // summary:
+ // Send an HTTP PUT request using XMLHttpRequest with the given URL and options.
+ // url: String
+ // URL to request
+ // options: dojo/request/xhr.__BaseOptions?
+ // Options for the request.
+ // returns: dojo/request.__Promise
+ };
+ xhr.del = function(url, options){
+ // summary:
+ // Send an HTTP DELETE request using XMLHttpRequest with the given URL and options.
+ // url: String
+ // URL to request
+ // options: dojo/request/xhr.__BaseOptions?
+ // Options for the request.
+ // returns: dojo/request.__Promise
+ };
+ =====*/
+ xhr._create = function(){
+ // summary:
+ // does the work of portably generating a new XMLHTTPRequest object.
+ throw new Error('XMLHTTP not available');
+ };
+ if(has('native-xhr') && !has('dojo-force-activex-xhr')){
+ xhr._create = function(){
+ return new XMLHttpRequest();
+ };
+ }else if(has('activex')){
+ try{
+ new ActiveXObject('Msxml2.XMLHTTP');
+ xhr._create = function(){
+ return new ActiveXObject('Msxml2.XMLHTTP');
+ };
+ }catch(e){
+ try{
+ new ActiveXObject('Microsoft.XMLHTTP');
+ xhr._create = function(){
+ return new ActiveXObject('Microsoft.XMLHTTP');
+ };
+ }catch(e){}
+ }
+ }
+
+ util.addCommonMethods(xhr);
+
+ return xhr;
+});
+
+},
+'dojo/text':function(){
+define(["./_base/kernel", "require", "./has", "./_base/xhr"], function(dojo, require, has, xhr){
+ // module:
+ // dojo/text
+
+ var getText;
+ if( 1 ){
+ getText= function(url, sync, load){
+ xhr("GET", {url: url, sync:!!sync, load: load, headers: dojo.config.textPluginHeaders || {}});
+ };
+ }else{
+ // TODOC: only works for dojo AMD loader
+ if(require.getText){
+ getText= require.getText;
+ }else{
+ console.error("dojo/text plugin failed to load because loader does not support getText");
+ }
+ }
+
+ var
+ theCache = {},
+
+ strip= function(text){
+ //Strips declarations so that external SVG and XML
+ //documents can be added to a document without worry. Also, if the string
+ //is an HTML document, only the part inside the body tag is returned.
+ if(text){
+ text= text.replace(/^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, "");
+ var matches= text.match(/]*>\s*([\s\S]+)\s*<\/body>/im);
+ if(matches){
+ text= matches[1];
+ }
+ }else{
+ text = "";
+ }
+ return text;
+ },
+
+ notFound = {},
+
+ pending = {};
+
+ dojo.cache = function(/*String||Object*/module, /*String*/url, /*String||Object?*/value){
+ // summary:
+ // A getter and setter for storing the string content associated with the
+ // module and url arguments.
+ // description:
+ // If module is a string that contains slashes, then it is interpretted as a fully
+ // resolved path (typically a result returned by require.toUrl), and url should not be
+ // provided. This is the preferred signature. If module is a string that does not
+ // contain slashes, then url must also be provided and module and url are used to
+ // call `dojo.moduleUrl()` to generate a module URL. This signature is deprecated.
+ // If value is specified, the cache value for the moduleUrl will be set to
+ // that value. Otherwise, dojo.cache will fetch the moduleUrl and store it
+ // in its internal cache and return that cached value for the URL. To clear
+ // a cache value pass null for value. Since XMLHttpRequest (XHR) is used to fetch the
+ // the URL contents, only modules on the same domain of the page can use this capability.
+ // The build system can inline the cache values though, to allow for xdomain hosting.
+ // module: String||Object
+ // If a String with slashes, a fully resolved path; if a String without slashes, the
+ // module name to use for the base part of the URL, similar to module argument
+ // to `dojo.moduleUrl`. If an Object, something that has a .toString() method that
+ // generates a valid path for the cache item. For example, a dojo._Url object.
+ // url: String
+ // The rest of the path to append to the path derived from the module argument. If
+ // module is an object, then this second argument should be the "value" argument instead.
+ // value: String||Object?
+ // If a String, the value to use in the cache for the module/url combination.
+ // If an Object, it can have two properties: value and sanitize. The value property
+ // should be the value to use in the cache, and sanitize can be set to true or false,
+ // to indicate if XML declarations should be removed from the value and if the HTML
+ // inside a body tag in the value should be extracted as the real value. The value argument
+ // or the value property on the value argument are usually only used by the build system
+ // as it inlines cache content.
+ // example:
+ // To ask dojo.cache to fetch content and store it in the cache (the dojo["cache"] style
+ // of call is used to avoid an issue with the build system erroneously trying to intern
+ // this example. To get the build system to intern your dojo.cache calls, use the
+ // "dojo.cache" style of call):
+ // | //If template.html contains "Hello " that will be
+ // | //the value for the text variable.
+ // | var text = dojo["cache"]("my.module", "template.html");
+ // example:
+ // To ask dojo.cache to fetch content and store it in the cache, and sanitize the input
+ // (the dojo["cache"] style of call is used to avoid an issue with the build system
+ // erroneously trying to intern this example. To get the build system to intern your
+ // dojo.cache calls, use the "dojo.cache" style of call):
+ // | //If template.html contains "Hello ", the
+ // | //text variable will contain just "Hello ".
+ // | var text = dojo["cache"]("my.module", "template.html", {sanitize: true});
+ // example:
+ // Same example as previous, but demonstrates how an object can be passed in as
+ // the first argument, then the value argument can then be the second argument.
+ // | //If template.html contains "Hello ", the
+ // | //text variable will contain just "Hello ".
+ // | var text = dojo["cache"](new dojo._Url("my/module/template.html"), {sanitize: true});
+
+ // * (string string [value]) => (module, url, value)
+ // * (object [value]) => (module, value), url defaults to ""
+ //
+ // * if module is an object, then it must be convertable to a string
+ // * (module, url) module + (url ? ("/" + url) : "") must be a legal argument to require.toUrl
+ // * value may be a string or an object; if an object then may have the properties "value" and/or "sanitize"
+ var key;
+ if(typeof module=="string"){
+ if(/\//.test(module)){
+ // module is a version 1.7+ resolved path
+ key = module;
+ value = url;
+ }else{
+ // module is a version 1.6- argument to dojo.moduleUrl
+ key = require.toUrl(module.replace(/\./g, "/") + (url ? ("/" + url) : ""));
+ }
+ }else{
+ key = module + "";
+ value = url;
+ }
+ var
+ val = (value != undefined && typeof value != "string") ? value.value : value,
+ sanitize = value && value.sanitize;
+
+ if(typeof val == "string"){
+ //We have a string, set cache value
+ theCache[key] = val;
+ return sanitize ? strip(val) : val;
+ }else if(val === null){
+ //Remove cached value
+ delete theCache[key];
+ return null;
+ }else{
+ //Allow cache values to be empty strings. If key property does
+ //not exist, fetch it.
+ if(!(key in theCache)){
+ getText(key, true, function(text){
+ theCache[key]= text;
+ });
+ }
+ return sanitize ? strip(theCache[key]) : theCache[key];
+ }
+ };
+
+ return {
+ // summary:
+ // This module implements the dojo/text! plugin and the dojo.cache API.
+ // description:
+ // We choose to include our own plugin to leverage functionality already contained in dojo
+ // and thereby reduce the size of the plugin compared to various foreign loader implementations.
+ // Also, this allows foreign AMD loaders to be used without their plugins.
+ //
+ // CAUTION: this module is designed to optionally function synchronously to support the dojo v1.x synchronous
+ // loader. This feature is outside the scope of the CommonJS plugins specification.
+
+ // the dojo/text caches it's own resources because of dojo.cache
+ dynamic: true,
+
+ normalize: function(id, toAbsMid){
+ // id is something like (path may be relative):
+ //
+ // "path/to/text.html"
+ // "path/to/text.html!strip"
+ var parts= id.split("!"),
+ url= parts[0];
+ return (/^\./.test(url) ? toAbsMid(url) : url) + (parts[1] ? "!" + parts[1] : "");
+ },
+
+ load: function(id, require, load){
+ // id: String
+ // Path to the resource.
+ // require: Function
+ // Object that include the function toUrl with given id returns a valid URL from which to load the text.
+ // load: Function
+ // Callback function which will be called, when the loading finished.
+
+ // id is something like (path is always absolute):
+ //
+ // "path/to/text.html"
+ // "path/to/text.html!strip"
+ var
+ parts= id.split("!"),
+ stripFlag= parts.length>1,
+ absMid= parts[0],
+ url = require.toUrl(parts[0]),
+ requireCacheUrl = "url:" + url,
+ text = notFound,
+ finish = function(text){
+ load(stripFlag ? strip(text) : text);
+ };
+ if(absMid in theCache){
+ text = theCache[absMid];
+ }else if(requireCacheUrl in require.cache){
+ text = require.cache[requireCacheUrl];
+ }else if(url in theCache){
+ text = theCache[url];
+ }
+ if(text===notFound){
+ if(pending[url]){
+ pending[url].push(finish);
+ }else{
+ var pendingList = pending[url] = [finish];
+ getText(url, !require.async, function(text){
+ theCache[absMid]= theCache[url]= text;
+ for(var i = 0; i 2){
+ return lang._hitchArgs.apply(dojo, arguments); // Function
+ }
+ if(!method){
+ method = scope;
+ scope = null;
+ }
+ if(lang.isString(method)){
+ scope = scope || dojo.global;
+ if(!scope[method]){ throw(['lang.hitch: scope["', method, '"] is null (scope="', scope, '")'].join('')); }
+ return function(){ return scope[method].apply(scope, arguments || []); }; // Function
+ }
+ return !scope ? method : function(){ return method.apply(scope, arguments || []); }; // Function
+ },
+
+ delegate: (function(){
+ // boodman/crockford delegation w/ cornford optimization
+ function TMP(){}
+ return function(obj, props){
+ TMP.prototype = obj;
+ var tmp = new TMP();
+ TMP.prototype = null;
+ if(props){
+ lang._mixin(tmp, props);
+ }
+ return tmp; // Object
+ };
+ })(),
+ /*=====
+ delegate: function(obj, props){
+ // summary:
+ // Returns a new object which "looks" to obj for properties which it
+ // does not have a value for. Optionally takes a bag of properties to
+ // seed the returned object with initially.
+ // description:
+ // This is a small implementation of the Boodman/Crockford delegation
+ // pattern in JavaScript. An intermediate object constructor mediates
+ // the prototype chain for the returned object, using it to delegate
+ // down to obj for property lookup when object-local lookup fails.
+ // This can be thought of similarly to ES4's "wrap", save that it does
+ // not act on types but rather on pure objects.
+ // obj: Object
+ // The object to delegate to for properties not found directly on the
+ // return object or in props.
+ // props: Object...
+ // an object containing properties to assign to the returned object
+ // returns:
+ // an Object of anonymous type
+ // example:
+ // | var foo = { bar: "baz" };
+ // | var thinger = lang.delegate(foo, { thud: "xyzzy"});
+ // | thinger.bar == "baz"; // delegated to foo
+ // | foo.thud == undefined; // by definition
+ // | thinger.thud == "xyzzy"; // mixed in from props
+ // | foo.bar = "thonk";
+ // | thinger.bar == "thonk"; // still delegated to foo's bar
+ },
+ =====*/
+
+ _toArray: has("ie") ?
+ (function(){
+ function slow(obj, offset, startWith){
+ var arr = startWith||[];
+ for(var x = offset || 0; x < obj.length; x++){
+ arr.push(obj[x]);
+ }
+ return arr;
+ }
+ return function(obj){
+ return ((obj.item) ? slow : efficient).apply(this, arguments);
+ };
+ })() : efficient,
+ /*=====
+ _toArray: function(obj, offset, startWith){
+ // summary:
+ // Converts an array-like object (i.e. arguments, DOMCollection) to an
+ // array. Returns a new Array with the elements of obj.
+ // obj: Object
+ // the object to "arrayify". We expect the object to have, at a
+ // minimum, a length property which corresponds to integer-indexed
+ // properties.
+ // offset: Number?
+ // the location in obj to start iterating from. Defaults to 0.
+ // Optional.
+ // startWith: Array?
+ // An array to pack with the properties of obj. If provided,
+ // properties in obj are appended at the end of startWith and
+ // startWith is the returned array.
+ },
+ =====*/
+
+ partial: function(/*Function|String*/ method /*, ...*/){
+ // summary:
+ // similar to hitch() except that the scope object is left to be
+ // whatever the execution context eventually becomes.
+ // description:
+ // Calling lang.partial is the functional equivalent of calling:
+ // | lang.hitch(null, funcName, ...);
+ // method:
+ // The function to "wrap"
+ var arr = [ null ];
+ return lang.hitch.apply(dojo, arr.concat(lang._toArray(arguments))); // Function
+ },
+
+ clone: function(/*anything*/ src){
+ // summary:
+ // Clones objects (including DOM nodes) and all children.
+ // Warning: do not clone cyclic structures.
+ // src:
+ // The object to clone
+ if(!src || typeof src != "object" || lang.isFunction(src)){
+ // null, undefined, any non-object, or function
+ return src; // anything
+ }
+ if(src.nodeType && "cloneNode" in src){
+ // DOM Node
+ return src.cloneNode(true); // Node
+ }
+ if(src instanceof Date){
+ // Date
+ return new Date(src.getTime()); // Date
+ }
+ if(src instanceof RegExp){
+ // RegExp
+ return new RegExp(src); // RegExp
+ }
+ var r, i, l;
+ if(lang.isArray(src)){
+ // array
+ r = [];
+ for(i = 0, l = src.length; i < l; ++i){
+ if(i in src){
+ r.push(lang.clone(src[i]));
+ }
+ }
+ // we don't clone functions for performance reasons
+ // }else if(d.isFunction(src)){
+ // // function
+ // r = function(){ return src.apply(this, arguments); };
+ }else{
+ // generic objects
+ r = src.constructor ? new src.constructor() : {};
+ }
+ return lang._mixin(r, src, lang.clone);
+ },
+
+
+ trim: String.prototype.trim ?
+ function(str){ return str.trim(); } :
+ function(str){ return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); },
+ /*=====
+ trim: function(str){
+ // summary:
+ // Trims whitespace from both sides of the string
+ // str: String
+ // String to be trimmed
+ // returns: String
+ // Returns the trimmed string
+ // description:
+ // This version of trim() was selected for inclusion into the base due
+ // to its compact size and relatively good performance
+ // (see [Steven Levithan's blog](http://blog.stevenlevithan.com/archives/faster-trim-javascript)
+ // Uses String.prototype.trim instead, if available.
+ // The fastest but longest version of this function is located at
+ // lang.string.trim()
+ },
+ =====*/
+
+ replace: function(tmpl, map, pattern){
+ // summary:
+ // Performs parameterized substitutions on a string. Throws an
+ // exception if any parameter is unmatched.
+ // tmpl: String
+ // String to be used as a template.
+ // map: Object|Function
+ // If an object, it is used as a dictionary to look up substitutions.
+ // If a function, it is called for every substitution with following parameters:
+ // a whole match, a name, an offset, and the whole template
+ // string (see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace
+ // for more details).
+ // pattern: RegEx?
+ // Optional regular expression objects that overrides the default pattern.
+ // Must be global and match one item. The default is: /\{([^\}]+)\}/g,
+ // which matches patterns like that: "{xxx}", where "xxx" is any sequence
+ // of characters, which doesn't include "}".
+ // returns: String
+ // Returns the substituted string.
+ // example:
+ // | // uses a dictionary for substitutions:
+ // | lang.replace("Hello, {name.first} {name.last} AKA {nick}!",
+ // | {
+ // | nick: "Bob",
+ // | name: {
+ // | first: "Robert",
+ // | middle: "X",
+ // | last: "Cringely"
+ // | }
+ // | });
+ // | // returns: Hello, Robert Cringely AKA Bob!
+ // example:
+ // | // uses an array for substitutions:
+ // | lang.replace("Hello, {0} {2}!",
+ // | ["Robert", "X", "Cringely"]);
+ // | // returns: Hello, Robert Cringely!
+ // example:
+ // | // uses a function for substitutions:
+ // | function sum(a){
+ // | var t = 0;
+ // | arrayforEach(a, function(x){ t += x; });
+ // | return t;
+ // | }
+ // | lang.replace(
+ // | "{count} payments averaging {avg} USD per payment.",
+ // | lang.hitch(
+ // | { payments: [11, 16, 12] },
+ // | function(_, key){
+ // | switch(key){
+ // | case "count": return this.payments.length;
+ // | case "min": return Math.min.apply(Math, this.payments);
+ // | case "max": return Math.max.apply(Math, this.payments);
+ // | case "sum": return sum(this.payments);
+ // | case "avg": return sum(this.payments) / this.payments.length;
+ // | }
+ // | }
+ // | )
+ // | );
+ // | // prints: 3 payments averaging 13 USD per payment.
+ // example:
+ // | // uses an alternative PHP-like pattern for substitutions:
+ // | lang.replace("Hello, ${0} ${2}!",
+ // | ["Robert", "X", "Cringely"], /\$\{([^\}]+)\}/g);
+ // | // returns: Hello, Robert Cringely!
+
+ return tmpl.replace(pattern || _pattern, lang.isFunction(map) ?
+ map : function(_, k){ return lang.getObject(k, false, map); });
+ }
+ };
+
+ 1 && lang.mixin(dojo, lang);
+
+ return lang;
+});
+
+
+},
+'dojo/request/util':function(){
+define("dojo/request/util", [
+ 'exports',
+ '../errors/RequestError',
+ '../errors/CancelError',
+ '../Deferred',
+ '../io-query',
+ '../_base/array',
+ '../_base/lang'
+], function(exports, RequestError, CancelError, Deferred, ioQuery, array, lang){
+ exports.deepCopy = function deepCopy(target, source){
+ for(var name in source){
+ var tval = target[name],
+ sval = source[name];
+ if(tval !== sval){
+ if(tval && typeof tval === 'object' && sval && typeof sval === 'object'){
+ exports.deepCopy(tval, sval);
+ }else{
+ target[name] = sval;
+ }
+ }
+ }
+ return target;
+ };
+
+ exports.deepCreate = function deepCreate(source, properties){
+ properties = properties || {};
+ var target = lang.delegate(source),
+ name, value;
+
+ for(name in source){
+ value = source[name];
+
+ if(value && typeof value === 'object'){
+ target[name] = exports.deepCreate(value, properties[name]);
+ }
+ }
+ return exports.deepCopy(target, properties);
+ };
+
+ var freeze = Object.freeze || function(obj){ return obj; };
+ function okHandler(response){
+ return freeze(response);
+ }
+
+ exports.deferred = function deferred(response, cancel, isValid, isReady, handleResponse, last){
+ var def = new Deferred(function(reason){
+ cancel && cancel(def, response);
+
+ if(!reason || !(reason instanceof RequestError) && !(reason instanceof CancelError)){
+ return new CancelError('Request canceled', response);
+ }
+ return reason;
+ });
+
+ def.response = response;
+ def.isValid = isValid;
+ def.isReady = isReady;
+ def.handleResponse = handleResponse;
+
+ function errHandler(error){
+ error.response = response;
+ throw error;
+ }
+ var responsePromise = def.then(okHandler).otherwise(errHandler);
+
+ if(exports.notify){
+ responsePromise.then(
+ lang.hitch(exports.notify, 'emit', 'load'),
+ lang.hitch(exports.notify, 'emit', 'error')
+ );
+ }
+
+ var dataPromise = responsePromise.then(function(response){
+ return response.data || response.text;
+ });
+
+ var promise = freeze(lang.delegate(dataPromise, {
+ response: responsePromise
+ }));
+
+
+ if(last){
+ def.then(function(response){
+ last.call(def, response);
+ }, function(error){
+ last.call(def, response, error);
+ });
+ }
+
+ def.promise = promise;
+ def.then = promise.then;
+
+ return def;
+ };
+
+ exports.addCommonMethods = function addCommonMethods(provider, methods){
+ array.forEach(methods||['GET', 'POST', 'PUT', 'DELETE'], function(method){
+ provider[(method === 'DELETE' ? 'DEL' : method).toLowerCase()] = function(url, options){
+ options = lang.delegate(options||{});
+ options.method = method;
+ return provider(url, options);
+ };
+ });
+ };
+
+ exports.parseArgs = function parseArgs(url, options, skipData){
+ var data = options.data,
+ query = options.query;
+
+ if(data && !skipData){
+ if(typeof data === 'object'){
+ options.data = ioQuery.objectToQuery(data);
+ }
+ }
+
+ if(query){
+ if(typeof query === 'object'){
+ query = ioQuery.objectToQuery(query);
+ }
+ if(options.preventCache){
+ query += (query ? '&' : '') + 'request.preventCache=' + (+(new Date));
+ }
+ }else if(options.preventCache){
+ query = 'request.preventCache=' + (+(new Date));
+ }
+
+ if(url && query){
+ url += (~url.indexOf('?') ? '&' : '?') + query;
+ }
+
+ return {
+ url: url,
+ options: options,
+ getHeader: function(headerName){ return null; }
+ };
+ };
+
+ exports.checkStatus = function(stat){
+ stat = stat || 0;
+ return (stat >= 200 && stat < 300) || // allow any 2XX response code
+ stat === 304 || // or, get it out of the cache
+ stat === 1223 || // or, Internet Explorer mangled the status code
+ !stat; // or, we're Titanium/browser chrome/chrome extension requesting a local file
+ };
+});
+
+},
+'dojo/Evented':function(){
+define("dojo/Evented", ["./aspect", "./on"], function(aspect, on){
+ // module:
+ // dojo/Evented
+
+ "use strict";
+ var after = aspect.after;
+ function Evented(){
+ // summary:
+ // A class that can be used as a mixin or base class,
+ // to add on() and emit() methods to a class
+ // for listening for events and emitting events:
+ //
+ // | define(["dojo/Evented"], function(Evented){
+ // | var EventedWidget = dojo.declare([Evented, dijit._Widget], {...});
+ // | widget = new EventedWidget();
+ // | widget.on("open", function(event){
+ // | ... do something with event
+ // | });
+ // |
+ // | widget.emit("open", {name:"some event", ...});
+ }
+ Evented.prototype = {
+ on: function(type, listener){
+ return on.parse(this, type, listener, function(target, type){
+ return after(target, 'on' + type, listener, true);
+ });
+ },
+ emit: function(type, event){
+ var args = [this];
+ args.push.apply(args, arguments);
+ return on.emit.apply(on, args);
+ }
+ };
+ return Evented;
+});
+
+},
+'dojo/mouse':function(){
+define("dojo/mouse", ["./_base/kernel", "./on", "./has", "./dom", "./_base/window"], function(dojo, on, has, dom, win){
+
+ // module:
+ // dojo/mouse
+
+ has.add("dom-quirks", win.doc && win.doc.compatMode == "BackCompat");
+ has.add("events-mouseenter", win.doc && "onmouseenter" in win.doc.createElement("div"));
+ has.add("events-mousewheel", win.doc && 'onmousewheel' in win.doc);
+
+ var mouseButtons;
+ if((has("dom-quirks") && has("ie")) || !has("dom-addeventlistener")){
+ mouseButtons = {
+ LEFT: 1,
+ MIDDLE: 4,
+ RIGHT: 2,
+ // helper functions
+ isButton: function(e, button){ return e.button & button; },
+ isLeft: function(e){ return e.button & 1; },
+ isMiddle: function(e){ return e.button & 4; },
+ isRight: function(e){ return e.button & 2; }
+ };
+ }else{
+ mouseButtons = {
+ LEFT: 0,
+ MIDDLE: 1,
+ RIGHT: 2,
+ // helper functions
+ isButton: function(e, button){ return e.button == button; },
+ isLeft: function(e){ return e.button == 0; },
+ isMiddle: function(e){ return e.button == 1; },
+ isRight: function(e){ return e.button == 2; }
+ };
+ }
+ dojo.mouseButtons = mouseButtons;
+
+/*=====
+ dojo.mouseButtons = {
+ // LEFT: Number
+ // Numeric value of the left mouse button for the platform.
+ LEFT: 0,
+ // MIDDLE: Number
+ // Numeric value of the middle mouse button for the platform.
+ MIDDLE: 1,
+ // RIGHT: Number
+ // Numeric value of the right mouse button for the platform.
+ RIGHT: 2,
+
+ isButton: function(e, button){
+ // summary:
+ // Checks an event object for a pressed button
+ // e: Event
+ // Event object to examine
+ // button: Number
+ // The button value (example: dojo.mouseButton.LEFT)
+ return e.button == button; // Boolean
+ },
+ isLeft: function(e){
+ // summary:
+ // Checks an event object for the pressed left button
+ // e: Event
+ // Event object to examine
+ return e.button == 0; // Boolean
+ },
+ isMiddle: function(e){
+ // summary:
+ // Checks an event object for the pressed middle button
+ // e: Event
+ // Event object to examine
+ return e.button == 1; // Boolean
+ },
+ isRight: function(e){
+ // summary:
+ // Checks an event object for the pressed right button
+ // e: Event
+ // Event object to examine
+ return e.button == 2; // Boolean
+ }
+ };
+=====*/
+
+ function eventHandler(type, selectHandler){
+ // emulation of mouseenter/leave with mouseover/out using descendant checking
+ var handler = function(node, listener){
+ return on(node, type, function(evt){
+ if(selectHandler){
+ return selectHandler(evt, listener);
+ }
+ if(!dom.isDescendant(evt.relatedTarget, node)){
+ return listener.call(this, evt);
+ }
+ });
+ };
+ handler.bubble = function(select){
+ return eventHandler(type, function(evt, listener){
+ // using a selector, use the select function to determine if the mouse moved inside the selector and was previously outside the selector
+ var target = select(evt.target);
+ var relatedTarget = evt.relatedTarget;
+ if(target && (target != (relatedTarget && relatedTarget.nodeType == 1 && select(relatedTarget)))){
+ return listener.call(target, evt);
+ }
+ });
+ };
+ return handler;
+ }
+ var wheel;
+ if(has("events-mousewheel")){
+ wheel = 'mousewheel';
+ }else{ //firefox
+ wheel = function(node, listener){
+ return on(node, 'DOMMouseScroll', function(evt){
+ evt.wheelDelta = -evt.detail;
+ listener.call(this, evt);
+ });
+ };
+ }
+ return {
+ // summary:
+ // This module provide mouse event handling utility functions and exports
+ // mouseenter and mouseleave event emulation.
+ // example:
+ // To use these events, you register a mouseenter like this:
+ // | define(["dojo/on", dojo/mouse"], function(on, mouse){
+ // | on(targetNode, mouse.enter, function(event){
+ // | dojo.addClass(targetNode, "highlighted");
+ // | });
+ // | on(targetNode, mouse.leave, function(event){
+ // | dojo.removeClass(targetNode, "highlighted");
+ // | });
+
+ _eventHandler: eventHandler, // for dojo/touch
+
+ // enter: Synthetic Event
+ // This is an extension event for the mouseenter that IE provides, emulating the
+ // behavior on other browsers.
+ enter: eventHandler("mouseover"),
+
+ // leave: Synthetic Event
+ // This is an extension event for the mouseleave that IE provides, emulating the
+ // behavior on other browsers.
+ leave: eventHandler("mouseout"),
+
+ // wheel: Normalized Mouse Wheel Event
+ // This is an extension event for the mousewheel that non-Mozilla browsers provide,
+ // emulating the behavior on Mozilla based browsers.
+ wheel: wheel,
+
+ isLeft: mouseButtons.isLeft,
+ /*=====
+ isLeft: function(){
+ // summary:
+ // Test an event object (from a mousedown event) to see if the left button was pressed.
+ },
+ =====*/
+
+ isMiddle: mouseButtons.isMiddle,
+ /*=====
+ isMiddle: function(){
+ // summary:
+ // Test an event object (from a mousedown event) to see if the middle button was pressed.
+ },
+ =====*/
+
+ isRight: mouseButtons.isRight
+ /*=====
+ , isRight: function(){
+ // summary:
+ // Test an event object (from a mousedown event) to see if the right button was pressed.
+ }
+ =====*/
+ };
+});
+
+},
+'dojo/topic':function(){
+define("dojo/topic", ["./Evented"], function(Evented){
+
+ // module:
+ // dojo/topic
+
+ var hub = new Evented;
+ return {
+ // summary:
+ // Pubsub hub.
+ // example:
+ // | topic.subscribe("some/topic", function(event){
+ // | ... do something with event
+ // | });
+ // | topic.publish("some/topic", {name:"some event", ...});
+
+ publish: function(topic, event){
+ // summary:
+ // Publishes a message to a topic on the pub/sub hub. All arguments after
+ // the first will be passed to the subscribers, so any number of arguments
+ // can be provided (not just event).
+ // topic: String
+ // The name of the topic to publish to
+ // event: Object
+ // An event to distribute to the topic listeners
+ return hub.emit.apply(hub, arguments);
+ },
+
+ subscribe: function(topic, listener){
+ // summary:
+ // Subscribes to a topic on the pub/sub hub
+ // topic: String
+ // The topic to subscribe to
+ // listener: Function
+ // A function to call when a message is published to the given topic
+ return hub.on.apply(hub, arguments);
+ }
+ };
+});
+
+},
+'dojo/_base/xhr':function(){
+define("dojo/_base/xhr", [
+ "./kernel",
+ "./sniff",
+ "require",
+ "../io-query",
+ /*===== "./declare", =====*/
+ "../dom",
+ "../dom-form",
+ "./Deferred",
+ "./config",
+ "./json",
+ "./lang",
+ "./array",
+ "../on",
+ "../aspect",
+ "../request/watch",
+ "../request/xhr",
+ "../request/util"
+], function(dojo, has, require, ioq, /*===== declare, =====*/ dom, domForm, Deferred, config, json, lang, array, on, aspect, watch, _xhr, util){
+ // module:
+ // dojo/_base/xhr
+
+ /*=====
+ dojo._xhrObj = function(){
+ // summary:
+ // does the work of portably generating a new XMLHTTPRequest object.
+ };
+ =====*/
+ dojo._xhrObj = _xhr._create;
+
+ var cfg = dojo.config;
+
+ // mix in io-query and dom-form
+ dojo.objectToQuery = ioq.objectToQuery;
+ dojo.queryToObject = ioq.queryToObject;
+ dojo.fieldToObject = domForm.fieldToObject;
+ dojo.formToObject = domForm.toObject;
+ dojo.formToQuery = domForm.toQuery;
+ dojo.formToJson = domForm.toJson;
+
+ // need to block async callbacks from snatching this thread as the result
+ // of an async callback might call another sync XHR, this hangs khtml forever
+ // must checked by watchInFlight()
+
+ dojo._blockAsync = false;
+
+ // MOW: remove dojo._contentHandlers alias in 2.0
+ var handlers = dojo._contentHandlers = dojo.contentHandlers = {
+ // summary:
+ // A map of available XHR transport handle types. Name matches the
+ // `handleAs` attribute passed to XHR calls.
+ // description:
+ // A map of available XHR transport handle types. Name matches the
+ // `handleAs` attribute passed to XHR calls. Each contentHandler is
+ // called, passing the xhr object for manipulation. The return value
+ // from the contentHandler will be passed to the `load` or `handle`
+ // functions defined in the original xhr call.
+ // example:
+ // Creating a custom content-handler:
+ // | xhr.contentHandlers.makeCaps = function(xhr){
+ // | return xhr.responseText.toUpperCase();
+ // | }
+ // | // and later:
+ // | dojo.xhrGet({
+ // | url:"foo.txt",
+ // | handleAs:"makeCaps",
+ // | load: function(data){ /* data is a toUpper version of foo.txt */ }
+ // | });
+
+ "text": function(xhr){
+ // summary:
+ // A contentHandler which simply returns the plaintext response data
+ return xhr.responseText;
+ },
+ "json": function(xhr){
+ // summary:
+ // A contentHandler which returns a JavaScript object created from the response data
+ return json.fromJson(xhr.responseText || null);
+ },
+ "json-comment-filtered": function(xhr){
+ // summary:
+ // A contentHandler which expects comment-filtered JSON.
+ // description:
+ // A contentHandler which expects comment-filtered JSON.
+ // the json-comment-filtered option was implemented to prevent
+ // "JavaScript Hijacking", but it is less secure than standard JSON. Use
+ // standard JSON instead. JSON prefixing can be used to subvert hijacking.
+ //
+ // Will throw a notice suggesting to use application/json mimetype, as
+ // json-commenting can introduce security issues. To decrease the chances of hijacking,
+ // use the standard `json` contentHandler, and prefix your "JSON" with: {}&&
+ //
+ // use djConfig.useCommentedJson = true to turn off the notice
+ if(!config.useCommentedJson){
+ console.warn("Consider using the standard mimetype:application/json."
+ + " json-commenting can introduce security issues. To"
+ + " decrease the chances of hijacking, use the standard the 'json' handler and"
+ + " prefix your json with: {}&&\n"
+ + "Use djConfig.useCommentedJson=true to turn off this message.");
+ }
+
+ var value = xhr.responseText;
+ var cStartIdx = value.indexOf("\/*");
+ var cEndIdx = value.lastIndexOf("*\/");
+ if(cStartIdx == -1 || cEndIdx == -1){
+ throw new Error("JSON was not comment filtered");
+ }
+ return json.fromJson(value.substring(cStartIdx+2, cEndIdx));
+ },
+ "javascript": function(xhr){
+ // summary:
+ // A contentHandler which evaluates the response data, expecting it to be valid JavaScript
+
+ // FIXME: try Moz and IE specific eval variants?
+ return dojo.eval(xhr.responseText);
+ },
+ "xml": function(xhr){
+ // summary:
+ // A contentHandler returning an XML Document parsed from the response data
+ var result = xhr.responseXML;
+
+ if(has("ie")){
+ if((!result || !result.documentElement)){
+ //WARNING: this branch used by the xml handling in dojo.io.iframe,
+ //so be sure to test dojo.io.iframe if making changes below.
+ var ms = function(n){ return "MSXML" + n + ".DOMDocument"; };
+ var dp = ["Microsoft.XMLDOM", ms(6), ms(4), ms(3), ms(2)];
+ array.some(dp, function(p){
+ try{
+ var dom = new ActiveXObject(p);
+ dom.async = false;
+ dom.loadXML(xhr.responseText);
+ result = dom;
+ }catch(e){ return false; }
+ return true;
+ });
+ }
+ }
+ return result; // DOMDocument
+ },
+ "json-comment-optional": function(xhr){
+ // summary:
+ // A contentHandler which checks the presence of comment-filtered JSON and
+ // alternates between the `json` and `json-comment-filtered` contentHandlers.
+ if(xhr.responseText && /^[^{\[]*\/\*/.test(xhr.responseText)){
+ return handlers["json-comment-filtered"](xhr);
+ }else{
+ return handlers["json"](xhr);
+ }
+ }
+ };
+
+ /*=====
+
+ // kwargs function parameter definitions. Assigning to dojo namespace rather than making them local variables
+ // because they are used by dojo/io modules too
+
+ dojo.__IoArgs = declare(null, {
+ // url: String
+ // URL to server endpoint.
+ // content: Object?
+ // Contains properties with string values. These
+ // properties will be serialized as name1=value2 and
+ // passed in the request.
+ // timeout: Integer?
+ // Milliseconds to wait for the response. If this time
+ // passes, the then error callbacks are called.
+ // form: DOMNode?
+ // DOM node for a form. Used to extract the form values
+ // and send to the server.
+ // preventCache: Boolean?
+ // Default is false. If true, then a
+ // "dojo.preventCache" parameter is sent in the request
+ // with a value that changes with each request
+ // (timestamp). Useful only with GET-type requests.
+ // handleAs: String?
+ // Acceptable values depend on the type of IO
+ // transport (see specific IO calls for more information).
+ // rawBody: String?
+ // Sets the raw body for an HTTP request. If this is used, then the content
+ // property is ignored. This is mostly useful for HTTP methods that have
+ // a body to their requests, like PUT or POST. This property can be used instead
+ // of postData and putData for dojo/_base/xhr.rawXhrPost and dojo/_base/xhr.rawXhrPut respectively.
+ // ioPublish: Boolean?
+ // Set this explicitly to false to prevent publishing of topics related to
+ // IO operations. Otherwise, if djConfig.ioPublish is set to true, topics
+ // will be published via dojo/topic.publish() for different phases of an IO operation.
+ // See dojo/main.__IoPublish for a list of topics that are published.
+
+ load: function(response, ioArgs){
+ // summary:
+ // This function will be
+ // called on a successful HTTP response code.
+ // ioArgs: dojo/main.__IoCallbackArgs
+ // Provides additional information about the request.
+ // response: Object
+ // The response in the format as defined with handleAs.
+ },
+
+ error: function(response, ioArgs){
+ // summary:
+ // This function will
+ // be called when the request fails due to a network or server error, the url
+ // is invalid, etc. It will also be called if the load or handle callback throws an
+ // exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications
+ // to continue to run even when a logic error happens in the callback, while making
+ // it easier to troubleshoot while in debug mode.
+ // ioArgs: dojo/main.__IoCallbackArgs
+ // Provides additional information about the request.
+ // response: Object
+ // The response in the format as defined with handleAs.
+ },
+
+ handle: function(loadOrError, response, ioArgs){
+ // summary:
+ // This function will
+ // be called at the end of every request, whether or not an error occurs.
+ // loadOrError: String
+ // Provides a string that tells you whether this function
+ // was called because of success (load) or failure (error).
+ // response: Object
+ // The response in the format as defined with handleAs.
+ // ioArgs: dojo/main.__IoCallbackArgs
+ // Provides additional information about the request.
+ }
+ });
+
+ dojo.__IoCallbackArgs = declare(null, {
+ // args: Object
+ // the original object argument to the IO call.
+ // xhr: XMLHttpRequest
+ // For XMLHttpRequest calls only, the
+ // XMLHttpRequest object that was used for the
+ // request.
+ // url: String
+ // The final URL used for the call. Many times it
+ // will be different than the original args.url
+ // value.
+ // query: String
+ // For non-GET requests, the
+ // name1=value1&name2=value2 parameters sent up in
+ // the request.
+ // handleAs: String
+ // The final indicator on how the response will be
+ // handled.
+ // id: String
+ // For dojo/io/script calls only, the internal
+ // script ID used for the request.
+ // canDelete: Boolean
+ // For dojo/io/script calls only, indicates
+ // whether the script tag that represents the
+ // request can be deleted after callbacks have
+ // been called. Used internally to know when
+ // cleanup can happen on JSONP-type requests.
+ // json: Object
+ // For dojo/io/script calls only: holds the JSON
+ // response for JSONP-type requests. Used
+ // internally to hold on to the JSON responses.
+ // You should not need to access it directly --
+ // the same object should be passed to the success
+ // callbacks directly.
+ });
+
+ dojo.__IoPublish = declare(null, {
+ // summary:
+ // This is a list of IO topics that can be published
+ // if djConfig.ioPublish is set to true. IO topics can be
+ // published for any Input/Output, network operation. So,
+ // dojo.xhr, dojo.io.script and dojo.io.iframe can all
+ // trigger these topics to be published.
+ // start: String
+ // "/dojo/io/start" is sent when there are no outstanding IO
+ // requests, and a new IO request is started. No arguments
+ // are passed with this topic.
+ // send: String
+ // "/dojo/io/send" is sent whenever a new IO request is started.
+ // It passes the dojo.Deferred for the request with the topic.
+ // load: String
+ // "/dojo/io/load" is sent whenever an IO request has loaded
+ // successfully. It passes the response and the dojo.Deferred
+ // for the request with the topic.
+ // error: String
+ // "/dojo/io/error" is sent whenever an IO request has errored.
+ // It passes the error and the dojo.Deferred
+ // for the request with the topic.
+ // done: String
+ // "/dojo/io/done" is sent whenever an IO request has completed,
+ // either by loading or by erroring. It passes the error and
+ // the dojo.Deferred for the request with the topic.
+ // stop: String
+ // "/dojo/io/stop" is sent when all outstanding IO requests have
+ // finished. No arguments are passed with this topic.
+ });
+ =====*/
+
+
+ dojo._ioSetArgs = function(/*dojo/main.__IoArgs*/args,
+ /*Function*/canceller,
+ /*Function*/okHandler,
+ /*Function*/errHandler){
+ // summary:
+ // sets up the Deferred and ioArgs property on the Deferred so it
+ // can be used in an io call.
+ // args:
+ // The args object passed into the public io call. Recognized properties on
+ // the args object are:
+ // canceller:
+ // The canceller function used for the Deferred object. The function
+ // will receive one argument, the Deferred object that is related to the
+ // canceller.
+ // okHandler:
+ // The first OK callback to be registered with Deferred. It has the opportunity
+ // to transform the OK response. It will receive one argument -- the Deferred
+ // object returned from this function.
+ // errHandler:
+ // The first error callback to be registered with Deferred. It has the opportunity
+ // to do cleanup on an error. It will receive two arguments: error (the
+ // Error object) and dfd, the Deferred object returned from this function.
+
+ var ioArgs = {args: args, url: args.url};
+
+ //Get values from form if requested.
+ var formObject = null;
+ if(args.form){
+ var form = dom.byId(args.form);
+ //IE requires going through getAttributeNode instead of just getAttribute in some form cases,
+ //so use it for all. See #2844
+ var actnNode = form.getAttributeNode("action");
+ ioArgs.url = ioArgs.url || (actnNode ? actnNode.value : null);
+ formObject = domForm.toObject(form);
+ }
+
+ // set up the query params
+ var miArgs = [{}];
+
+ if(formObject){
+ // potentially over-ride url-provided params w/ form values
+ miArgs.push(formObject);
+ }
+ if(args.content){
+ // stuff in content over-rides what's set by form
+ miArgs.push(args.content);
+ }
+ if(args.preventCache){
+ miArgs.push({"dojo.preventCache": new Date().valueOf()});
+ }
+ ioArgs.query = ioq.objectToQuery(lang.mixin.apply(null, miArgs));
+
+ // .. and the real work of getting the deferred in order, etc.
+ ioArgs.handleAs = args.handleAs || "text";
+ var d = new Deferred(function(dfd){
+ dfd.canceled = true;
+ canceller && canceller(dfd);
+
+ var err = dfd.ioArgs.error;
+ if(!err){
+ err = new Error("request cancelled");
+ err.dojoType="cancel";
+ dfd.ioArgs.error = err;
+ }
+ return err;
+ });
+ d.addCallback(okHandler);
+
+ //Support specifying load, error and handle callback functions from the args.
+ //For those callbacks, the "this" object will be the args object.
+ //The callbacks will get the deferred result value as the
+ //first argument and the ioArgs object as the second argument.
+ var ld = args.load;
+ if(ld && lang.isFunction(ld)){
+ d.addCallback(function(value){
+ return ld.call(args, value, ioArgs);
+ });
+ }
+ var err = args.error;
+ if(err && lang.isFunction(err)){
+ d.addErrback(function(value){
+ return err.call(args, value, ioArgs);
+ });
+ }
+ var handle = args.handle;
+ if(handle && lang.isFunction(handle)){
+ d.addBoth(function(value){
+ return handle.call(args, value, ioArgs);
+ });
+ }
+
+ // Attach error handler last (not including topic publishing)
+ // to catch any errors that may have been generated from load
+ // or handle functions.
+ d.addErrback(function(error){
+ return errHandler(error, d);
+ });
+
+ //Plug in topic publishing, if dojo.publish is loaded.
+ if(cfg.ioPublish && dojo.publish && ioArgs.args.ioPublish !== false){
+ d.addCallbacks(
+ function(res){
+ dojo.publish("/dojo/io/load", [d, res]);
+ return res;
+ },
+ function(res){
+ dojo.publish("/dojo/io/error", [d, res]);
+ return res;
+ }
+ );
+ d.addBoth(function(res){
+ dojo.publish("/dojo/io/done", [d, res]);
+ return res;
+ });
+ }
+
+ d.ioArgs = ioArgs;
+
+ // FIXME: need to wire up the xhr object's abort method to something
+ // analogous in the Deferred
+ return d;
+ };
+
+ var _deferredOk = function(/*Deferred*/dfd){
+ // summary:
+ // okHandler function for dojo._ioSetArgs call.
+
+ var ret = handlers[dfd.ioArgs.handleAs](dfd.ioArgs.xhr);
+ return ret === undefined ? null : ret;
+ };
+ var _deferError = function(/*Error*/error, /*Deferred*/dfd){
+ // summary:
+ // errHandler function for dojo._ioSetArgs call.
+
+ if(!dfd.ioArgs.args.failOk){
+ console.error(error);
+ }
+ return error;
+ };
+
+ //Use a separate count for knowing if we are starting/stopping io calls.
+ var _checkPubCount = function(dfd){
+ if(_pubCount <= 0){
+ _pubCount = 0;
+ if(cfg.ioPublish && dojo.publish && (!dfd || dfd && dfd.ioArgs.args.ioPublish !== false)){
+ dojo.publish("/dojo/io/stop");
+ }
+ }
+ };
+
+ var _pubCount = 0;
+ aspect.after(watch, "_onAction", function(){
+ _pubCount -= 1;
+ });
+ aspect.after(watch, "_onInFlight", _checkPubCount);
+
+ dojo._ioCancelAll = watch.cancelAll;
+ /*=====
+ dojo._ioCancelAll = function(){
+ // summary:
+ // Cancels all pending IO requests, regardless of IO type
+ // (xhr, script, iframe).
+ };
+ =====*/
+
+ dojo._ioNotifyStart = function(/*Deferred*/dfd){
+ // summary:
+ // If dojo.publish is available, publish topics
+ // about the start of a request queue and/or the
+ // the beginning of request.
+ //
+ // Used by IO transports. An IO transport should
+ // call this method before making the network connection.
+ if(cfg.ioPublish && dojo.publish && dfd.ioArgs.args.ioPublish !== false){
+ if(!_pubCount){
+ dojo.publish("/dojo/io/start");
+ }
+ _pubCount += 1;
+ dojo.publish("/dojo/io/send", [dfd]);
+ }
+ };
+
+ dojo._ioWatch = function(dfd, validCheck, ioCheck, resHandle){
+ // summary:
+ // Watches the io request represented by dfd to see if it completes.
+ // dfd: Deferred
+ // The Deferred object to watch.
+ // validCheck: Function
+ // Function used to check if the IO request is still valid. Gets the dfd
+ // object as its only argument.
+ // ioCheck: Function
+ // Function used to check if basic IO call worked. Gets the dfd
+ // object as its only argument.
+ // resHandle: Function
+ // Function used to process response. Gets the dfd
+ // object as its only argument.
+
+ var args = dfd.ioArgs.options = dfd.ioArgs.args;
+ lang.mixin(dfd, {
+ response: dfd.ioArgs,
+ isValid: function(response){
+ return validCheck(dfd);
+ },
+ isReady: function(response){
+ return ioCheck(dfd);
+ },
+ handleResponse: function(response){
+ return resHandle(dfd);
+ }
+ });
+ watch(dfd);
+
+ _checkPubCount(dfd);
+ };
+
+ var _defaultContentType = "application/x-www-form-urlencoded";
+
+ dojo._ioAddQueryToUrl = function(/*dojo.__IoCallbackArgs*/ioArgs){
+ // summary:
+ // Adds query params discovered by the io deferred construction to the URL.
+ // Only use this for operations which are fundamentally GET-type operations.
+ if(ioArgs.query.length){
+ ioArgs.url += (ioArgs.url.indexOf("?") == -1 ? "?" : "&") + ioArgs.query;
+ ioArgs.query = null;
+ }
+ };
+
+ /*=====
+ dojo.__XhrArgs = declare(dojo.__IoArgs, {
+ // summary:
+ // In addition to the properties listed for the dojo._IoArgs type,
+ // the following properties are allowed for dojo.xhr* methods.
+ // handleAs: String?
+ // Acceptable values are: text (default), json, json-comment-optional,
+ // json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
+ // sync: Boolean?
+ // false is default. Indicates whether the request should
+ // be a synchronous (blocking) request.
+ // headers: Object?
+ // Additional HTTP headers to send in the request.
+ // failOk: Boolean?
+ // false is default. Indicates whether a request should be
+ // allowed to fail (and therefore no console error message in
+ // the event of a failure)
+ // contentType: String|Boolean
+ // "application/x-www-form-urlencoded" is default. Set to false to
+ // prevent a Content-Type header from being sent, or to a string
+ // to send a different Content-Type.
+ });
+ =====*/
+
+ dojo.xhr = function(/*String*/ method, /*dojo.__XhrArgs*/ args, /*Boolean?*/ hasBody){
+ // summary:
+ // Deprecated. Use dojo/request instead.
+ // description:
+ // Sends an HTTP request with the given method.
+ // See also dojo.xhrGet(), xhrPost(), xhrPut() and dojo.xhrDelete() for shortcuts
+ // for those HTTP methods. There are also methods for "raw" PUT and POST methods
+ // via dojo.rawXhrPut() and dojo.rawXhrPost() respectively.
+ // method:
+ // HTTP method to be used, such as GET, POST, PUT, DELETE. Should be uppercase.
+ // hasBody:
+ // If the request has an HTTP body, then pass true for hasBody.
+
+ var rDfd;
+ //Make the Deferred object for this xhr request.
+ var dfd = dojo._ioSetArgs(args, function(dfd){
+ rDfd && rDfd.cancel();
+ }, _deferredOk, _deferError);
+ var ioArgs = dfd.ioArgs;
+
+ //Allow for specifying the HTTP body completely.
+ if("postData" in args){
+ ioArgs.query = args.postData;
+ }else if("putData" in args){
+ ioArgs.query = args.putData;
+ }else if("rawBody" in args){
+ ioArgs.query = args.rawBody;
+ }else if((arguments.length > 2 && !hasBody) || "POST|PUT".indexOf(method.toUpperCase()) === -1){
+ //Check for hasBody being passed. If no hasBody,
+ //then only append query string if not a POST or PUT request.
+ dojo._ioAddQueryToUrl(ioArgs);
+ }
+
+ var options = {
+ method: method,
+ handleAs: "text",
+ timeout: args.timeout,
+ withCredentials: args.withCredentials,
+ ioArgs: ioArgs
+ };
+
+ if(typeof args.headers !== 'undefined'){
+ options.headers = args.headers;
+ }
+ if(typeof args.contentType !== 'undefined'){
+ if(!options.headers){
+ options.headers = {};
+ }
+ options.headers['Content-Type'] = args.contentType;
+ }
+ if(typeof ioArgs.query !== 'undefined'){
+ options.data = ioArgs.query;
+ }
+ if(typeof args.sync !== 'undefined'){
+ options.sync = args.sync;
+ }
+
+ dojo._ioNotifyStart(dfd);
+ try{
+ rDfd = _xhr(ioArgs.url, options, true);
+ }catch(e){
+ // If XHR creation fails, dojo/request/xhr throws
+ // When this happens, cancel the deferred
+ dfd.cancel();
+ return dfd;
+ }
+
+ // sync ioArgs
+ dfd.ioArgs.xhr = rDfd.response.xhr;
+
+ rDfd.then(function(){
+ dfd.resolve(dfd);
+ }).otherwise(function(error){
+ ioArgs.error = error;
+ if(error.response){
+ error.status = error.response.status;
+ error.responseText = error.response.text;
+ error.xhr = error.response.xhr;
+ }
+ dfd.reject(error);
+ });
+ return dfd; // dojo/_base/Deferred
+ };
+
+ dojo.xhrGet = function(/*dojo.__XhrArgs*/ args){
+ // summary:
+ // Sends an HTTP GET request to the server.
+ return dojo.xhr("GET", args); // dojo/_base/Deferred
+ };
+
+ dojo.rawXhrPost = dojo.xhrPost = function(/*dojo.__XhrArgs*/ args){
+ // summary:
+ // Sends an HTTP POST request to the server. In addition to the properties
+ // listed for the dojo.__XhrArgs type, the following property is allowed:
+ // postData:
+ // String. Send raw data in the body of the POST request.
+ return dojo.xhr("POST", args, true); // dojo/_base/Deferred
+ };
+
+ dojo.rawXhrPut = dojo.xhrPut = function(/*dojo.__XhrArgs*/ args){
+ // summary:
+ // Sends an HTTP PUT request to the server. In addition to the properties
+ // listed for the dojo.__XhrArgs type, the following property is allowed:
+ // putData:
+ // String. Send raw data in the body of the PUT request.
+ return dojo.xhr("PUT", args, true); // dojo/_base/Deferred
+ };
+
+ dojo.xhrDelete = function(/*dojo.__XhrArgs*/ args){
+ // summary:
+ // Sends an HTTP DELETE request to the server.
+ return dojo.xhr("DELETE", args); // dojo/_base/Deferred
+ };
+
+ /*
+ dojo.wrapForm = function(formNode){
+ // summary:
+ // A replacement for FormBind, but not implemented yet.
+
+ // FIXME: need to think harder about what extensions to this we might
+ // want. What should we allow folks to do w/ this? What events to
+ // set/send?
+ throw new Error("dojo.wrapForm not yet implemented");
+ }
+ */
+
+ dojo._isDocumentOk = function(x){
+ return util.checkStatus(x.status);
+ };
+
+ dojo._getText = function(url){
+ var result;
+ dojo.xhrGet({url:url, sync:true, load:function(text){
+ result = text;
+ }});
+ return result;
+ };
+
+ // Add aliases for static functions to dojo.xhr since dojo.xhr is what's returned from this module
+ lang.mixin(dojo.xhr, {
+ _xhrObj: dojo._xhrObj,
+ fieldToObject: domForm.fieldToObject,
+ formToObject: domForm.toObject,
+ objectToQuery: ioq.objectToQuery,
+ formToQuery: domForm.toQuery,
+ formToJson: domForm.toJson,
+ queryToObject: ioq.queryToObject,
+ contentHandlers: handlers,
+ _ioSetArgs: dojo._ioSetArgs,
+ _ioCancelAll: dojo._ioCancelAll,
+ _ioNotifyStart: dojo._ioNotifyStart,
+ _ioWatch: dojo._ioWatch,
+ _ioAddQueryToUrl: dojo._ioAddQueryToUrl,
+ _isDocumentOk: dojo._isDocumentOk,
+ _getText: dojo._getText,
+ get: dojo.xhrGet,
+ post: dojo.xhrPost,
+ put: dojo.xhrPut,
+ del: dojo.xhrDelete // because "delete" is a reserved word
+ });
+
+ return dojo.xhr;
+});
+
+},
+'dojo/loadInit':function(){
+define("dojo/loadInit", ["./_base/loader"], function(loader){
+ return {
+ dynamic:0,
+ normalize:function(id){return id;},
+ load:loader.loadInit
+ };
+});
+
+},
+'dojo/_base/unload':function(){
+define(["./kernel", "./lang", "../on"], function(dojo, lang, on){
+
+// module:
+// dojo/unload
+
+var win = window;
+
+var unload = {
+ // summary:
+ // This module contains the document and window unload detection API.
+
+ addOnWindowUnload: function(/*Object|Function?*/ obj, /*String|Function?*/ functionName){
+ // summary:
+ // registers a function to be triggered when window.onunload
+ // fires.
+ // description:
+ // The first time that addOnWindowUnload is called Dojo
+ // will register a page listener to trigger your unload
+ // handler with. Note that registering these handlers may
+ // destroy "fastback" page caching in browsers that support
+ // it. Be careful trying to modify the DOM or access
+ // JavaScript properties during this phase of page unloading:
+ // they may not always be available. Consider
+ // addOnUnload() if you need to modify the DOM or do
+ // heavy JavaScript work since it fires at the equivalent of
+ // the page's "onbeforeunload" event.
+ // example:
+ // | unload.addOnWindowUnload(functionPointer)
+ // | unload.addOnWindowUnload(object, "functionName");
+ // | unload.addOnWindowUnload(object, function(){ /* ... */});
+
+ if (!dojo.windowUnloaded){
+ on(win, "unload", (dojo.windowUnloaded = function(){
+ // summary:
+ // signal fired by impending window destruction. You may use
+ // dojo.addOnWindowUnload() to register a listener for this
+ // event. NOTE: if you wish to dojo.connect() to this method
+ // to perform page/application cleanup, be aware that this
+ // event WILL NOT fire if no handler has been registered with
+ // addOnWindowUnload(). This behavior started in Dojo 1.3.
+ // Previous versions always triggered windowUnloaded(). See
+ // addOnWindowUnload for more info.
+ }));
+ }
+ on(win, "unload", lang.hitch(obj, functionName));
+ },
+
+ addOnUnload: function(/*Object?|Function?*/ obj, /*String|Function?*/ functionName){
+ // summary:
+ // registers a function to be triggered when the page unloads.
+ // description:
+ // The first time that addOnUnload is called Dojo will
+ // register a page listener to trigger your unload handler
+ // with.
+ //
+ // In a browser environment, the functions will be triggered
+ // during the window.onbeforeunload event. Be careful of doing
+ // too much work in an unload handler. onbeforeunload can be
+ // triggered if a link to download a file is clicked, or if
+ // the link is a javascript: link. In these cases, the
+ // onbeforeunload event fires, but the document is not
+ // actually destroyed. So be careful about doing destructive
+ // operations in a dojo.addOnUnload callback.
+ //
+ // Further note that calling dojo.addOnUnload will prevent
+ // browsers from using a "fast back" cache to make page
+ // loading via back button instantaneous.
+ // example:
+ // | dojo.addOnUnload(functionPointer)
+ // | dojo.addOnUnload(object, "functionName")
+ // | dojo.addOnUnload(object, function(){ /* ... */});
+
+ on(win, "beforeunload", lang.hitch(obj, functionName));
+ }
+};
+
+dojo.addOnWindowUnload = unload.addOnWindowUnload;
+dojo.addOnUnload = unload.addOnUnload;
+
+return unload;
+
+});
+
+},
+'dojo/Deferred':function(){
+define([
+ "./has",
+ "./_base/lang",
+ "./errors/CancelError",
+ "./promise/Promise",
+ "./promise/instrumentation"
+], function(has, lang, CancelError, Promise, instrumentation){
+ "use strict";
+
+ // module:
+ // dojo/Deferred
+
+ var PROGRESS = 0,
+ RESOLVED = 1,
+ REJECTED = 2;
+ var FULFILLED_ERROR_MESSAGE = "This deferred has already been fulfilled.";
+
+ var freezeObject = Object.freeze || function(){};
+
+ var signalWaiting = function(waiting, type, result, rejection, deferred){
+ if( 1 ){
+ if(type === REJECTED && Deferred.instrumentRejected && waiting.length === 0){
+ Deferred.instrumentRejected(result, false, rejection, deferred);
+ }
+ }
+
+ for(var i = 0; i < waiting.length; i++){
+ signalListener(waiting[i], type, result, rejection);
+ }
+ };
+
+ var signalListener = function(listener, type, result, rejection){
+ var func = listener[type];
+ var deferred = listener.deferred;
+ if(func){
+ try{
+ var newResult = func(result);
+ if(type === PROGRESS){
+ if(typeof newResult !== "undefined"){
+ signalDeferred(deferred, type, newResult);
+ }
+ }else{
+ if(newResult && typeof newResult.then === "function"){
+ listener.cancel = newResult.cancel;
+ newResult.then(
+ // Only make resolvers if they're actually going to be used
+ makeDeferredSignaler(deferred, RESOLVED),
+ makeDeferredSignaler(deferred, REJECTED),
+ makeDeferredSignaler(deferred, PROGRESS));
+ return;
+ }
+ signalDeferred(deferred, RESOLVED, newResult);
+ }
+ }catch(error){
+ signalDeferred(deferred, REJECTED, error);
+ }
+ }else{
+ signalDeferred(deferred, type, result);
+ }
+
+ if( 1 ){
+ if(type === REJECTED && Deferred.instrumentRejected){
+ Deferred.instrumentRejected(result, !!func, rejection, deferred.promise);
+ }
+ }
+ };
+
+ var makeDeferredSignaler = function(deferred, type){
+ return function(value){
+ signalDeferred(deferred, type, value);
+ };
+ };
+
+ var signalDeferred = function(deferred, type, result){
+ if(!deferred.isCanceled()){
+ switch(type){
+ case PROGRESS:
+ deferred.progress(result);
+ break;
+ case RESOLVED:
+ deferred.resolve(result);
+ break;
+ case REJECTED:
+ deferred.reject(result);
+ break;
+ }
+ }
+ };
+
+ var Deferred = function(canceler){
+ // summary:
+ // Creates a new deferred. This API is preferred over
+ // `dojo/_base/Deferred`.
+ // description:
+ // Creates a new deferred, as an abstraction over (primarily)
+ // asynchronous operations. The deferred is the private interface
+ // that should not be returned to calling code. That's what the
+ // `promise` is for. See `dojo/promise/Promise`.
+ // canceler: Function?
+ // Will be invoked if the deferred is canceled. The canceler
+ // receives the reason the deferred was canceled as its argument.
+ // The deferred is rejected with its return value, or a new
+ // `dojo/errors/CancelError` instance.
+
+ // promise: dojo/promise/Promise
+ // The public promise object that clients can add callbacks to.
+ var promise = this.promise = new Promise();
+
+ var deferred = this;
+ var fulfilled, result, rejection;
+ var canceled = false;
+ var waiting = [];
+
+ if( 1 && Error.captureStackTrace){
+ Error.captureStackTrace(deferred, Deferred);
+ Error.captureStackTrace(promise, Deferred);
+ }
+
+ this.isResolved = promise.isResolved = function(){
+ // summary:
+ // Checks whether the deferred has been resolved.
+ // returns: Boolean
+
+ return fulfilled === RESOLVED;
+ };
+
+ this.isRejected = promise.isRejected = function(){
+ // summary:
+ // Checks whether the deferred has been rejected.
+ // returns: Boolean
+
+ return fulfilled === REJECTED;
+ };
+
+ this.isFulfilled = promise.isFulfilled = function(){
+ // summary:
+ // Checks whether the deferred has been resolved or rejected.
+ // returns: Boolean
+
+ return !!fulfilled;
+ };
+
+ this.isCanceled = promise.isCanceled = function(){
+ // summary:
+ // Checks whether the deferred has been canceled.
+ // returns: Boolean
+
+ return canceled;
+ };
+
+ this.progress = function(update, strict){
+ // summary:
+ // Emit a progress update on the deferred.
+ // description:
+ // Emit a progress update on the deferred. Progress updates
+ // can be used to communicate updates about the asynchronous
+ // operation before it has finished.
+ // update: any
+ // The progress update. Passed to progbacks.
+ // strict: Boolean?
+ // If strict, will throw an error if the deferred has already
+ // been fulfilled and consequently no progress can be emitted.
+ // returns: dojo/promise/Promise
+ // Returns the original promise for the deferred.
+
+ if(!fulfilled){
+ signalWaiting(waiting, PROGRESS, update, null, deferred);
+ return promise;
+ }else if(strict === true){
+ throw new Error(FULFILLED_ERROR_MESSAGE);
+ }else{
+ return promise;
+ }
+ };
+
+ this.resolve = function(value, strict){
+ // summary:
+ // Resolve the deferred.
+ // description:
+ // Resolve the deferred, putting it in a success state.
+ // value: any
+ // The result of the deferred. Passed to callbacks.
+ // strict: Boolean?
+ // If strict, will throw an error if the deferred has already
+ // been fulfilled and consequently cannot be resolved.
+ // returns: dojo/promise/Promise
+ // Returns the original promise for the deferred.
+
+ if(!fulfilled){
+ // Set fulfilled, store value. After signaling waiting listeners unset
+ // waiting.
+ signalWaiting(waiting, fulfilled = RESOLVED, result = value, null, deferred);
+ waiting = null;
+ return promise;
+ }else if(strict === true){
+ throw new Error(FULFILLED_ERROR_MESSAGE);
+ }else{
+ return promise;
+ }
+ };
+
+ var reject = this.reject = function(error, strict){
+ // summary:
+ // Reject the deferred.
+ // description:
+ // Reject the deferred, putting it in an error state.
+ // error: any
+ // The error result of the deferred. Passed to errbacks.
+ // strict: Boolean?
+ // If strict, will throw an error if the deferred has already
+ // been fulfilled and consequently cannot be rejected.
+ // returns: dojo/promise/Promise
+ // Returns the original promise for the deferred.
+
+ if(!fulfilled){
+ if( 1 && Error.captureStackTrace){
+ Error.captureStackTrace(rejection = {}, reject);
+ }
+ signalWaiting(waiting, fulfilled = REJECTED, result = error, rejection, deferred);
+ waiting = null;
+ return promise;
+ }else if(strict === true){
+ throw new Error(FULFILLED_ERROR_MESSAGE);
+ }else{
+ return promise;
+ }
+ };
+
+ this.then = promise.then = function(callback, errback, progback){
+ // summary:
+ // Add new callbacks to the deferred.
+ // description:
+ // Add new callbacks to the deferred. Callbacks can be added
+ // before or after the deferred is fulfilled.
+ // callback: Function?
+ // Callback to be invoked when the promise is resolved.
+ // Receives the resolution value.
+ // errback: Function?
+ // Callback to be invoked when the promise is rejected.
+ // Receives the rejection error.
+ // progback: Function?
+ // Callback to be invoked when the promise emits a progress
+ // update. Receives the progress update.
+ // returns: dojo/promise/Promise
+ // Returns a new promise for the result of the callback(s).
+ // This can be used for chaining many asynchronous operations.
+
+ var listener = [progback, callback, errback];
+ // Ensure we cancel the promise we're waiting for, or if callback/errback
+ // have returned a promise, cancel that one.
+ listener.cancel = promise.cancel;
+ listener.deferred = new Deferred(function(reason){
+ // Check whether cancel is really available, returned promises are not
+ // required to expose `cancel`
+ return listener.cancel && listener.cancel(reason);
+ });
+ if(fulfilled && !waiting){
+ signalListener(listener, fulfilled, result, rejection);
+ }else{
+ waiting.push(listener);
+ }
+ return listener.deferred.promise;
+ };
+
+ this.cancel = promise.cancel = function(reason, strict){
+ // summary:
+ // Inform the deferred it may cancel its asynchronous operation.
+ // description:
+ // Inform the deferred it may cancel its asynchronous operation.
+ // The deferred's (optional) canceler is invoked and the
+ // deferred will be left in a rejected state. Can affect other
+ // promises that originate with the same deferred.
+ // reason: any
+ // A message that may be sent to the deferred's canceler,
+ // explaining why it's being canceled.
+ // strict: Boolean?
+ // If strict, will throw an error if the deferred has already
+ // been fulfilled and consequently cannot be canceled.
+ // returns: any
+ // Returns the rejection reason if the deferred was canceled
+ // normally.
+
+ if(!fulfilled){
+ // Cancel can be called even after the deferred is fulfilled
+ if(canceler){
+ var returnedReason = canceler(reason);
+ reason = typeof returnedReason === "undefined" ? reason : returnedReason;
+ }
+ canceled = true;
+ if(!fulfilled){
+ // Allow canceler to provide its own reason, but fall back to a CancelError
+ if(typeof reason === "undefined"){
+ reason = new CancelError();
+ }
+ reject(reason);
+ return reason;
+ }else if(fulfilled === REJECTED && result === reason){
+ return reason;
+ }
+ }else if(strict === true){
+ throw new Error(FULFILLED_ERROR_MESSAGE);
+ }
+ };
+
+ freezeObject(promise);
+ };
+
+ Deferred.prototype.toString = function(){
+ // returns: String
+ // Returns `[object Deferred]`.
+
+ return "[object Deferred]";
+ };
+
+ if(instrumentation){
+ instrumentation(Deferred);
+ }
+
+ return Deferred;
+});
+
+},
+'dojo/_base/NodeList':function(){
+define("dojo/_base/NodeList", ["./kernel", "../query", "./array", "./html", "../NodeList-dom"], function(dojo, query, array){
+ // module:
+ // dojo/_base/NodeList
+
+ /*=====
+ return {
+ // summary:
+ // This module extends dojo/NodeList with the legacy connect(), coords(),
+ // blur(), focus(), change(), click(), error(), keydown(), keypress(),
+ // keyup(), load(), mousedown(), mouseenter(), mouseleave(), mousemove(),
+ // mouseout(), mouseover(), mouseup(), and submit() methods.
+ };
+ =====*/
+
+ var NodeList = query.NodeList,
+ nlp = NodeList.prototype;
+
+ nlp.connect = NodeList._adaptAsForEach(function(){
+ // don't bind early to dojo.connect since we no longer explicitly depend on it
+ return dojo.connect.apply(this, arguments);
+ });
+ /*=====
+ nlp.connect = function(methodName, objOrFunc, funcName){
+ // summary:
+ // Attach event handlers to every item of the NodeList. Uses dojo.connect()
+ // so event properties are normalized.
+ //
+ // Application must manually require() "dojo/_base/connect" before using this method.
+ // methodName: String
+ // the name of the method to attach to. For DOM events, this should be
+ // the lower-case name of the event
+ // objOrFunc: Object|Function|String
+ // if 2 arguments are passed (methodName, objOrFunc), objOrFunc should
+ // reference a function or be the name of the function in the global
+ // namespace to attach. If 3 arguments are provided
+ // (methodName, objOrFunc, funcName), objOrFunc must be the scope to
+ // locate the bound function in
+ // funcName: String?
+ // optional. A string naming the function in objOrFunc to bind to the
+ // event. May also be a function reference.
+ // example:
+ // add an onclick handler to every button on the page
+ // | query("div:nth-child(odd)").connect("onclick", function(e){
+ // | console.log("clicked!");
+ // | });
+ // example:
+ // attach foo.bar() to every odd div's onmouseover
+ // | query("div:nth-child(odd)").connect("onmouseover", foo, "bar");
+
+ return null; // NodeList
+ };
+ =====*/
+
+ nlp.coords = NodeList._adaptAsMap(dojo.coords);
+ /*=====
+ nlp.coords = function(){
+ // summary:
+ // Deprecated: Use position() for border-box x/y/w/h
+ // or marginBox() for margin-box w/h/l/t.
+ // Returns the box objects of all elements in a node list as
+ // an Array (*not* a NodeList). Acts like `domGeom.coords`, though assumes
+ // the node passed is each node in this list.
+
+ return []; // Array
+ };
+ =====*/
+
+ NodeList.events = [
+ // summary:
+ // list of all DOM events used in NodeList
+ "blur", "focus", "change", "click", "error", "keydown", "keypress",
+ "keyup", "load", "mousedown", "mouseenter", "mouseleave", "mousemove",
+ "mouseout", "mouseover", "mouseup", "submit"
+ ];
+
+ // FIXME: pseudo-doc the above automatically generated on-event functions
+
+ // syntactic sugar for DOM events
+ array.forEach(NodeList.events, function(evt){
+ var _oe = "on" + evt;
+ nlp[_oe] = function(a, b){
+ return this.connect(_oe, a, b);
+ };
+ // FIXME: should these events trigger publishes?
+ /*
+ return (a ? this.connect(_oe, a, b) :
+ this.forEach(function(n){
+ // FIXME:
+ // listeners get buried by
+ // addEventListener and can't be dug back
+ // out to be triggered externally.
+ // see:
+ // http://developer.mozilla.org/en/docs/DOM:element
+
+ console.log(n, evt, _oe);
+
+ // FIXME: need synthetic event support!
+ var _e = { target: n, faux: true, type: evt };
+ // dojo._event_listener._synthesizeEvent({}, { target: n, faux: true, type: evt });
+ try{ n[evt](_e); }catch(e){ console.log(e); }
+ try{ n[_oe](_e); }catch(e){ console.log(e); }
+ })
+ );
+ */
+ }
+ );
+
+ dojo.NodeList = NodeList;
+ return NodeList;
+});
+
+},
+'dojo/_base/Color':function(){
+define(["./kernel", "./lang", "./array", "./config"], function(dojo, lang, ArrayUtil, config){
+
+ var Color = dojo.Color = function(/*Array|String|Object*/ color){
+ // summary:
+ // Takes a named string, hex string, array of rgb or rgba values,
+ // an object with r, g, b, and a properties, or another `Color` object
+ // and creates a new Color instance to work from.
+ //
+ // example:
+ // Work with a Color instance:
+ // | var c = new Color();
+ // | c.setColor([0,0,0]); // black
+ // | var hex = c.toHex(); // #000000
+ //
+ // example:
+ // Work with a node's color:
+ // | var color = dojo.style("someNode", "backgroundColor");
+ // | var n = new Color(color);
+ // | // adjust the color some
+ // | n.r *= .5;
+ // | console.log(n.toString()); // rgb(128, 255, 255);
+ if(color){ this.setColor(color); }
+ };
+
+ // FIXME:
+ // there's got to be a more space-efficient way to encode or discover
+ // these!! Use hex?
+ Color.named = {
+ // summary:
+ // Dictionary list of all CSS named colors, by name. Values are 3-item arrays with corresponding RG and B values.
+ "black": [0,0,0],
+ "silver": [192,192,192],
+ "gray": [128,128,128],
+ "white": [255,255,255],
+ "maroon": [128,0,0],
+ "red": [255,0,0],
+ "purple": [128,0,128],
+ "fuchsia":[255,0,255],
+ "green": [0,128,0],
+ "lime": [0,255,0],
+ "olive": [128,128,0],
+ "yellow": [255,255,0],
+ "navy": [0,0,128],
+ "blue": [0,0,255],
+ "teal": [0,128,128],
+ "aqua": [0,255,255],
+ "transparent": config.transparentColor || [0,0,0,0]
+ };
+
+ lang.extend(Color, {
+ r: 255, g: 255, b: 255, a: 1,
+ _set: function(r, g, b, a){
+ var t = this; t.r = r; t.g = g; t.b = b; t.a = a;
+ },
+ setColor: function(/*Array|String|Object*/ color){
+ // summary:
+ // Takes a named string, hex string, array of rgb or rgba values,
+ // an object with r, g, b, and a properties, or another `Color` object
+ // and sets this color instance to that value.
+ //
+ // example:
+ // | var c = new Color(); // no color
+ // | c.setColor("#ededed"); // greyish
+ if(lang.isString(color)){
+ Color.fromString(color, this);
+ }else if(lang.isArray(color)){
+ Color.fromArray(color, this);
+ }else{
+ this._set(color.r, color.g, color.b, color.a);
+ if(!(color instanceof Color)){ this.sanitize(); }
+ }
+ return this; // Color
+ },
+ sanitize: function(){
+ // summary:
+ // Ensures the object has correct attributes
+ // description:
+ // the default implementation does nothing, include dojo.colors to
+ // augment it with real checks
+ return this; // Color
+ },
+ toRgb: function(){
+ // summary:
+ // Returns 3 component array of rgb values
+ // example:
+ // | var c = new Color("#000000");
+ // | console.log(c.toRgb()); // [0,0,0]
+ var t = this;
+ return [t.r, t.g, t.b]; // Array
+ },
+ toRgba: function(){
+ // summary:
+ // Returns a 4 component array of rgba values from the color
+ // represented by this object.
+ var t = this;
+ return [t.r, t.g, t.b, t.a]; // Array
+ },
+ toHex: function(){
+ // summary:
+ // Returns a CSS color string in hexadecimal representation
+ // example:
+ // | console.log(new Color([0,0,0]).toHex()); // #000000
+ var arr = ArrayUtil.map(["r", "g", "b"], function(x){
+ var s = this[x].toString(16);
+ return s.length < 2 ? "0" + s : s;
+ }, this);
+ return "#" + arr.join(""); // String
+ },
+ toCss: function(/*Boolean?*/ includeAlpha){
+ // summary:
+ // Returns a css color string in rgb(a) representation
+ // example:
+ // | var c = new Color("#FFF").toCss();
+ // | console.log(c); // rgb('255','255','255')
+ var t = this, rgb = t.r + ", " + t.g + ", " + t.b;
+ return (includeAlpha ? "rgba(" + rgb + ", " + t.a : "rgb(" + rgb) + ")"; // String
+ },
+ toString: function(){
+ // summary:
+ // Returns a visual representation of the color
+ return this.toCss(true); // String
+ }
+ });
+
+ Color.blendColors = dojo.blendColors = function(
+ /*Color*/ start,
+ /*Color*/ end,
+ /*Number*/ weight,
+ /*Color?*/ obj
+ ){
+ // summary:
+ // Blend colors end and start with weight from 0 to 1, 0.5 being a 50/50 blend,
+ // can reuse a previously allocated Color object for the result
+ var t = obj || new Color();
+ ArrayUtil.forEach(["r", "g", "b", "a"], function(x){
+ t[x] = start[x] + (end[x] - start[x]) * weight;
+ if(x != "a"){ t[x] = Math.round(t[x]); }
+ });
+ return t.sanitize(); // Color
+ };
+
+ Color.fromRgb = dojo.colorFromRgb = function(/*String*/ color, /*Color?*/ obj){
+ // summary:
+ // Returns a `Color` instance from a string of the form
+ // "rgb(...)" or "rgba(...)". Optionally accepts a `Color`
+ // object to update with the parsed value and return instead of
+ // creating a new object.
+ // returns:
+ // A Color object. If obj is passed, it will be the return value.
+ var m = color.toLowerCase().match(/^rgba?\(([\s\.,0-9]+)\)/);
+ return m && Color.fromArray(m[1].split(/\s*,\s*/), obj); // Color
+ };
+
+ Color.fromHex = dojo.colorFromHex = function(/*String*/ color, /*Color?*/ obj){
+ // summary:
+ // Converts a hex string with a '#' prefix to a color object.
+ // Supports 12-bit #rgb shorthand. Optionally accepts a
+ // `Color` object to update with the parsed value.
+ //
+ // returns:
+ // A Color object. If obj is passed, it will be the return value.
+ //
+ // example:
+ // | var thing = dojo.colorFromHex("#ededed"); // grey, longhand
+ //
+ // example:
+ // | var thing = dojo.colorFromHex("#000"); // black, shorthand
+ var t = obj || new Color(),
+ bits = (color.length == 4) ? 4 : 8,
+ mask = (1 << bits) - 1;
+ color = Number("0x" + color.substr(1));
+ if(isNaN(color)){
+ return null; // Color
+ }
+ ArrayUtil.forEach(["b", "g", "r"], function(x){
+ var c = color & mask;
+ color >>= bits;
+ t[x] = bits == 4 ? 17 * c : c;
+ });
+ t.a = 1;
+ return t; // Color
+ };
+
+ Color.fromArray = dojo.colorFromArray = function(/*Array*/ a, /*Color?*/ obj){
+ // summary:
+ // Builds a `Color` from a 3 or 4 element array, mapping each
+ // element in sequence to the rgb(a) values of the color.
+ // example:
+ // | var myColor = dojo.colorFromArray([237,237,237,0.5]); // grey, 50% alpha
+ // returns:
+ // A Color object. If obj is passed, it will be the return value.
+ var t = obj || new Color();
+ t._set(Number(a[0]), Number(a[1]), Number(a[2]), Number(a[3]));
+ if(isNaN(t.a)){ t.a = 1; }
+ return t.sanitize(); // Color
+ };
+
+ Color.fromString = dojo.colorFromString = function(/*String*/ str, /*Color?*/ obj){
+ // summary:
+ // Parses `str` for a color value. Accepts hex, rgb, and rgba
+ // style color values.
+ // description:
+ // Acceptable input values for str may include arrays of any form
+ // accepted by dojo.colorFromArray, hex strings such as "#aaaaaa", or
+ // rgb or rgba strings such as "rgb(133, 200, 16)" or "rgba(10, 10,
+ // 10, 50)"
+ // returns:
+ // A Color object. If obj is passed, it will be the return value.
+ var a = Color.named[str];
+ return a && Color.fromArray(a, obj) || Color.fromRgb(str, obj) || Color.fromHex(str, obj); // Color
+ };
+
+ return Color;
+});
+
+},
+'dojo/promise/instrumentation':function(){
+define([
+ "./tracer",
+ "../has",
+ "../_base/lang",
+ "../_base/array"
+], function(tracer, has, lang, arrayUtil){
+ function logError(error, rejection, deferred){
+ var stack = "";
+ if(error && error.stack){
+ stack += error.stack;
+ }
+ if(rejection && rejection.stack){
+ stack += "\n ----------------------------------------\n rejected" + rejection.stack.split("\n").slice(1).join("\n").replace(/^\s+/, " ");
+ }
+ if(deferred && deferred.stack){
+ stack += "\n ----------------------------------------\n" + deferred.stack;
+ }
+ console.error(error, stack);
+ }
+
+ function reportRejections(error, handled, rejection, deferred){
+ if(!handled){
+ logError(error, rejection, deferred);
+ }
+ }
+
+ var errors = [];
+ var activeTimeout = false;
+ var unhandledWait = 1000;
+ function trackUnhandledRejections(error, handled, rejection, deferred){
+ if(handled){
+ arrayUtil.some(errors, function(obj, ix){
+ if(obj.error === error){
+ errors.splice(ix, 1);
+ return true;
+ }
+ });
+ }else if(!arrayUtil.some(errors, function(obj){ return obj.error === error; })){
+ errors.push({
+ error: error,
+ rejection: rejection,
+ deferred: deferred,
+ timestamp: new Date().getTime()
+ });
+ }
+
+ if(!activeTimeout){
+ activeTimeout = setTimeout(logRejected, unhandledWait);
+ }
+ }
+
+ function logRejected(){
+ var now = new Date().getTime();
+ var reportBefore = now - unhandledWait;
+ errors = arrayUtil.filter(errors, function(obj){
+ if(obj.timestamp < reportBefore){
+ logError(obj.error, obj.rejection, obj.deferred);
+ return false;
+ }
+ return true;
+ });
+
+ if(errors.length){
+ activeTimeout = setTimeout(logRejected, errors[0].timestamp + unhandledWait - now);
+ }
+ }
+
+ return function(Deferred){
+ // summary:
+ // Initialize instrumentation for the Deferred class.
+ // description:
+ // Initialize instrumentation for the Deferred class.
+ // Done automatically by `dojo/Deferred` if the
+ // `deferredInstrumentation` and `useDeferredInstrumentation`
+ // config options are set.
+ //
+ // Sets up `dojo/promise/tracer` to log to the console.
+ //
+ // Sets up instrumentation of rejected deferreds so unhandled
+ // errors are logged to the console.
+
+ var usage = has("config-useDeferredInstrumentation");
+ if(usage){
+ tracer.on("resolved", lang.hitch(console, "log", "resolved"));
+ tracer.on("rejected", lang.hitch(console, "log", "rejected"));
+ tracer.on("progress", lang.hitch(console, "log", "progress"));
+
+ var args = [];
+ if(typeof usage === "string"){
+ args = usage.split(",");
+ usage = args.shift();
+ }
+ if(usage === "report-rejections"){
+ Deferred.instrumentRejected = reportRejections;
+ }else if(usage === "report-unhandled-rejections" || usage === true || usage === 1){
+ Deferred.instrumentRejected = trackUnhandledRejections;
+ unhandledWait = parseInt(args[0], 10) || unhandledWait;
+ }else{
+ throw new Error("Unsupported instrumentation usage <" + usage + ">");
+ }
+ }
+ };
+});
+
+},
+'dojo/selector/_loader':function(){
+define(["../has", "require"],
+ function(has, require){
+
+"use strict";
+var testDiv = document.createElement("div");
+has.add("dom-qsa2.1", !!testDiv.querySelectorAll);
+has.add("dom-qsa3", function(){
+ // test to see if we have a reasonable native selector engine available
+ try{
+ testDiv.innerHTML = "
"; // test kind of from sizzle
+ // Safari can't handle uppercase or unicode characters when
+ // in quirks mode, IE8 can't handle pseudos like :empty
+ return testDiv.querySelectorAll(".TEST:empty").length == 1;
+ }catch(e){}
+ });
+var fullEngine;
+var acme = "./acme", lite = "./lite";
+return {
+ // summary:
+ // This module handles loading the appropriate selector engine for the given browser
+
+ load: function(id, parentRequire, loaded, config){
+ var req = require;
+ // here we implement the default logic for choosing a selector engine
+ id = id == "default" ? has("config-selectorEngine") || "css3" : id;
+ id = id == "css2" || id == "lite" ? lite :
+ id == "css2.1" ? has("dom-qsa2.1") ? lite : acme :
+ id == "css3" ? has("dom-qsa3") ? lite : acme :
+ id == "acme" ? acme : (req = parentRequire) && id;
+ if(id.charAt(id.length-1) == '?'){
+ id = id.substring(0,id.length - 1);
+ var optionalLoad = true;
+ }
+ // the query engine is optional, only load it if a native one is not available or existing one has not been loaded
+ if(optionalLoad && (has("dom-compliant-qsa") || fullEngine)){
+ return loaded(fullEngine);
+ }
+ // load the referenced selector engine
+ req([id], function(engine){
+ if(id != "./lite"){
+ fullEngine = engine;
+ }
+ loaded(engine);
+ });
+ }
+};
+});
+
+},
+'dojo/promise/Promise':function(){
+define([
+ "../_base/lang"
+], function(lang){
+ "use strict";
+
+ // module:
+ // dojo/promise/Promise
+
+ function throwAbstract(){
+ throw new TypeError("abstract");
+ }
+
+ return lang.extend(function Promise(){
+ // summary:
+ // The public interface to a deferred.
+ // description:
+ // The public interface to a deferred. All promises in Dojo are
+ // instances of this class.
+ }, {
+ then: function(callback, errback, progback){
+ // summary:
+ // Add new callbacks to the promise.
+ // description:
+ // Add new callbacks to the deferred. Callbacks can be added
+ // before or after the deferred is fulfilled.
+ // callback: Function?
+ // Callback to be invoked when the promise is resolved.
+ // Receives the resolution value.
+ // errback: Function?
+ // Callback to be invoked when the promise is rejected.
+ // Receives the rejection error.
+ // progback: Function?
+ // Callback to be invoked when the promise emits a progress
+ // update. Receives the progress update.
+ // returns: dojo/promise/Promise
+ // Returns a new promise for the result of the callback(s).
+ // This can be used for chaining many asynchronous operations.
+
+ throwAbstract();
+ },
+
+ cancel: function(reason, strict){
+ // summary:
+ // Inform the deferred it may cancel its asynchronous operation.
+ // description:
+ // Inform the deferred it may cancel its asynchronous operation.
+ // The deferred's (optional) canceler is invoked and the
+ // deferred will be left in a rejected state. Can affect other
+ // promises that originate with the same deferred.
+ // reason: any
+ // A message that may be sent to the deferred's canceler,
+ // explaining why it's being canceled.
+ // strict: Boolean?
+ // If strict, will throw an error if the deferred has already
+ // been fulfilled and consequently cannot be canceled.
+ // returns: any
+ // Returns the rejection reason if the deferred was canceled
+ // normally.
+
+ throwAbstract();
+ },
+
+ isResolved: function(){
+ // summary:
+ // Checks whether the promise has been resolved.
+ // returns: Boolean
+
+ throwAbstract();
+ },
+
+ isRejected: function(){
+ // summary:
+ // Checks whether the promise has been rejected.
+ // returns: Boolean
+
+ throwAbstract();
+ },
+
+ isFulfilled: function(){
+ // summary:
+ // Checks whether the promise has been resolved or rejected.
+ // returns: Boolean
+
+ throwAbstract();
+ },
+
+ isCanceled: function(){
+ // summary:
+ // Checks whether the promise has been canceled.
+ // returns: Boolean
+
+ throwAbstract();
+ },
+
+ always: function(callbackOrErrback){
+ // summary:
+ // Add a callback to be invoked when the promise is resolved
+ // or rejected.
+ // callbackOrErrback: Function?
+ // A function that is used both as a callback and errback.
+ // returns: dojo/promise/Promise
+ // Returns a new promise for the result of the callback/errback.
+
+ return this.then(callbackOrErrback, callbackOrErrback);
+ },
+
+ otherwise: function(errback){
+ // summary:
+ // Add new errbacks to the promise.
+ // errback: Function?
+ // Callback to be invoked when the promise is rejected.
+ // returns: dojo/promise/Promise
+ // Returns a new promise for the result of the errback.
+
+ return this.then(null, errback);
+ },
+
+ trace: function(){
+ return this;
+ },
+
+ traceRejected: function(){
+ return this;
+ },
+
+ toString: function(){
+ // returns: string
+ // Returns `[object Promise]`.
+
+ return "[object Promise]";
+ }
+ });
+});
+
+},
+'dojo/request/watch':function(){
+define([
+ './util',
+ '../errors/RequestTimeoutError',
+ '../errors/CancelError',
+ '../_base/array',
+ '../_base/window',
+ '../has!host-browser?dom-addeventlistener?:../on:'
+], function(util, RequestTimeoutError, CancelError, array, win, on){
+ // avoid setting a timer per request. It degrades performance on IE
+ // something fierece if we don't use unified loops.
+ var _inFlightIntvl = null,
+ _inFlight = [];
+
+ function watchInFlight(){
+ // summary:
+ // internal method that checks each inflight XMLHttpRequest to see
+ // if it has completed or if the timeout situation applies.
+
+ var now = +(new Date);
+
+ // we need manual loop because we often modify _inFlight (and therefore 'i') while iterating
+ for(var i = 0, dfd; i < _inFlight.length && (dfd = _inFlight[i]); i++){
+ var response = dfd.response,
+ options = response.options;
+ if((dfd.isCanceled && dfd.isCanceled()) || (dfd.isValid && !dfd.isValid(response))){
+ _inFlight.splice(i--, 1);
+ watch._onAction && watch._onAction();
+ }else if(dfd.isReady && dfd.isReady(response)){
+ _inFlight.splice(i--, 1);
+ dfd.handleResponse(response);
+ watch._onAction && watch._onAction();
+ }else if(dfd.startTime){
+ // did we timeout?
+ if(dfd.startTime + (options.timeout || 0) < now){
+ _inFlight.splice(i--, 1);
+ // Cancel the request so the io module can do appropriate cleanup.
+ dfd.cancel(new RequestTimeoutError('Timeout exceeded', response));
+ watch._onAction && watch._onAction();
+ }
+ }
+ }
+
+ watch._onInFlight && watch._onInFlight(dfd);
+
+ if(!_inFlight.length){
+ clearInterval(_inFlightIntvl);
+ _inFlightIntvl = null;
+ }
+ }
+
+ function watch(dfd){
+ // summary:
+ // Watches the io request represented by dfd to see if it completes.
+ // dfd: Deferred
+ // The Deferred object to watch.
+ // response: Object
+ // The object used as the value of the request promise.
+ // validCheck: Function
+ // Function used to check if the IO request is still valid. Gets the dfd
+ // object as its only argument.
+ // ioCheck: Function
+ // Function used to check if basic IO call worked. Gets the dfd
+ // object as its only argument.
+ // resHandle: Function
+ // Function used to process response. Gets the dfd
+ // object as its only argument.
+ if(dfd.response.options.timeout){
+ dfd.startTime = +(new Date);
+ }
+
+ if(dfd.isFulfilled()){
+ // bail out if the deferred is already fulfilled
+ return;
+ }
+
+ _inFlight.push(dfd);
+ if(!_inFlightIntvl){
+ _inFlightIntvl = setInterval(watchInFlight, 50);
+ }
+
+ // handle sync requests separately from async:
+ // http://bugs.dojotoolkit.org/ticket/8467
+ if(dfd.response.options.sync){
+ watchInFlight();
+ }
+ }
+
+ watch.cancelAll = function cancelAll(){
+ // summary:
+ // Cancels all pending IO requests, regardless of IO type
+ try{
+ array.forEach(_inFlight, function(dfd){
+ try{
+ dfd.cancel(new CancelError('All requests canceled.'));
+ }catch(e){}
+ });
+ }catch(e){}
+ };
+
+ if(win && on && win.doc.attachEvent){
+ // Automatically call cancel all io calls on unload in IE
+ // http://bugs.dojotoolkit.org/ticket/2357
+ on(win.global, 'unload', function(){
+ watch.cancelAll();
+ });
+ }
+
+ return watch;
+});
+
+},
+'dojo/on':function(){
+define(["./has!dom-addeventlistener?:./aspect", "./_base/kernel", "./has"], function(aspect, dojo, has){
+
+ "use strict";
+ if( 1 ){ // check to make sure we are in a browser, this module should work anywhere
+ var major = window.ScriptEngineMajorVersion;
+ has.add("jscript", major && (major() + ScriptEngineMinorVersion() / 10));
+ has.add("event-orientationchange", has("touch") && !has("android")); // TODO: how do we detect this?
+ has.add("event-stopimmediatepropagation", window.Event && !!window.Event.prototype && !!window.Event.prototype.stopImmediatePropagation);
+ }
+ var on = function(target, type, listener, dontFix){
+ // summary:
+ // A function that provides core event listening functionality. With this function
+ // you can provide a target, event type, and listener to be notified of
+ // future matching events that are fired.
+ // target: Element|Object
+ // This is the target object or DOM element that to receive events from
+ // type: String|Function
+ // This is the name of the event to listen for or an extension event type.
+ // listener: Function
+ // This is the function that should be called when the event fires.
+ // returns: Object
+ // An object with a remove() method that can be used to stop listening for this
+ // event.
+ // description:
+ // To listen for "click" events on a button node, we can do:
+ // | define(["dojo/on"], function(listen){
+ // | on(button, "click", clickHandler);
+ // | ...
+ // Evented JavaScript objects can also have their own events.
+ // | var obj = new Evented;
+ // | on(obj, "foo", fooHandler);
+ // And then we could publish a "foo" event:
+ // | on.emit(obj, "foo", {key: "value"});
+ // We can use extension events as well. For example, you could listen for a tap gesture:
+ // | define(["dojo/on", "dojo/gesture/tap", function(listen, tap){
+ // | on(button, tap, tapHandler);
+ // | ...
+ // which would trigger fooHandler. Note that for a simple object this is equivalent to calling:
+ // | obj.onfoo({key:"value"});
+ // If you use on.emit on a DOM node, it will use native event dispatching when possible.
+
+ if(typeof target.on == "function" && typeof type != "function"){
+ // delegate to the target's on() method, so it can handle it's own listening if it wants
+ return target.on(type, listener);
+ }
+ // delegate to main listener code
+ return on.parse(target, type, listener, addListener, dontFix, this);
+ };
+ on.pausable = function(target, type, listener, dontFix){
+ // summary:
+ // This function acts the same as on(), but with pausable functionality. The
+ // returned signal object has pause() and resume() functions. Calling the
+ // pause() method will cause the listener to not be called for future events. Calling the
+ // resume() method will cause the listener to again be called for future events.
+ var paused;
+ var signal = on(target, type, function(){
+ if(!paused){
+ return listener.apply(this, arguments);
+ }
+ }, dontFix);
+ signal.pause = function(){
+ paused = true;
+ };
+ signal.resume = function(){
+ paused = false;
+ };
+ return signal;
+ };
+ on.once = function(target, type, listener, dontFix){
+ // summary:
+ // This function acts the same as on(), but will only call the listener once. The
+ // listener will be called for the first
+ // event that takes place and then listener will automatically be removed.
+ var signal = on(target, type, function(){
+ // remove this listener
+ signal.remove();
+ // proceed to call the listener
+ return listener.apply(this, arguments);
+ });
+ return signal;
+ };
+ on.parse = function(target, type, listener, addListener, dontFix, matchesTarget){
+ if(type.call){
+ // event handler function
+ // on(node, touch.press, touchListener);
+ return type.call(matchesTarget, target, listener);
+ }
+
+ if(type.indexOf(",") > -1){
+ // we allow comma delimited event names, so you can register for multiple events at once
+ var events = type.split(/\s*,\s*/);
+ var handles = [];
+ var i = 0;
+ var eventName;
+ while(eventName = events[i++]){
+ handles.push(addListener(target, eventName, listener, dontFix, matchesTarget));
+ }
+ handles.remove = function(){
+ for(var i = 0; i < handles.length; i++){
+ handles[i].remove();
+ }
+ };
+ return handles;
+ }
+ return addListener(target, type, listener, dontFix, matchesTarget);
+ };
+ var touchEvents = /^touch/;
+ function addListener(target, type, listener, dontFix, matchesTarget){
+ // event delegation:
+ var selector = type.match(/(.*):(.*)/);
+ // if we have a selector:event, the last one is interpreted as an event, and we use event delegation
+ if(selector){
+ type = selector[2];
+ selector = selector[1];
+ // create the extension event for selectors and directly call it
+ return on.selector(selector, type).call(matchesTarget, target, listener);
+ }
+ // test to see if it a touch event right now, so we don't have to do it every time it fires
+ if(has("touch")){
+ if(touchEvents.test(type)){
+ // touch event, fix it
+ listener = fixTouchListener(listener);
+ }
+ if(!has("event-orientationchange") && (type == "orientationchange")){
+ //"orientationchange" not supported <= Android 2.1,
+ //but works through "resize" on window
+ type = "resize";
+ target = window;
+ listener = fixTouchListener(listener);
+ }
+ }
+ if(addStopImmediate){
+ // add stopImmediatePropagation if it doesn't exist
+ listener = addStopImmediate(listener);
+ }
+ // normal path, the target is |this|
+ if(target.addEventListener){
+ // the target has addEventListener, which should be used if available (might or might not be a node, non-nodes can implement this method as well)
+ // check for capture conversions
+ var capture = type in captures,
+ adjustedType = capture ? captures[type] : type;
+ target.addEventListener(adjustedType, listener, capture);
+ // create and return the signal
+ return {
+ remove: function(){
+ target.removeEventListener(adjustedType, listener, capture);
+ }
+ };
+ }
+ type = "on" + type;
+ if(fixAttach && target.attachEvent){
+ return fixAttach(target, type, listener);
+ }
+ throw new Error("Target must be an event emitter");
+ }
+
+ on.selector = function(selector, eventType, children){
+ // summary:
+ // Creates a new extension event with event delegation. This is based on
+ // the provided event type (can be extension event) that
+ // only calls the listener when the CSS selector matches the target of the event.
+ //
+ // The application must require() an appropriate level of dojo/query to handle the selector.
+ // selector:
+ // The CSS selector to use for filter events and determine the |this| of the event listener.
+ // eventType:
+ // The event to listen for
+ // children:
+ // Indicates if children elements of the selector should be allowed. This defaults to
+ // true
+ // example:
+ // | require(["dojo/on", "dojo/mouse", "dojo/query!css2"], function(listen, mouse){
+ // | on(node, on.selector(".my-class", mouse.enter), handlerForMyHover);
+ return function(target, listener){
+ // if the selector is function, use it to select the node, otherwise use the matches method
+ var matchesTarget = typeof selector == "function" ? {matches: selector} : this,
+ bubble = eventType.bubble;
+ function select(eventTarget){
+ // see if we have a valid matchesTarget or default to dojo.query
+ matchesTarget = matchesTarget && matchesTarget.matches ? matchesTarget : dojo.query;
+ // there is a selector, so make sure it matches
+ while(!matchesTarget.matches(eventTarget, selector, target)){
+ if(eventTarget == target || children === false || !(eventTarget = eventTarget.parentNode) || eventTarget.nodeType != 1){ // intentional assignment
+ return;
+ }
+ }
+ return eventTarget;
+ }
+ if(bubble){
+ // the event type doesn't naturally bubble, but has a bubbling form, use that, and give it the selector so it can perform the select itself
+ return on(target, bubble(select), listener);
+ }
+ // standard event delegation
+ return on(target, eventType, function(event){
+ // call select to see if we match
+ var eventTarget = select(event.target);
+ // if it matches we call the listener
+ return eventTarget && listener.call(eventTarget, event);
+ });
+ };
+ };
+
+ function syntheticPreventDefault(){
+ this.cancelable = false;
+ }
+ function syntheticStopPropagation(){
+ this.bubbles = false;
+ }
+ var slice = [].slice,
+ syntheticDispatch = on.emit = function(target, type, event){
+ // summary:
+ // Fires an event on the target object.
+ // target:
+ // The target object to fire the event on. This can be a DOM element or a plain
+ // JS object. If the target is a DOM element, native event emiting mechanisms
+ // are used when possible.
+ // type:
+ // The event type name. You can emulate standard native events like "click" and
+ // "mouseover" or create custom events like "open" or "finish".
+ // event:
+ // An object that provides the properties for the event. See https://developer.mozilla.org/en/DOM/event.initEvent
+ // for some of the properties. These properties are copied to the event object.
+ // Of particular importance are the cancelable and bubbles properties. The
+ // cancelable property indicates whether or not the event has a default action
+ // that can be cancelled. The event is cancelled by calling preventDefault() on
+ // the event object. The bubbles property indicates whether or not the
+ // event will bubble up the DOM tree. If bubbles is true, the event will be called
+ // on the target and then each parent successively until the top of the tree
+ // is reached or stopPropagation() is called. Both bubbles and cancelable
+ // default to false.
+ // returns:
+ // If the event is cancelable and the event is not cancelled,
+ // emit will return true. If the event is cancelable and the event is cancelled,
+ // emit will return false.
+ // details:
+ // Note that this is designed to emit events for listeners registered through
+ // dojo/on. It should actually work with any event listener except those
+ // added through IE's attachEvent (IE8 and below's non-W3C event emiting
+ // doesn't support custom event types). It should work with all events registered
+ // through dojo/on. Also note that the emit method does do any default
+ // action, it only returns a value to indicate if the default action should take
+ // place. For example, emiting a keypress event would not cause a character
+ // to appear in a textbox.
+ // example:
+ // To fire our own click event
+ // | on.emit(dojo.byId("button"), "click", {
+ // | cancelable: true,
+ // | bubbles: true,
+ // | screenX: 33,
+ // | screenY: 44
+ // | });
+ // We can also fire our own custom events:
+ // | on.emit(dojo.byId("slider"), "slide", {
+ // | cancelable: true,
+ // | bubbles: true,
+ // | direction: "left-to-right"
+ // | });
+ var args = slice.call(arguments, 2);
+ var method = "on" + type;
+ if("parentNode" in target){
+ // node (or node-like), create event controller methods
+ var newEvent = args[0] = {};
+ for(var i in event){
+ newEvent[i] = event[i];
+ }
+ newEvent.preventDefault = syntheticPreventDefault;
+ newEvent.stopPropagation = syntheticStopPropagation;
+ newEvent.target = target;
+ newEvent.type = type;
+ event = newEvent;
+ }
+ do{
+ // call any node which has a handler (note that ideally we would try/catch to simulate normal event propagation but that causes too much pain for debugging)
+ target[method] && target[method].apply(target, args);
+ // and then continue up the parent node chain if it is still bubbling (if started as bubbles and stopPropagation hasn't been called)
+ }while(event && event.bubbles && (target = target.parentNode));
+ return event && event.cancelable && event; // if it is still true (was cancelable and was cancelled), return the event to indicate default action should happen
+ };
+ var captures = {};
+ if(!has("event-stopimmediatepropagation")){
+ var stopImmediatePropagation =function(){
+ this.immediatelyStopped = true;
+ this.modified = true; // mark it as modified so the event will be cached in IE
+ };
+ var addStopImmediate = function(listener){
+ return function(event){
+ if(!event.immediatelyStopped){// check to make sure it hasn't been stopped immediately
+ event.stopImmediatePropagation = stopImmediatePropagation;
+ return listener.apply(this, arguments);
+ }
+ };
+ }
+ }
+ if(has("dom-addeventlistener")){
+ // normalize focusin and focusout
+ captures = {
+ focusin: "focus",
+ focusout: "blur"
+ };
+ if(has("opera")){
+ captures.keydown = "keypress"; // this one needs to be transformed because Opera doesn't support repeating keys on keydown (and keypress works because it incorrectly fires on all keydown events)
+ }
+
+ // emiter that works with native event handling
+ on.emit = function(target, type, event){
+ if(target.dispatchEvent && document.createEvent){
+ // use the native event emiting mechanism if it is available on the target object
+ // create a generic event
+ // we could create branch into the different types of event constructors, but
+ // that would be a lot of extra code, with little benefit that I can see, seems
+ // best to use the generic constructor and copy properties over, making it
+ // easy to have events look like the ones created with specific initializers
+ var nativeEvent = target.ownerDocument.createEvent("HTMLEvents");
+ nativeEvent.initEvent(type, !!event.bubbles, !!event.cancelable);
+ // and copy all our properties over
+ for(var i in event){
+ var value = event[i];
+ if(!(i in nativeEvent)){
+ nativeEvent[i] = event[i];
+ }
+ }
+ return target.dispatchEvent(nativeEvent) && nativeEvent;
+ }
+ return syntheticDispatch.apply(on, arguments); // emit for a non-node
+ };
+ }else{
+ // no addEventListener, basically old IE event normalization
+ on._fixEvent = function(evt, sender){
+ // summary:
+ // normalizes properties on the event object including event
+ // bubbling methods, keystroke normalization, and x/y positions
+ // evt:
+ // native event object
+ // sender:
+ // node to treat as "currentTarget"
+ if(!evt){
+ var w = sender && (sender.ownerDocument || sender.document || sender).parentWindow || window;
+ evt = w.event;
+ }
+ if(!evt){return evt;}
+ if(lastEvent && evt.type == lastEvent.type){
+ // should be same event, reuse event object (so it can be augmented)
+ evt = lastEvent;
+ }
+ if(!evt.target){ // check to see if it has been fixed yet
+ evt.target = evt.srcElement;
+ evt.currentTarget = (sender || evt.srcElement);
+ if(evt.type == "mouseover"){
+ evt.relatedTarget = evt.fromElement;
+ }
+ if(evt.type == "mouseout"){
+ evt.relatedTarget = evt.toElement;
+ }
+ if(!evt.stopPropagation){
+ evt.stopPropagation = stopPropagation;
+ evt.preventDefault = preventDefault;
+ }
+ switch(evt.type){
+ case "keypress":
+ var c = ("charCode" in evt ? evt.charCode : evt.keyCode);
+ if (c==10){
+ // CTRL-ENTER is CTRL-ASCII(10) on IE, but CTRL-ENTER on Mozilla
+ c=0;
+ evt.keyCode = 13;
+ }else if(c==13||c==27){
+ c=0; // Mozilla considers ENTER and ESC non-printable
+ }else if(c==3){
+ c=99; // Mozilla maps CTRL-BREAK to CTRL-c
+ }
+ // Mozilla sets keyCode to 0 when there is a charCode
+ // but that stops the event on IE.
+ evt.charCode = c;
+ _setKeyChar(evt);
+ break;
+ }
+ }
+ return evt;
+ };
+ var lastEvent, IESignal = function(handle){
+ this.handle = handle;
+ };
+ IESignal.prototype.remove = function(){
+ delete _dojoIEListeners_[this.handle];
+ };
+ var fixListener = function(listener){
+ // this is a minimal function for closing on the previous listener with as few as variables as possible
+ return function(evt){
+ evt = on._fixEvent(evt, this);
+ var result = listener.call(this, evt);
+ if(evt.modified){
+ // cache the last event and reuse it if we can
+ if(!lastEvent){
+ setTimeout(function(){
+ lastEvent = null;
+ });
+ }
+ lastEvent = evt;
+ }
+ return result;
+ };
+ };
+ var fixAttach = function(target, type, listener){
+ listener = fixListener(listener);
+ if(((target.ownerDocument ? target.ownerDocument.parentWindow : target.parentWindow || target.window || window) != top ||
+ has("jscript") < 5.8) &&
+ !has("config-_allow_leaks")){
+ // IE will leak memory on certain handlers in frames (IE8 and earlier) and in unattached DOM nodes for JScript 5.7 and below.
+ // Here we use global redirection to solve the memory leaks
+ if(typeof _dojoIEListeners_ == "undefined"){
+ _dojoIEListeners_ = [];
+ }
+ var emiter = target[type];
+ if(!emiter || !emiter.listeners){
+ var oldListener = emiter;
+ emiter = Function('event', 'var callee = arguments.callee; for(var i = 0; i 0){
+ // TODO: why do we use a non-standard signature? why do we need "last"?
+ return array.lastIndexOf(a, x, from);
+ }
+ var l = a && a.length || 0, end = up ? l + uOver : lOver, i;
+ if(from === u){
+ i = up ? lOver : l + uOver;
+ }else{
+ if(from < 0){
+ i = l + from;
+ if(i < 0){
+ i = lOver;
+ }
+ }else{
+ i = from >= l ? l + uOver : from;
+ }
+ }
+ if(l && typeof a == "string") a = a.split("");
+ for(; i != end; i += delta){
+ if(a[i] == x){
+ return i; // Number
+ }
+ }
+ return -1; // Number
+ };
+ }
+
+ var array = {
+ // summary:
+ // The Javascript v1.6 array extensions.
+
+ every: everyOrSome(false),
+ /*=====
+ every: function(arr, callback, thisObject){
+ // summary:
+ // Determines whether or not every item in arr satisfies the
+ // condition implemented by callback.
+ // arr: Array|String
+ // the array to iterate on. If a string, operates on individual characters.
+ // callback: Function|String
+ // a function is invoked with three arguments: item, index,
+ // and array and returns true if the condition is met.
+ // thisObject: Object?
+ // may be used to scope the call to callback
+ // returns: Boolean
+ // description:
+ // This function corresponds to the JavaScript 1.6 Array.every() method, with one difference: when
+ // run over sparse arrays, this implementation passes the "holes" in the sparse array to
+ // the callback function with a value of undefined. JavaScript 1.6's every skips the holes in the sparse array.
+ // For more details, see:
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/every
+ // example:
+ // | // returns false
+ // | array.every([1, 2, 3, 4], function(item){ return item>1; });
+ // example:
+ // | // returns true
+ // | array.every([1, 2, 3, 4], function(item){ return item>0; });
+ },
+ =====*/
+
+ some: everyOrSome(true),
+ /*=====
+ some: function(arr, callback, thisObject){
+ // summary:
+ // Determines whether or not any item in arr satisfies the
+ // condition implemented by callback.
+ // arr: Array|String
+ // the array to iterate over. If a string, operates on individual characters.
+ // callback: Function|String
+ // a function is invoked with three arguments: item, index,
+ // and array and returns true if the condition is met.
+ // thisObject: Object?
+ // may be used to scope the call to callback
+ // returns: Boolean
+ // description:
+ // This function corresponds to the JavaScript 1.6 Array.some() method, with one difference: when
+ // run over sparse arrays, this implementation passes the "holes" in the sparse array to
+ // the callback function with a value of undefined. JavaScript 1.6's some skips the holes in the sparse array.
+ // For more details, see:
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/some
+ // example:
+ // | // is true
+ // | array.some([1, 2, 3, 4], function(item){ return item>1; });
+ // example:
+ // | // is false
+ // | array.some([1, 2, 3, 4], function(item){ return item<1; });
+ },
+ =====*/
+
+ indexOf: index(true),
+ /*=====
+ indexOf: function(arr, value, fromIndex, findLast){
+ // summary:
+ // locates the first index of the provided value in the
+ // passed array. If the value is not found, -1 is returned.
+ // description:
+ // This method corresponds to the JavaScript 1.6 Array.indexOf method, with one difference: when
+ // run over sparse arrays, the Dojo function invokes the callback for every index whereas JavaScript
+ // 1.6's indexOf skips the holes in the sparse array.
+ // For details on this method, see:
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/indexOf
+ // arr: Array
+ // value: Object
+ // fromIndex: Integer?
+ // findLast: Boolean?
+ // returns: Number
+ },
+ =====*/
+
+ lastIndexOf: index(false),
+ /*=====
+ lastIndexOf: function(arr, value, fromIndex){
+ // summary:
+ // locates the last index of the provided value in the passed
+ // array. If the value is not found, -1 is returned.
+ // description:
+ // This method corresponds to the JavaScript 1.6 Array.lastIndexOf method, with one difference: when
+ // run over sparse arrays, the Dojo function invokes the callback for every index whereas JavaScript
+ // 1.6's lastIndexOf skips the holes in the sparse array.
+ // For details on this method, see:
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/lastIndexOf
+ // arr: Array,
+ // value: Object,
+ // fromIndex: Integer?
+ // returns: Number
+ },
+ =====*/
+
+ forEach: function(arr, callback, thisObject){
+ // summary:
+ // for every item in arr, callback is invoked. Return values are ignored.
+ // If you want to break out of the loop, consider using array.every() or array.some().
+ // forEach does not allow breaking out of the loop over the items in arr.
+ // arr:
+ // the array to iterate over. If a string, operates on individual characters.
+ // callback:
+ // a function is invoked with three arguments: item, index, and array
+ // thisObject:
+ // may be used to scope the call to callback
+ // description:
+ // This function corresponds to the JavaScript 1.6 Array.forEach() method, with one difference: when
+ // run over sparse arrays, this implementation passes the "holes" in the sparse array to
+ // the callback function with a value of undefined. JavaScript 1.6's forEach skips the holes in the sparse array.
+ // For more details, see:
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/forEach
+ // example:
+ // | // log out all members of the array:
+ // | array.forEach(
+ // | [ "thinger", "blah", "howdy", 10 ],
+ // | function(item){
+ // | console.log(item);
+ // | }
+ // | );
+ // example:
+ // | // log out the members and their indexes
+ // | array.forEach(
+ // | [ "thinger", "blah", "howdy", 10 ],
+ // | function(item, idx, arr){
+ // | console.log(item, "at index:", idx);
+ // | }
+ // | );
+ // example:
+ // | // use a scoped object member as the callback
+ // |
+ // | var obj = {
+ // | prefix: "logged via obj.callback:",
+ // | callback: function(item){
+ // | console.log(this.prefix, item);
+ // | }
+ // | };
+ // |
+ // | // specifying the scope function executes the callback in that scope
+ // | array.forEach(
+ // | [ "thinger", "blah", "howdy", 10 ],
+ // | obj.callback,
+ // | obj
+ // | );
+ // |
+ // | // alternately, we can accomplish the same thing with lang.hitch()
+ // | array.forEach(
+ // | [ "thinger", "blah", "howdy", 10 ],
+ // | lang.hitch(obj, "callback")
+ // | );
+ // arr: Array|String
+ // callback: Function|String
+ // thisObject: Object?
+
+ var i = 0, l = arr && arr.length || 0;
+ if(l && typeof arr == "string") arr = arr.split("");
+ if(typeof callback == "string") callback = cache[callback] || buildFn(callback);
+ if(thisObject){
+ for(; i < l; ++i){
+ callback.call(thisObject, arr[i], i, arr);
+ }
+ }else{
+ for(; i < l; ++i){
+ callback(arr[i], i, arr);
+ }
+ }
+ },
+
+ map: function(arr, callback, thisObject, Ctr){
+ // summary:
+ // applies callback to each element of arr and returns
+ // an Array with the results
+ // arr: Array|String
+ // the array to iterate on. If a string, operates on
+ // individual characters.
+ // callback: Function|String
+ // a function is invoked with three arguments, (item, index,
+ // array), and returns a value
+ // thisObject: Object?
+ // may be used to scope the call to callback
+ // returns: Array
+ // description:
+ // This function corresponds to the JavaScript 1.6 Array.map() method, with one difference: when
+ // run over sparse arrays, this implementation passes the "holes" in the sparse array to
+ // the callback function with a value of undefined. JavaScript 1.6's map skips the holes in the sparse array.
+ // For more details, see:
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
+ // example:
+ // | // returns [2, 3, 4, 5]
+ // | array.map([1, 2, 3, 4], function(item){ return item+1 });
+
+ // TODO: why do we have a non-standard signature here? do we need "Ctr"?
+ var i = 0, l = arr && arr.length || 0, out = new (Ctr || Array)(l);
+ if(l && typeof arr == "string") arr = arr.split("");
+ if(typeof callback == "string") callback = cache[callback] || buildFn(callback);
+ if(thisObject){
+ for(; i < l; ++i){
+ out[i] = callback.call(thisObject, arr[i], i, arr);
+ }
+ }else{
+ for(; i < l; ++i){
+ out[i] = callback(arr[i], i, arr);
+ }
+ }
+ return out; // Array
+ },
+
+ filter: function(arr, callback, thisObject){
+ // summary:
+ // Returns a new Array with those items from arr that match the
+ // condition implemented by callback.
+ // arr: Array
+ // the array to iterate over.
+ // callback: Function|String
+ // a function that is invoked with three arguments (item,
+ // index, array). The return of this function is expected to
+ // be a boolean which determines whether the passed-in item
+ // will be included in the returned array.
+ // thisObject: Object?
+ // may be used to scope the call to callback
+ // returns: Array
+ // description:
+ // This function corresponds to the JavaScript 1.6 Array.filter() method, with one difference: when
+ // run over sparse arrays, this implementation passes the "holes" in the sparse array to
+ // the callback function with a value of undefined. JavaScript 1.6's filter skips the holes in the sparse array.
+ // For more details, see:
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
+ // example:
+ // | // returns [2, 3, 4]
+ // | array.filter([1, 2, 3, 4], function(item){ return item>1; });
+
+ // TODO: do we need "Ctr" here like in map()?
+ var i = 0, l = arr && arr.length || 0, out = [], value;
+ if(l && typeof arr == "string") arr = arr.split("");
+ if(typeof callback == "string") callback = cache[callback] || buildFn(callback);
+ if(thisObject){
+ for(; i < l; ++i){
+ value = arr[i];
+ if(callback.call(thisObject, value, i, arr)){
+ out.push(value);
+ }
+ }
+ }else{
+ for(; i < l; ++i){
+ value = arr[i];
+ if(callback(value, i, arr)){
+ out.push(value);
+ }
+ }
+ }
+ return out; // Array
+ },
+
+ clearCache: function(){
+ cache = {};
+ }
+ };
+
+
+ 1 && lang.mixin(dojo, array);
+
+ return array;
+});
+
+},
+'dojo/_base/json':function(){
+define(["./kernel", "../json"], function(dojo, json){
+
+// module:
+// dojo/_base/json
+
+/*=====
+return {
+ // summary:
+ // This module defines the dojo JSON API.
+};
+=====*/
+
+dojo.fromJson = function(/*String*/ js){
+ // summary:
+ // Parses a JavaScript expression and returns a JavaScript value.
+ // description:
+ // Throws for invalid JavaScript expressions. It does not use a strict JSON parser. It
+ // always delegates to eval(). The content passed to this method must therefore come
+ // from a trusted source.
+ // It is recommend that you use dojo/json's parse function for an
+ // implementation uses the (faster) native JSON parse when available.
+ // js:
+ // a string literal of a JavaScript expression, for instance:
+ // `'{ "foo": [ "bar", 1, { "baz": "thud" } ] }'`
+
+ return eval("(" + js + ")"); // Object
+};
+
+/*=====
+dojo._escapeString = function(){
+ // summary:
+ // Adds escape sequences for non-visual characters, double quote and
+ // backslash and surrounds with double quotes to form a valid string
+ // literal.
+};
+=====*/
+dojo._escapeString = json.stringify; // just delegate to json.stringify
+
+dojo.toJsonIndentStr = "\t";
+dojo.toJson = function(/*Object*/ it, /*Boolean?*/ prettyPrint){
+ // summary:
+ // Returns a [JSON](http://json.org) serialization of an object.
+ // description:
+ // Returns a [JSON](http://json.org) serialization of an object.
+ // Note that this doesn't check for infinite recursion, so don't do that!
+ // It is recommend that you use dojo/json's stringify function for an lighter
+ // and faster implementation that matches the native JSON API and uses the
+ // native JSON serializer when available.
+ // it:
+ // an object to be serialized. Objects may define their own
+ // serialization via a special "__json__" or "json" function
+ // property. If a specialized serializer has been defined, it will
+ // be used as a fallback.
+ // Note that in 1.6, toJson would serialize undefined, but this no longer supported
+ // since it is not supported by native JSON serializer.
+ // prettyPrint:
+ // if true, we indent objects and arrays to make the output prettier.
+ // The variable `dojo.toJsonIndentStr` is used as the indent string --
+ // to use something other than the default (tab), change that variable
+ // before calling dojo.toJson().
+ // Note that if native JSON support is available, it will be used for serialization,
+ // and native implementations vary on the exact spacing used in pretty printing.
+ // returns:
+ // A JSON string serialization of the passed-in object.
+ // example:
+ // simple serialization of a trivial object
+ // | var jsonStr = dojo.toJson({ howdy: "stranger!", isStrange: true });
+ // | doh.is('{"howdy":"stranger!","isStrange":true}', jsonStr);
+ // example:
+ // a custom serializer for an objects of a particular class:
+ // | dojo.declare("Furby", null, {
+ // | furbies: "are strange",
+ // | furbyCount: 10,
+ // | __json__: function(){
+ // | },
+ // | });
+
+ // use dojo/json
+ return json.stringify(it, function(key, value){
+ if(value){
+ var tf = value.__json__||value.json;
+ if(typeof tf == "function"){
+ return tf.call(value);
+ }
+ }
+ return value;
+ }, prettyPrint && dojo.toJsonIndentStr); // String
+};
+
+return dojo;
+});
+
+},
+'dojo/_base/window':function(){
+define("dojo/_base/window", ["./kernel", "./lang", "../sniff"], function(dojo, lang, has){
+// module:
+// dojo/_base/window
+
+var ret = {
+ // summary:
+ // API to save/set/restore the global/document scope.
+
+ global: dojo.global,
+ /*=====
+ global: {
+ // summary:
+ // Alias for the current window. 'global' can be modified
+ // for temporary context shifting. See also withGlobal().
+ // description:
+ // Use this rather than referring to 'window' to ensure your code runs
+ // correctly in managed contexts.
+ },
+ =====*/
+
+ doc: this["document"] || null,
+ /*=====
+ doc: {
+ // summary:
+ // Alias for the current document. 'doc' can be modified
+ // for temporary context shifting. See also withDoc().
+ // description:
+ // Use this rather than referring to 'window.document' to ensure your code runs
+ // correctly in managed contexts.
+ // example:
+ // | n.appendChild(dojo.doc.createElement('div'));
+ },
+ =====*/
+
+ body: function(/*Document?*/ doc){
+ // summary:
+ // Return the body element of the specified document or of dojo/_base/window::doc.
+ // example:
+ // | win.body().appendChild(dojo.doc.createElement('div'));
+
+ // Note: document.body is not defined for a strict xhtml document
+ // Would like to memoize this, but dojo.doc can change vi dojo.withDoc().
+ doc = doc || dojo.doc;
+ return doc.body || doc.getElementsByTagName("body")[0]; // Node
+ },
+
+ setContext: function(/*Object*/ globalObject, /*DocumentElement*/ globalDocument){
+ // summary:
+ // changes the behavior of many core Dojo functions that deal with
+ // namespace and DOM lookup, changing them to work in a new global
+ // context (e.g., an iframe). The varibles dojo.global and dojo.doc
+ // are modified as a result of calling this function and the result of
+ // `dojo.body()` likewise differs.
+ dojo.global = ret.global = globalObject;
+ dojo.doc = ret.doc = globalDocument;
+ },
+
+ withGlobal: function( /*Object*/ globalObject,
+ /*Function*/ callback,
+ /*Object?*/ thisObject,
+ /*Array?*/ cbArguments){
+ // summary:
+ // Invoke callback with globalObject as dojo.global and
+ // globalObject.document as dojo.doc.
+ // description:
+ // Invoke callback with globalObject as dojo.global and
+ // globalObject.document as dojo.doc. If provided, globalObject
+ // will be executed in the context of object thisObject
+ // When callback() returns or throws an error, the dojo.global
+ // and dojo.doc will be restored to its previous state.
+
+ var oldGlob = dojo.global;
+ try{
+ dojo.global = ret.global = globalObject;
+ return ret.withDoc.call(null, globalObject.document, callback, thisObject, cbArguments);
+ }finally{
+ dojo.global = ret.global = oldGlob;
+ }
+ },
+
+ withDoc: function( /*DocumentElement*/ documentObject,
+ /*Function*/ callback,
+ /*Object?*/ thisObject,
+ /*Array?*/ cbArguments){
+ // summary:
+ // Invoke callback with documentObject as dojo/_base/window::doc.
+ // description:
+ // Invoke callback with documentObject as dojo/_base/window::doc. If provided,
+ // callback will be executed in the context of object thisObject
+ // When callback() returns or throws an error, the dojo/_base/window::doc will
+ // be restored to its previous state.
+
+ var oldDoc = ret.doc,
+ oldQ = has("quirks"),
+ oldIE = has("ie"), isIE, mode, pwin;
+
+ try{
+ dojo.doc = ret.doc = documentObject;
+ // update dojo.isQuirks and the value of the has feature "quirks".
+ // remove setting dojo.isQuirks and dojo.isIE for 2.0
+ dojo.isQuirks = has.add("quirks", dojo.doc.compatMode == "BackCompat", true, true); // no need to check for QuirksMode which was Opera 7 only
+
+ if(has("ie")){
+ if((pwin = documentObject.parentWindow) && pwin.navigator){
+ // re-run IE detection logic and update dojo.isIE / has("ie")
+ // (the only time parentWindow/navigator wouldn't exist is if we were not
+ // passed an actual legitimate document object)
+ isIE = parseFloat(pwin.navigator.appVersion.split("MSIE ")[1]) || undefined;
+ mode = documentObject.documentMode;
+ if(mode && mode != 5 && Math.floor(isIE) != mode){
+ isIE = mode;
+ }
+ dojo.isIE = has.add("ie", isIE, true, true);
+ }
+ }
+
+ if(thisObject && typeof callback == "string"){
+ callback = thisObject[callback];
+ }
+
+ return callback.apply(thisObject, cbArguments || []);
+ }finally{
+ dojo.doc = ret.doc = oldDoc;
+ dojo.isQuirks = has.add("quirks", oldQ, true, true);
+ dojo.isIE = has.add("ie", oldIE, true, true);
+ }
+ }
+};
+
+ 1 && lang.mixin(dojo, ret);
+
+return ret;
+
+});
+
+},
+'dojo/dom-class':function(){
+define(["./_base/lang", "./_base/array", "./dom"], function(lang, array, dom){
+ // module:
+ // dojo/dom-class
+
+ var className = "className";
+
+ /* Part I of classList-based implementation is preserved here for posterity
+ var classList = "classList";
+ has.add("dom-classList", function(){
+ return classList in document.createElement("p");
+ });
+ */
+
+ // =============================
+ // (CSS) Class Functions
+ // =============================
+
+ var cls, // exports object
+ spaces = /\s+/, a1 = [""];
+
+ function str2array(s){
+ if(typeof s == "string" || s instanceof String){
+ if(s && !spaces.test(s)){
+ a1[0] = s;
+ return a1;
+ }
+ var a = s.split(spaces);
+ if(a.length && !a[0]){
+ a.shift();
+ }
+ if(a.length && !a[a.length - 1]){
+ a.pop();
+ }
+ return a;
+ }
+ // assumed to be an array
+ if(!s){
+ return [];
+ }
+ return array.filter(s, function(x){ return x; });
+ }
+
+ /* Part II of classList-based implementation is preserved here for posterity
+ if(has("dom-classList")){
+ // new classList version
+ cls = {
+ contains: function containsClass(node, classStr){
+ var clslst = classStr && dom.byId(node)[classList];
+ return clslst && clslst.contains(classStr); // Boolean
+ },
+
+ add: function addClass(node, classStr){
+ node = dom.byId(node);
+ classStr = str2array(classStr);
+ for(var i = 0, len = classStr.length; i < len; ++i){
+ node[classList].add(classStr[i]);
+ }
+ },
+
+ remove: function removeClass(node, classStr){
+ node = dom.byId(node);
+ if(classStr === undefined){
+ node[className] = "";
+ }else{
+ classStr = str2array(classStr);
+ for(var i = 0, len = classStr.length; i < len; ++i){
+ node[classList].remove(classStr[i]);
+ }
+ }
+ },
+
+ replace: function replaceClass(node, addClassStr, removeClassStr){
+ node = dom.byId(node);
+ if(removeClassStr === undefined){
+ node[className] = "";
+ }else{
+ removeClassStr = str2array(removeClassStr);
+ for(var i = 0, len = removeClassStr.length; i < len; ++i){
+ node[classList].remove(removeClassStr[i]);
+ }
+ }
+ addClassStr = str2array(addClassStr);
+ for(i = 0, len = addClassStr.length; i < len; ++i){
+ node[classList].add(addClassStr[i]);
+ }
+ },
+
+ toggle: function toggleClass(node, classStr, condition){
+ node = dom.byId(node);
+ if(condition === undefined){
+ classStr = str2array(classStr);
+ for(var i = 0, len = classStr.length; i < len; ++i){
+ node[classList].toggle(classStr[i]);
+ }
+ }else{
+ cls[condition ? "add" : "remove"](node, classStr);
+ }
+ return condition; // Boolean
+ }
+ }
+ }
+ */
+
+ // regular DOM version
+ var fakeNode = {}; // for effective replacement
+ cls = {
+ // summary:
+ // This module defines the core dojo DOM class API.
+
+ contains: function containsClass(/*DomNode|String*/ node, /*String*/ classStr){
+ // summary:
+ // Returns whether or not the specified classes are a portion of the
+ // class list currently applied to the node.
+ // node: String|DOMNode
+ // String ID or DomNode reference to check the class for.
+ // classStr: String
+ // A string class name to look for.
+ // example:
+ // Do something if a node with id="someNode" has class="aSillyClassName" present
+ // | if(dojo.hasClass("someNode","aSillyClassName")){ ... }
+
+ return ((" " + dom.byId(node)[className] + " ").indexOf(" " + classStr + " ") >= 0); // Boolean
+ },
+
+ add: function addClass(/*DomNode|String*/ node, /*String|Array*/ classStr){
+ // summary:
+ // Adds the specified classes to the end of the class list on the
+ // passed node. Will not re-apply duplicate classes.
+ //
+ // node: String|DOMNode
+ // String ID or DomNode reference to add a class string too
+ //
+ // classStr: String|Array
+ // A String class name to add, or several space-separated class names,
+ // or an array of class names.
+ //
+ // example:
+ // Add a class to some node:
+ // | require(["dojo/dom-class"], function(domClass){
+ // | domClass.add("someNode", "anewClass");
+ // | });
+ //
+ // example:
+ // Add two classes at once:
+ // | require(["dojo/dom-class"], function(domClass){
+ // | domClass.add("someNode", "firstClass secondClass");
+ // | });
+ //
+ // example:
+ // Add two classes at once (using array):
+ // | require(["dojo/dom-class"], function(domClass){
+ // | domClass.add("someNode", ["firstClass", "secondClass"]);
+ // | });
+ //
+ // example:
+ // Available in `dojo/NodeList` for multiple additions
+ // | require(["dojo/query"], function(query){
+ // | query("ul > li").addClass("firstLevel");
+ // | });
+
+ node = dom.byId(node);
+ classStr = str2array(classStr);
+ var cls = node[className], oldLen;
+ cls = cls ? " " + cls + " " : " ";
+ oldLen = cls.length;
+ for(var i = 0, len = classStr.length, c; i < len; ++i){
+ c = classStr[i];
+ if(c && cls.indexOf(" " + c + " ") < 0){
+ cls += c + " ";
+ }
+ }
+ if(oldLen < cls.length){
+ node[className] = cls.substr(1, cls.length - 2);
+ }
+ },
+
+ remove: function removeClass(/*DomNode|String*/ node, /*String|Array?*/ classStr){
+ // summary:
+ // Removes the specified classes from node. No `contains()`
+ // check is required.
+ //
+ // node: String|DOMNode
+ // String ID or DomNode reference to remove the class from.
+ //
+ // classStr: String|Array
+ // An optional String class name to remove, or several space-separated
+ // class names, or an array of class names. If omitted, all class names
+ // will be deleted.
+ //
+ // example:
+ // Remove a class from some node:
+ // | require(["dojo/dom-class"], function(domClass){
+ // | domClass.remove("someNode", "firstClass");
+ // | });
+ //
+ // example:
+ // Remove two classes from some node:
+ // | require(["dojo/dom-class"], function(domClass){
+ // | domClass.remove("someNode", "firstClass secondClass");
+ // | });
+ //
+ // example:
+ // Remove two classes from some node (using array):
+ // | require(["dojo/dom-class"], function(domClass){
+ // | domClass.remove("someNode", ["firstClass", "secondClass"]);
+ // | });
+ //
+ // example:
+ // Remove all classes from some node:
+ // | require(["dojo/dom-class"], function(domClass){
+ // | domClass.remove("someNode");
+ // | });
+ //
+ // example:
+ // Available in `dojo/NodeList` for multiple removal
+ // | require(["dojo/query"], function(query){
+ // | query("ul > li").removeClass("foo");
+ // | });
+
+ node = dom.byId(node);
+ var cls;
+ if(classStr !== undefined){
+ classStr = str2array(classStr);
+ cls = " " + node[className] + " ";
+ for(var i = 0, len = classStr.length; i < len; ++i){
+ cls = cls.replace(" " + classStr[i] + " ", " ");
+ }
+ cls = lang.trim(cls);
+ }else{
+ cls = "";
+ }
+ if(node[className] != cls){ node[className] = cls; }
+ },
+
+ replace: function replaceClass(/*DomNode|String*/ node, /*String|Array*/ addClassStr, /*String|Array?*/ removeClassStr){
+ // summary:
+ // Replaces one or more classes on a node if not present.
+ // Operates more quickly than calling dojo.removeClass and dojo.addClass
+ //
+ // node: String|DOMNode
+ // String ID or DomNode reference to remove the class from.
+ //
+ // addClassStr: String|Array
+ // A String class name to add, or several space-separated class names,
+ // or an array of class names.
+ //
+ // removeClassStr: String|Array?
+ // A String class name to remove, or several space-separated class names,
+ // or an array of class names.
+ //
+ // example:
+ // | require(["dojo/dom-class"], function(domClass){
+ // | domClass.replace("someNode", "add1 add2", "remove1 remove2");
+ // | });
+ //
+ // example:
+ // Replace all classes with addMe
+ // | require(["dojo/dom-class"], function(domClass){
+ // | domClass.replace("someNode", "addMe");
+ // | });
+ //
+ // example:
+ // Available in `dojo/NodeList` for multiple toggles
+ // | require(["dojo/query"], function(query){
+ // | query(".findMe").replaceClass("addMe", "removeMe");
+ // | });
+
+ node = dom.byId(node);
+ fakeNode[className] = node[className];
+ cls.remove(fakeNode, removeClassStr);
+ cls.add(fakeNode, addClassStr);
+ if(node[className] !== fakeNode[className]){
+ node[className] = fakeNode[className];
+ }
+ },
+
+ toggle: function toggleClass(/*DomNode|String*/ node, /*String|Array*/ classStr, /*Boolean?*/ condition){
+ // summary:
+ // Adds a class to node if not present, or removes if present.
+ // Pass a boolean condition if you want to explicitly add or remove.
+ // Returns the condition that was specified directly or indirectly.
+ //
+ // node: String|DOMNode
+ // String ID or DomNode reference to toggle a class string
+ //
+ // classStr: String|Array
+ // A String class name to toggle, or several space-separated class names,
+ // or an array of class names.
+ //
+ // condition:
+ // If passed, true means to add the class, false means to remove.
+ // Otherwise dojo.hasClass(node, classStr) is used to detect the class presence.
+ //
+ // example:
+ // | require(["dojo/dom-class"], function(domClass){
+ // | domClass.toggle("someNode", "hovered");
+ // | });
+ //
+ // example:
+ // Forcefully add a class
+ // | require(["dojo/dom-class"], function(domClass){
+ // | domClass.toggle("someNode", "hovered", true);
+ // | });
+ //
+ // example:
+ // Available in `dojo/NodeList` for multiple toggles
+ // | require(["dojo/query"], function(query){
+ // | query(".toggleMe").toggleClass("toggleMe");
+ // | });
+
+ node = dom.byId(node);
+ if(condition === undefined){
+ classStr = str2array(classStr);
+ for(var i = 0, len = classStr.length, c; i < len; ++i){
+ c = classStr[i];
+ cls[cls.contains(node, c) ? "remove" : "add"](node, c);
+ }
+ }else{
+ cls[condition ? "add" : "remove"](node, classStr);
+ }
+ return condition; // Boolean
+ }
+ };
+
+ return cls;
+});
+
+},
+'dojo/_base/config':function(){
+define(["../has", "require"], function(has, require){
+ // module:
+ // dojo/_base/config
+
+/*=====
+return {
+ // summary:
+ // This module defines the user configuration during bootstrap.
+ // description:
+ // By defining user configuration as a module value, an entire configuration can be specified in a build,
+ // thereby eliminating the need for sniffing and or explicitly setting in the global variable dojoConfig.
+ // Also, when multiple instances of dojo exist in a single application, each will necessarily be located
+ // at an unique absolute module identifier as given by the package configuration. Implementing configuration
+ // as a module allows for specifying unique, per-instance configurations.
+ // example:
+ // Create a second instance of dojo with a different, instance-unique configuration (assume the loader and
+ // dojo.js are already loaded).
+ // | // specify a configuration that creates a new instance of dojo at the absolute module identifier "myDojo"
+ // | require({
+ // | packages:[{
+ // | name:"myDojo",
+ // | location:".", //assume baseUrl points to dojo.js
+ // | }]
+ // | });
+ // |
+ // | // specify a configuration for the myDojo instance
+ // | define("myDojo/config", {
+ // | // normal configuration variables go here, e.g.,
+ // | locale:"fr-ca"
+ // | });
+ // |
+ // | // load and use the new instance of dojo
+ // | require(["myDojo"], function(dojo){
+ // | // dojo is the new instance of dojo
+ // | // use as required
+ // | });
+
+ // isDebug: Boolean
+ // Defaults to `false`. If set to `true`, ensures that Dojo provides
+ // extended debugging feedback via Firebug. If Firebug is not available
+ // on your platform, setting `isDebug` to `true` will force Dojo to
+ // pull in (and display) the version of Firebug Lite which is
+ // integrated into the Dojo distribution, thereby always providing a
+ // debugging/logging console when `isDebug` is enabled. Note that
+ // Firebug's `console.*` methods are ALWAYS defined by Dojo. If
+ // `isDebug` is false and you are on a platform without Firebug, these
+ // methods will be defined as no-ops.
+ isDebug: false,
+
+ // locale: String
+ // The locale to assume for loading localized resources in this page,
+ // specified according to [RFC 3066](http://www.ietf.org/rfc/rfc3066.txt).
+ // Must be specified entirely in lowercase, e.g. `en-us` and `zh-cn`.
+ // See the documentation for `dojo.i18n` and `dojo.requireLocalization`
+ // for details on loading localized resources. If no locale is specified,
+ // Dojo assumes the locale of the user agent, according to `navigator.userLanguage`
+ // or `navigator.language` properties.
+ locale: undefined,
+
+ // extraLocale: Array
+ // No default value. Specifies additional locales whose
+ // resources should also be loaded alongside the default locale when
+ // calls to `dojo.requireLocalization()` are processed.
+ extraLocale: undefined,
+
+ // baseUrl: String
+ // The directory in which `dojo.js` is located. Under normal
+ // conditions, Dojo auto-detects the correct location from which it
+ // was loaded. You may need to manually configure `baseUrl` in cases
+ // where you have renamed `dojo.js` or in which ` ` tags confuse
+ // some browsers (e.g. IE 6). The variable `dojo.baseUrl` is assigned
+ // either the value of `djConfig.baseUrl` if one is provided or the
+ // auto-detected root if not. Other modules are located relative to
+ // this path. The path should end in a slash.
+ baseUrl: undefined,
+
+ // modulePaths: [deprecated] Object
+ // A map of module names to paths relative to `dojo.baseUrl`. The
+ // key/value pairs correspond directly to the arguments which
+ // `dojo.registerModulePath` accepts. Specifying
+ // `djConfig.modulePaths = { "foo": "../../bar" }` is the equivalent
+ // of calling `dojo.registerModulePath("foo", "../../bar");`. Multiple
+ // modules may be configured via `djConfig.modulePaths`.
+ modulePaths: {},
+
+ // addOnLoad: Function|Array
+ // Adds a callback via dojo/ready. Useful when Dojo is added after
+ // the page loads and djConfig.afterOnLoad is true. Supports the same
+ // arguments as dojo/ready. When using a function reference, use
+ // `djConfig.addOnLoad = function(){};`. For object with function name use
+ // `djConfig.addOnLoad = [myObject, "functionName"];` and for object with
+ // function reference use
+ // `djConfig.addOnLoad = [myObject, function(){}];`
+ addOnLoad: null,
+
+ // parseOnLoad: Boolean
+ // Run the parser after the page is loaded
+ parseOnLoad: false,
+
+ // require: String[]
+ // An array of module names to be loaded immediately after dojo.js has been included
+ // in a page.
+ require: [],
+
+ // defaultDuration: Number
+ // Default duration, in milliseconds, for wipe and fade animations within dijits.
+ // Assigned to dijit.defaultDuration.
+ defaultDuration: 200,
+
+ // dojoBlankHtmlUrl: String
+ // Used by some modules to configure an empty iframe. Used by dojo/io/iframe and
+ // dojo/back, and dijit/popup support in IE where an iframe is needed to make sure native
+ // controls do not bleed through the popups. Normally this configuration variable
+ // does not need to be set, except when using cross-domain/CDN Dojo builds.
+ // Save dojo/resources/blank.html to your domain and set `djConfig.dojoBlankHtmlUrl`
+ // to the path on your domain your copy of blank.html.
+ dojoBlankHtmlUrl: undefined,
+
+ // ioPublish: Boolean?
+ // Set this to true to enable publishing of topics for the different phases of
+ // IO operations. Publishing is done via dojo/topic.publish(). See dojo/main.__IoPublish for a list
+ // of topics that are published.
+ ioPublish: false,
+
+ // useCustomLogger: Anything?
+ // If set to a value that evaluates to true such as a string or array and
+ // isDebug is true and Firebug is not available or running, then it bypasses
+ // the creation of Firebug Lite allowing you to define your own console object.
+ useCustomLogger: undefined,
+
+ // transparentColor: Array
+ // Array containing the r, g, b components used as transparent color in dojo.Color;
+ // if undefined, [255,255,255] (white) will be used.
+ transparentColor: undefined,
+
+ // deps: Function|Array
+ // Defines dependencies to be used before the loader has been loaded.
+ // When provided, they cause the loader to execute require(deps, callback)
+ // once it has finished loading. Should be used with callback.
+ deps: undefined,
+
+ // callback: Function|Array
+ // Defines a callback to be used when dependencies are defined before
+ // the loader has been loaded. When provided, they cause the loader to
+ // execute require(deps, callback) once it has finished loading.
+ // Should be used with deps.
+ callback: undefined,
+
+ // deferredInstrumentation: Boolean
+ // Whether deferred instrumentation should be loaded or included
+ // in builds.
+ deferredInstrumentation: true,
+
+ // useDeferredInstrumentation: Boolean|String
+ // Whether the deferred instrumentation should be used.
+ //
+ // * `"report-rejections"`: report each rejection as it occurs.
+ // * `true` or `1` or `"report-unhandled-rejections"`: wait 1 second
+ // in an attempt to detect unhandled rejections.
+ useDeferredInstrumentation: "report-unhandled-rejections"
+};
+=====*/
+
+ var result = {};
+ if( 1 ){
+ // must be the dojo loader; take a shallow copy of require.rawConfig
+ var src = require.rawConfig, p;
+ for(p in src){
+ result[p] = src[p];
+ }
+ }else{
+ var adviseHas = function(featureSet, prefix, booting){
+ for(p in featureSet){
+ p!="has" && has.add(prefix + p, featureSet[p], 0, booting);
+ }
+ };
+ result = 1 ?
+ // must be a built version of the dojo loader; all config stuffed in require.rawConfig
+ require.rawConfig :
+ // a foreign loader
+ this.dojoConfig || this.djConfig || {};
+ adviseHas(result, "config", 1);
+ adviseHas(result.has, "", 1);
+ }
+ return result;
+});
+
+
+},
+'dojo/main':function(){
+define([
+ "./_base/kernel", // kernel.isAsync
+ "./has",
+ "require",
+ "./sniff",
+ "./_base/lang",
+ "./_base/array",
+ "./_base/config",
+ "./ready",
+ "./_base/declare",
+ "./_base/connect",
+ "./_base/Deferred",
+ "./_base/json",
+ "./_base/Color",
+ "./has!dojo-firebug?./_firebug/firebug",
+ "./_base/browser",
+ "./_base/loader"
+], function(kernel, has, require, sniff, lang, array, config, ready){
+ // module:
+ // dojo/main
+ // summary:
+ // This is the package main module for the dojo package; it loads dojo base appropriate for the execution environment.
+
+ // the preferred way to load the dojo firebug console is by setting has("dojo-firebug") true in dojoConfig
+ // the isDebug config switch is for backcompat and will work fine in sync loading mode; it works in
+ // async mode too, but there's no guarantee when the module is loaded; therefore, if you need a firebug
+ // console guaranteed at a particular spot in an app, either set config.has["dojo-firebug"] true before
+ // loading dojo.js or explicitly include dojo/_firebug/firebug in a dependency list.
+ if(config.isDebug){
+ require(["./_firebug/firebug"]);
+ }
+
+ // dojoConfig.require is deprecated; use the loader configuration property deps
+ 1 || has.add("dojo-config-require", 1);
+ if( 1 ){
+ var deps= config.require;
+ if(deps){
+ // config.require may be dot notation
+ deps= array.map(lang.isArray(deps) ? deps : [deps], function(item){ return item.replace(/\./g, "/"); });
+ if(kernel.isAsync){
+ require(deps);
+ }else{
+ // this is a bit janky; in 1.6- dojo is defined before these requires are applied; but in 1.7+
+ // dojo isn't defined until returning from this module; this is only a problem in sync mode
+ // since we're in sync mode, we know we've got our loader with its priority ready queue
+ ready(1, function(){require(deps);});
+ }
+ }
+ }
+
+ return kernel;
+});
+
+},
+'dojo/_base/event':function(){
+define("dojo/_base/event", ["./kernel", "../on", "../has", "../dom-geometry"], function(dojo, on, has, dom){
+ // module:
+ // dojo/_base/event
+
+ if(on._fixEvent){
+ var fixEvent = on._fixEvent;
+ on._fixEvent = function(evt, se){
+ // add some additional normalization for back-compat, this isn't in on.js because it is somewhat more expensive
+ evt = fixEvent(evt, se);
+ if(evt){
+ dom.normalizeEvent(evt);
+ }
+ return evt;
+ };
+ }
+
+ var ret = {
+ // summary:
+ // This module defines dojo DOM event API. Usually you should use dojo/on, and evt.stopPropagation() +
+ // evt.preventDefault(), rather than this module.
+
+ fix: function(/*Event*/ evt, /*DOMNode*/ sender){
+ // summary:
+ // normalizes properties on the event object including event
+ // bubbling methods, keystroke normalization, and x/y positions
+ // evt: Event
+ // native event object
+ // sender: DOMNode
+ // node to treat as "currentTarget"
+ if(on._fixEvent){
+ return on._fixEvent(evt, sender);
+ }
+ return evt; // Event
+ },
+
+ stop: function(/*Event*/ evt){
+ // summary:
+ // prevents propagation and clobbers the default action of the
+ // passed event
+ // evt: Event
+ // The event object. If omitted, window.event is used on IE.
+ if(has("dom-addeventlistener") || (evt && evt.preventDefault)){
+ evt.preventDefault();
+ evt.stopPropagation();
+ }else{
+ evt = evt || window.event;
+ evt.cancelBubble = true;
+ on._preventDefault.call(evt);
+ }
+ }
+ };
+
+ if( 1 ){
+ dojo.fixEvent = ret.fix;
+ dojo.stopEvent = ret.stop;
+ }
+
+ return ret;
+});
+
+},
+'dojo/sniff':function(){
+define(["./has"], function(has){
+ // module:
+ // dojo/sniff
+
+ /*=====
+ return function(){
+ // summary:
+ // This module sets has() flags based on the current browser.
+ // It returns the has() function.
+ };
+ =====*/
+
+ if( 1 ){
+ var n = navigator,
+ dua = n.userAgent,
+ dav = n.appVersion,
+ tv = parseFloat(dav);
+
+ has.add("air", dua.indexOf("AdobeAIR") >= 0),
+ has.add("khtml", dav.indexOf("Konqueror") >= 0 ? tv : undefined);
+ has.add("webkit", parseFloat(dua.split("WebKit/")[1]) || undefined);
+ has.add("chrome", parseFloat(dua.split("Chrome/")[1]) || undefined);
+ has.add("safari", dav.indexOf("Safari")>=0 && !has("chrome") ? parseFloat(dav.split("Version/")[1]) : undefined);
+ has.add("mac", dav.indexOf("Macintosh") >= 0);
+ has.add("quirks", document.compatMode == "BackCompat");
+ has.add("ios", /iPhone|iPod|iPad/.test(dua));
+ has.add("android", parseFloat(dua.split("Android ")[1]) || undefined);
+
+ if(!has("webkit")){
+ // Opera
+ if(dua.indexOf("Opera") >= 0){
+ // see http://dev.opera.com/articles/view/opera-ua-string-changes and http://www.useragentstring.com/pages/Opera/
+ // 9.8 has both styles; <9.8, 9.9 only old style
+ has.add("opera", tv >= 9.8 ? parseFloat(dua.split("Version/")[1]) || tv : tv);
+ }
+
+ // Mozilla and firefox
+ if(dua.indexOf("Gecko") >= 0 && !has("khtml") && !has("webkit")){
+ has.add("mozilla", tv);
+ }
+ if(has("mozilla")){
+ //We really need to get away from this. Consider a sane isGecko approach for the future.
+ has.add("ff", parseFloat(dua.split("Firefox/")[1] || dua.split("Minefield/")[1]) || undefined);
+ }
+
+ // IE
+ if(document.all && !has("opera")){
+ var isIE = parseFloat(dav.split("MSIE ")[1]) || undefined;
+
+ //In cases where the page has an HTTP header or META tag with
+ //X-UA-Compatible, then it is in emulation mode.
+ //Make sure isIE reflects the desired version.
+ //document.documentMode of 5 means quirks mode.
+ //Only switch the value if documentMode's major version
+ //is different from isIE's major version.
+ var mode = document.documentMode;
+ if(mode && mode != 5 && Math.floor(isIE) != mode){
+ isIE = mode;
+ }
+
+ has.add("ie", isIE);
+ }
+
+ // Wii
+ has.add("wii", typeof opera != "undefined" && opera.wiiremote);
+ }
+ }
+
+ return has;
+});
+
+},
+'dojo/request/handlers':function(){
+define([
+ '../json',
+ '../_base/kernel',
+ '../_base/array',
+ '../has'
+], function(JSON, kernel, array, has){
+ has.add('activex', typeof ActiveXObject !== 'undefined');
+
+ var handleXML;
+ if(has('activex')){
+ // GUIDs obtained from http://msdn.microsoft.com/en-us/library/ms757837(VS.85).aspx
+ var dp = [
+ 'Msxml2.DOMDocument.6.0',
+ 'Msxml2.DOMDocument.4.0',
+ 'MSXML2.DOMDocument.3.0',
+ 'MSXML.DOMDocument' // 2.0
+ ];
+
+ handleXML = function(response){
+ var result = response.data;
+
+ if(!result || !result.documentElement){
+ var text = response.text;
+ array.some(dp, function(p){
+ try{
+ var dom = new ActiveXObject(p);
+ dom.async = false;
+ dom.loadXML(text);
+ result = dom;
+ }catch(e){ return false; }
+ return true;
+ });
+ }
+
+ return result;
+ };
+ }
+
+ var handlers = {
+ 'javascript': function(response){
+ return kernel.eval(response.text || '');
+ },
+ 'json': function(response){
+ return JSON.parse(response.text || null);
+ },
+ 'xml': handleXML
+ };
+
+ function handle(response){
+ var handler = handlers[response.options.handleAs];
+
+ response.data = handler ? handler(response) : (response.data || response.text);
+
+ return response;
+ }
+
+ handle.register = function(name, handler){
+ handlers[name] = handler;
+ };
+
+ return handle;
+});
+
+},
+'dojo/aspect':function(){
+define("dojo/aspect", [], function(){
+
+ // module:
+ // dojo/aspect
+
+ "use strict";
+ var undefined, nextId = 0;
+ function advise(dispatcher, type, advice, receiveArguments){
+ var previous = dispatcher[type];
+ var around = type == "around";
+ var signal;
+ if(around){
+ var advised = advice(function(){
+ return previous.advice(this, arguments);
+ });
+ signal = {
+ remove: function(){
+ signal.cancelled = true;
+ },
+ advice: function(target, args){
+ return signal.cancelled ?
+ previous.advice(target, args) : // cancelled, skip to next one
+ advised.apply(target, args); // called the advised function
+ }
+ };
+ }else{
+ // create the remove handler
+ signal = {
+ remove: function(){
+ var previous = signal.previous;
+ var next = signal.next;
+ if(!next && !previous){
+ delete dispatcher[type];
+ }else{
+ if(previous){
+ previous.next = next;
+ }else{
+ dispatcher[type] = next;
+ }
+ if(next){
+ next.previous = previous;
+ }
+ }
+ },
+ id: nextId++,
+ advice: advice,
+ receiveArguments: receiveArguments
+ };
+ }
+ if(previous && !around){
+ if(type == "after"){
+ // add the listener to the end of the list
+ var next = previous;
+ while(next){
+ previous = next;
+ next = next.next;
+ }
+ previous.next = signal;
+ signal.previous = previous;
+ }else if(type == "before"){
+ // add to beginning
+ dispatcher[type] = signal;
+ signal.next = previous;
+ previous.previous = signal;
+ }
+ }else{
+ // around or first one just replaces
+ dispatcher[type] = signal;
+ }
+ return signal;
+ }
+ function aspect(type){
+ return function(target, methodName, advice, receiveArguments){
+ var existing = target[methodName], dispatcher;
+ if(!existing || existing.target != target){
+ // no dispatcher in place
+ target[methodName] = dispatcher = function(){
+ var executionId = nextId;
+ // before advice
+ var args = arguments;
+ var before = dispatcher.before;
+ while(before){
+ args = before.advice.apply(this, args) || args;
+ before = before.next;
+ }
+ // around advice
+ if(dispatcher.around){
+ var results = dispatcher.around.advice(this, args);
+ }
+ // after advice
+ var after = dispatcher.after;
+ while(after && after.id < executionId){
+ if(after.receiveArguments){
+ var newResults = after.advice.apply(this, args);
+ // change the return value only if a new value was returned
+ results = newResults === undefined ? results : newResults;
+ }else{
+ results = after.advice.call(this, results, args);
+ }
+ after = after.next;
+ }
+ return results;
+ };
+ if(existing){
+ dispatcher.around = {advice: function(target, args){
+ return existing.apply(target, args);
+ }};
+ }
+ dispatcher.target = target;
+ }
+ var results = advise((dispatcher || existing), type, advice, receiveArguments);
+ advice = null;
+ return results;
+ };
+ }
+
+ // TODOC: after/before/around return object
+
+ var after = aspect("after");
+ /*=====
+ after = function(target, methodName, advice, receiveArguments){
+ // summary:
+ // The "after" export of the aspect module is a function that can be used to attach
+ // "after" advice to a method. This function will be executed after the original method
+ // is executed. By default the function will be called with a single argument, the return
+ // value of the original method, or the the return value of the last executed advice (if a previous one exists).
+ // The fourth (optional) argument can be set to true to so the function receives the original
+ // arguments (from when the original method was called) rather than the return value.
+ // If there are multiple "after" advisors, they are executed in the order they were registered.
+ // target: Object
+ // This is the target object
+ // methodName: String
+ // This is the name of the method to attach to.
+ // advice: Function
+ // This is function to be called after the original method
+ // receiveArguments: Boolean?
+ // If this is set to true, the advice function receives the original arguments (from when the original mehtod
+ // was called) rather than the return value of the original/previous method.
+ // returns:
+ // A signal object that can be used to cancel the advice. If remove() is called on this signal object, it will
+ // stop the advice function from being executed.
+ };
+ =====*/
+
+ var before = aspect("before");
+ /*=====
+ before = function(target, methodName, advice){
+ // summary:
+ // The "before" export of the aspect module is a function that can be used to attach
+ // "before" advice to a method. This function will be executed before the original method
+ // is executed. This function will be called with the arguments used to call the method.
+ // This function may optionally return an array as the new arguments to use to call
+ // the original method (or the previous, next-to-execute before advice, if one exists).
+ // If the before method doesn't return anything (returns undefined) the original arguments
+ // will be preserved.
+ // If there are multiple "before" advisors, they are executed in the reverse order they were registered.
+ // target: Object
+ // This is the target object
+ // methodName: String
+ // This is the name of the method to attach to.
+ // advice: Function
+ // This is function to be called before the original method
+ };
+ =====*/
+
+ var around = aspect("around");
+ /*=====
+ around = function(target, methodName, advice){
+ // summary:
+ // The "around" export of the aspect module is a function that can be used to attach
+ // "around" advice to a method. The advisor function is immediately executed when
+ // the around() is called, is passed a single argument that is a function that can be
+ // called to continue execution of the original method (or the next around advisor).
+ // The advisor function should return a function, and this function will be called whenever
+ // the method is called. It will be called with the arguments used to call the method.
+ // Whatever this function returns will be returned as the result of the method call (unless after advise changes it).
+ // example:
+ // If there are multiple "around" advisors, the most recent one is executed first,
+ // which can then delegate to the next one and so on. For example:
+ // | around(obj, "foo", function(originalFoo){
+ // | return function(){
+ // | var start = new Date().getTime();
+ // | var results = originalFoo.apply(this, arguments); // call the original
+ // | var end = new Date().getTime();
+ // | console.log("foo execution took " + (end - start) + " ms");
+ // | return results;
+ // | };
+ // | });
+ // target: Object
+ // This is the target object
+ // methodName: String
+ // This is the name of the method to attach to.
+ // advice: Function
+ // This is function to be called around the original method
+ };
+ =====*/
+
+ return {
+ // summary:
+ // provides aspect oriented programming functionality, allowing for
+ // one to add before, around, or after advice on existing methods.
+ // example:
+ // | define(["dojo/aspect"], function(aspect){
+ // | var signal = aspect.after(targetObject, "methodName", function(someArgument){
+ // | this will be called when targetObject.methodName() is called, after the original function is called
+ // | });
+ //
+ // example:
+ // The returned signal object can be used to cancel the advice.
+ // | signal.remove(); // this will stop the advice from being executed anymore
+ // | aspect.before(targetObject, "methodName", function(someArgument){
+ // | // this will be called when targetObject.methodName() is called, before the original function is called
+ // | });
+
+ before: before,
+ around: around,
+ after: after
+ };
+});
+
+},
+'dojo/ready':function(){
+define("dojo/ready", ["./_base/kernel", "./has", "require", "./domReady", "./_base/lang"], function(dojo, has, require, domReady, lang){
+ // module:
+ // dojo/ready
+ // note:
+ // This module should be unnecessary in dojo 2.0
+
+ var
+ // truthy if DOMContentLoaded or better (e.g., window.onload fired) has been achieved
+ isDomReady = 0,
+
+ // a function to call to cause onLoad to be called when all requested modules have been loaded
+ requestCompleteSignal,
+
+ // The queue of functions waiting to execute as soon as dojo.ready conditions satisfied
+ loadQ = [],
+
+ // prevent recursion in onLoad
+ onLoadRecursiveGuard = 0,
+
+ handleDomReady = function(){
+ isDomReady = 1;
+ dojo._postLoad = dojo.config.afterOnLoad = true;
+ if(loadQ.length){
+ requestCompleteSignal(onLoad);
+ }
+ },
+
+ // run the next function queued with dojo.ready
+ onLoad = function(){
+ if(isDomReady && !onLoadRecursiveGuard && loadQ.length){
+ //guard against recursions into this function
+ onLoadRecursiveGuard = 1;
+ var f = loadQ.shift();
+ try{
+ f();
+ }
+ // FIXME: signal the error via require.on
+ finally{
+ onLoadRecursiveGuard = 0;
+ }
+ onLoadRecursiveGuard = 0;
+ if(loadQ.length){
+ requestCompleteSignal(onLoad);
+ }
+ }
+ };
+
+ require.on("idle", onLoad);
+ requestCompleteSignal = function(){
+ if(require.idle()){
+ onLoad();
+ } // else do nothing, onLoad will be called with the next idle signal
+ };
+
+ var ready = dojo.ready = dojo.addOnLoad = function(priority, context, callback){
+ // summary:
+ // Add a function to execute on DOM content loaded and all requested modules have arrived and been evaluated.
+ // In most cases, the `domReady` plug-in should suffice and this method should not be needed.
+ // priority: Integer?
+ // The order in which to exec this callback relative to other callbacks, defaults to 1000
+ // context: Object?|Function
+ // The context in which to run execute callback, or a callback if not using context
+ // callback: Function?
+ // The function to execute.
+ //
+ // example:
+ // Simple DOM and Modules ready syntax
+ // | require(["dojo/ready"], function(ready){
+ // | ready(function(){ alert("Dom ready!"); });
+ // | });
+ //
+ // example:
+ // Using a priority
+ // | require(["dojo/ready"], function(ready){
+ // | ready(2, function(){ alert("low priority ready!"); })
+ // | });
+ //
+ // example:
+ // Using context
+ // | require(["dojo/ready"], function(ready){
+ // | ready(foo, function(){
+ // | // in here, this == foo
+ // | });
+ // | });
+ //
+ // example:
+ // Using dojo/hitch style args:
+ // | require(["dojo/ready"], function(ready){
+ // | var foo = { dojoReady: function(){ console.warn(this, "dojo dom and modules ready."); } };
+ // | ready(foo, "dojoReady");
+ // | });
+
+ var hitchArgs = lang._toArray(arguments);
+ if(typeof priority != "number"){
+ callback = context;
+ context = priority;
+ priority = 1000;
+ }else{
+ hitchArgs.shift();
+ }
+ callback = callback ?
+ lang.hitch.apply(dojo, hitchArgs) :
+ function(){
+ context();
+ };
+ callback.priority = priority;
+ for(var i = 0; i < loadQ.length && priority >= loadQ[i].priority; i++){}
+ loadQ.splice(i, 0, callback);
+ requestCompleteSignal();
+ };
+
+ 1 || has.add("dojo-config-addOnLoad", 1);
+ if( 1 ){
+ var dca = dojo.config.addOnLoad;
+ if(dca){
+ ready[(lang.isArray(dca) ? "apply" : "call")](dojo, dca);
+ }
+ }
+
+ if( 1 && dojo.config.parseOnLoad && !dojo.isAsync){
+ ready(99, function(){
+ if(!dojo.parser){
+ dojo.deprecated("Add explicit require(['dojo/parser']);", "", "2.0");
+ require(["dojo/parser"]);
+ }
+ });
+ }
+
+ if( 1 ){
+ domReady(handleDomReady);
+ }else{
+ handleDomReady();
+ }
+
+ return ready;
+});
+
+},
+'dojo/_base/connect':function(){
+define(["./kernel", "../on", "../topic", "../aspect", "./event", "../mouse", "./sniff", "./lang", "../keys"], function(dojo, on, hub, aspect, eventModule, mouse, has, lang){
+// module:
+// dojo/_base/connect
+
+has.add("events-keypress-typed", function(){ // keypresses should only occur a printable character is hit
+ var testKeyEvent = {charCode: 0};
+ try{
+ testKeyEvent = document.createEvent("KeyboardEvent");
+ (testKeyEvent.initKeyboardEvent || testKeyEvent.initKeyEvent).call(testKeyEvent, "keypress", true, true, null, false, false, false, false, 9, 3);
+ }catch(e){}
+ return testKeyEvent.charCode == 0 && !has("opera");
+});
+
+function connect_(obj, event, context, method, dontFix){
+ method = lang.hitch(context, method);
+ if(!obj || !(obj.addEventListener || obj.attachEvent)){
+ // it is a not a DOM node and we are using the dojo.connect style of treating a
+ // method like an event, must go right to aspect
+ return aspect.after(obj || dojo.global, event, method, true);
+ }
+ if(typeof event == "string" && event.substring(0, 2) == "on"){
+ event = event.substring(2);
+ }
+ if(!obj){
+ obj = dojo.global;
+ }
+ if(!dontFix){
+ switch(event){
+ // dojo.connect has special handling for these event types
+ case "keypress":
+ event = keypress;
+ break;
+ case "mouseenter":
+ event = mouse.enter;
+ break;
+ case "mouseleave":
+ event = mouse.leave;
+ break;
+ }
+ }
+ return on(obj, event, method, dontFix);
+}
+
+var _punctMap = {
+ 106:42,
+ 111:47,
+ 186:59,
+ 187:43,
+ 188:44,
+ 189:45,
+ 190:46,
+ 191:47,
+ 192:96,
+ 219:91,
+ 220:92,
+ 221:93,
+ 222:39,
+ 229:113
+};
+var evtCopyKey = has("mac") ? "metaKey" : "ctrlKey";
+
+
+var _synthesizeEvent = function(evt, props){
+ var faux = lang.mixin({}, evt, props);
+ setKeyChar(faux);
+ // FIXME: would prefer to use lang.hitch: lang.hitch(evt, evt.preventDefault);
+ // but it throws an error when preventDefault is invoked on Safari
+ // does Event.preventDefault not support "apply" on Safari?
+ faux.preventDefault = function(){ evt.preventDefault(); };
+ faux.stopPropagation = function(){ evt.stopPropagation(); };
+ return faux;
+};
+function setKeyChar(evt){
+ evt.keyChar = evt.charCode ? String.fromCharCode(evt.charCode) : '';
+ evt.charOrCode = evt.keyChar || evt.keyCode;
+}
+var keypress;
+if(has("events-keypress-typed")){
+ // this emulates Firefox's keypress behavior where every keydown can correspond to a keypress
+ var _trySetKeyCode = function(e, code){
+ try{
+ // squelch errors when keyCode is read-only
+ // (e.g. if keyCode is ctrl or shift)
+ return (e.keyCode = code);
+ }catch(e){
+ return 0;
+ }
+ };
+ keypress = function(object, listener){
+ var keydownSignal = on(object, "keydown", function(evt){
+ // munge key/charCode
+ var k=evt.keyCode;
+ // These are Windows Virtual Key Codes
+ // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/UserInput/VirtualKeyCodes.asp
+ var unprintable = (k!=13) && k!=32 && (k!=27||!has("ie")) && (k<48||k>90) && (k<96||k>111) && (k<186||k>192) && (k<219||k>222) && k!=229;
+ // synthesize keypress for most unprintables and CTRL-keys
+ if(unprintable||evt.ctrlKey){
+ var c = unprintable ? 0 : k;
+ if(evt.ctrlKey){
+ if(k==3 || k==13){
+ return listener.call(evt.currentTarget, evt); // IE will post CTRL-BREAK, CTRL-ENTER as keypress natively
+ }else if(c>95 && c<106){
+ c -= 48; // map CTRL-[numpad 0-9] to ASCII
+ }else if((!evt.shiftKey)&&(c>=65&&c<=90)){
+ c += 32; // map CTRL-[A-Z] to lowercase
+ }else{
+ c = _punctMap[c] || c; // map other problematic CTRL combinations to ASCII
+ }
+ }
+ // simulate a keypress event
+ var faux = _synthesizeEvent(evt, {type: 'keypress', faux: true, charCode: c});
+ listener.call(evt.currentTarget, faux);
+ if(has("ie")){
+ _trySetKeyCode(evt, faux.keyCode);
+ }
+ }
+ });
+ var keypressSignal = on(object, "keypress", function(evt){
+ var c = evt.charCode;
+ c = c>=32 ? c : 0;
+ evt = _synthesizeEvent(evt, {charCode: c, faux: true});
+ return listener.call(this, evt);
+ });
+ return {
+ remove: function(){
+ keydownSignal.remove();
+ keypressSignal.remove();
+ }
+ };
+ };
+}else{
+ if(has("opera")){
+ keypress = function(object, listener){
+ return on(object, "keypress", function(evt){
+ var c = evt.which;
+ if(c==3){
+ c=99; // Mozilla maps CTRL-BREAK to CTRL-c
+ }
+ // can't trap some keys at all, like INSERT and DELETE
+ // there is no differentiating info between DELETE and ".", or INSERT and "-"
+ c = c<32 && !evt.shiftKey ? 0 : c;
+ if(evt.ctrlKey && !evt.shiftKey && c>=65 && c<=90){
+ // lowercase CTRL-[A-Z] keys
+ c += 32;
+ }
+ return listener.call(this, _synthesizeEvent(evt, { charCode: c }));
+ });
+ };
+ }else{
+ keypress = function(object, listener){
+ return on(object, "keypress", function(evt){
+ setKeyChar(evt);
+ return listener.call(this, evt);
+ });
+ };
+ }
+}
+
+var connect = {
+ // summary:
+ // This module defines the dojo.connect API.
+ // This modules also provides keyboard event handling helpers.
+ // This module exports an extension event for emulating Firefox's keypress handling.
+ // However, this extension event exists primarily for backwards compatibility and
+ // is not recommended. WebKit and IE uses an alternate keypress handling (only
+ // firing for printable characters, to distinguish from keydown events), and most
+ // consider the WebKit/IE behavior more desirable.
+
+ _keypress:keypress,
+
+ connect:function(obj, event, context, method, dontFix){
+ // summary:
+ // `dojo.connect` is a deprecated event handling and delegation method in
+ // Dojo. It allows one function to "listen in" on the execution of
+ // any other, triggering the second whenever the first is called. Many
+ // listeners may be attached to a function, and source functions may
+ // be either regular function calls or DOM events.
+ //
+ // description:
+ // Connects listeners to actions, so that after event fires, a
+ // listener is called with the same arguments passed to the original
+ // function.
+ //
+ // Since `dojo.connect` allows the source of events to be either a
+ // "regular" JavaScript function or a DOM event, it provides a uniform
+ // interface for listening to all the types of events that an
+ // application is likely to deal with though a single, unified
+ // interface. DOM programmers may want to think of it as
+ // "addEventListener for everything and anything".
+ //
+ // When setting up a connection, the `event` parameter must be a
+ // string that is the name of the method/event to be listened for. If
+ // `obj` is null, `kernel.global` is assumed, meaning that connections
+ // to global methods are supported but also that you may inadvertently
+ // connect to a global by passing an incorrect object name or invalid
+ // reference.
+ //
+ // `dojo.connect` generally is forgiving. If you pass the name of a
+ // function or method that does not yet exist on `obj`, connect will
+ // not fail, but will instead set up a stub method. Similarly, null
+ // arguments may simply be omitted such that fewer than 4 arguments
+ // may be required to set up a connection See the examples for details.
+ //
+ // The return value is a handle that is needed to
+ // remove this connection with `dojo.disconnect`.
+ //
+ // obj: Object?
+ // The source object for the event function.
+ // Defaults to `kernel.global` if null.
+ // If obj is a DOM node, the connection is delegated
+ // to the DOM event manager (unless dontFix is true).
+ //
+ // event: String
+ // String name of the event function in obj.
+ // I.e. identifies a property `obj[event]`.
+ //
+ // context: Object|null
+ // The object that method will receive as "this".
+ //
+ // If context is null and method is a function, then method
+ // inherits the context of event.
+ //
+ // If method is a string then context must be the source
+ // object object for method (context[method]). If context is null,
+ // kernel.global is used.
+ //
+ // method: String|Function
+ // A function reference, or name of a function in context.
+ // The function identified by method fires after event does.
+ // method receives the same arguments as the event.
+ // See context argument comments for information on method's scope.
+ //
+ // dontFix: Boolean?
+ // If obj is a DOM node, set dontFix to true to prevent delegation
+ // of this connection to the DOM event manager.
+ //
+ // example:
+ // When obj.onchange(), do ui.update():
+ // | dojo.connect(obj, "onchange", ui, "update");
+ // | dojo.connect(obj, "onchange", ui, ui.update); // same
+ //
+ // example:
+ // Using return value for disconnect:
+ // | var link = dojo.connect(obj, "onchange", ui, "update");
+ // | ...
+ // | dojo.disconnect(link);
+ //
+ // example:
+ // When onglobalevent executes, watcher.handler is invoked:
+ // | dojo.connect(null, "onglobalevent", watcher, "handler");
+ //
+ // example:
+ // When ob.onCustomEvent executes, customEventHandler is invoked:
+ // | dojo.connect(ob, "onCustomEvent", null, "customEventHandler");
+ // | dojo.connect(ob, "onCustomEvent", "customEventHandler"); // same
+ //
+ // example:
+ // When ob.onCustomEvent executes, customEventHandler is invoked
+ // with the same scope (this):
+ // | dojo.connect(ob, "onCustomEvent", null, customEventHandler);
+ // | dojo.connect(ob, "onCustomEvent", customEventHandler); // same
+ //
+ // example:
+ // When globalEvent executes, globalHandler is invoked
+ // with the same scope (this):
+ // | dojo.connect(null, "globalEvent", null, globalHandler);
+ // | dojo.connect("globalEvent", globalHandler); // same
+
+ // normalize arguments
+ var a=arguments, args=[], i=0;
+ // if a[0] is a String, obj was omitted
+ args.push(typeof a[0] == "string" ? null : a[i++], a[i++]);
+ // if the arg-after-next is a String or Function, context was NOT omitted
+ var a1 = a[i+1];
+ args.push(typeof a1 == "string" || typeof a1 == "function" ? a[i++] : null, a[i++]);
+ // absorb any additional arguments
+ for(var l=a.length; iThe name of the property in the global namespace (The window in browser environments) which refers to the current instance of Ext.
+ * This is usually "Ext", but if a sandboxed build of ExtJS is being used, this will be an alternative name.
+ * If code is being generated for use by eval or to create a new Function, and the global instance
+ * of Ext must be referenced, this is the name that should be built into the code.
+ */
+ name: Ext.sandboxName || 'Ext',
+
+ /**
+ * A reusable empty function
+ */
+ emptyFn: emptyFn,
+
+ /**
+ * A zero length string which will pass a truth test. Useful for passing to methods
+ * which use a truth test to reject falsy values where a string value must be cleared.
+ */
+ emptyString: new String(),
+
+ baseCSSPrefix: Ext.buildSettings.baseCSSPrefix,
+
+ /**
+ * Copies all the properties of config to object if they don't already exist.
+ * @param {Object} object The receiver of the properties
+ * @param {Object} config The source of the properties
+ * @return {Object} returns obj
+ */
+ applyIf: function(object, config) {
+ var property;
+
+ if (object) {
+ for (property in config) {
+ if (object[property] === undefined) {
+ object[property] = config[property];
+ }
+ }
+ }
+
+ return object;
+ },
+
+ /**
+ * Iterates either an array or an object. This method delegates to
+ * {@link Ext.Array#each Ext.Array.each} if the given value is iterable, and {@link Ext.Object#each Ext.Object.each} otherwise.
+ *
+ * @param {Object/Array} object The object or array to be iterated.
+ * @param {Function} fn The function to be called for each iteration. See and {@link Ext.Array#each Ext.Array.each} and
+ * {@link Ext.Object#each Ext.Object.each} for detailed lists of arguments passed to this function depending on the given object
+ * type that is being iterated.
+ * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
+ * Defaults to the object being iterated itself.
+ * @markdown
+ */
+ iterate: function(object, fn, scope) {
+ if (Ext.isEmpty(object)) {
+ return;
+ }
+
+ if (scope === undefined) {
+ scope = object;
+ }
+
+ if (Ext.isIterable(object)) {
+ Ext.Array.each.call(Ext.Array, object, fn, scope);
+ }
+ else {
+ Ext.Object.each.call(Ext.Object, object, fn, scope);
+ }
+ }
+ });
+
+ Ext.apply(Ext, {
+
+ /**
+ * This method deprecated. Use {@link Ext#define Ext.define} instead.
+ * @method
+ * @param {Function} superclass
+ * @param {Object} overrides
+ * @return {Function} The subclass constructor from the overrides parameter, or a generated one if not provided.
+ * @deprecated 4.0.0 Use {@link Ext#define Ext.define} instead
+ */
+ extend: (function() {
+ // inline overrides
+ var objectConstructor = objectPrototype.constructor,
+ inlineOverrides = function(o) {
+ for (var m in o) {
+ if (!o.hasOwnProperty(m)) {
+ continue;
+ }
+ this[m] = o[m];
+ }
+ };
+
+ return function(subclass, superclass, overrides) {
+ // First we check if the user passed in just the superClass with overrides
+ if (Ext.isObject(superclass)) {
+ overrides = superclass;
+ superclass = subclass;
+ subclass = overrides.constructor !== objectConstructor ? overrides.constructor : function() {
+ superclass.apply(this, arguments);
+ };
+ }
+
+ if (!superclass) {
+ Ext.Error.raise({
+ sourceClass: 'Ext',
+ sourceMethod: 'extend',
+ msg: 'Attempting to extend from a class which has not been loaded on the page.'
+ });
+ }
+
+ // We create a new temporary class
+ var F = function() {},
+ subclassProto, superclassProto = superclass.prototype;
+
+ F.prototype = superclassProto;
+ subclassProto = subclass.prototype = new F();
+ subclassProto.constructor = subclass;
+ subclass.superclass = superclassProto;
+
+ if (superclassProto.constructor === objectConstructor) {
+ superclassProto.constructor = superclass;
+ }
+
+ subclass.override = function(overrides) {
+ Ext.override(subclass, overrides);
+ };
+
+ subclassProto.override = inlineOverrides;
+ subclassProto.proto = subclassProto;
+
+ subclass.override(overrides);
+ subclass.extend = function(o) {
+ return Ext.extend(subclass, o);
+ };
+
+ return subclass;
+ };
+ }()),
+
+ /**
+ * Overrides members of the specified `target` with the given values.
+ *
+ * If the `target` is a class declared using {@link Ext#define Ext.define}, the
+ * `override` method of that class is called (see {@link Ext.Base#override}) given
+ * the `overrides`.
+ *
+ * If the `target` is a function, it is assumed to be a constructor and the contents
+ * of `overrides` are applied to its `prototype` using {@link Ext#apply Ext.apply}.
+ *
+ * If the `target` is an instance of a class declared using {@link Ext#define Ext.define},
+ * the `overrides` are applied to only that instance. In this case, methods are
+ * specially processed to allow them to use {@link Ext.Base#callParent}.
+ *
+ * var panel = new Ext.Panel({ ... });
+ *
+ * Ext.override(panel, {
+ * initComponent: function () {
+ * // extra processing...
+ *
+ * this.callParent();
+ * }
+ * });
+ *
+ * If the `target` is none of these, the `overrides` are applied to the `target`
+ * using {@link Ext#apply Ext.apply}.
+ *
+ * Please refer to {@link Ext#define Ext.define} and {@link Ext.Base#override} for
+ * further details.
+ *
+ * @param {Object} target The target to override.
+ * @param {Object} overrides The properties to add or replace on `target`.
+ * @method override
+ */
+ override: function (target, overrides) {
+ if (target.$isClass) {
+ target.override(overrides);
+ } else if (typeof target == 'function') {
+ Ext.apply(target.prototype, overrides);
+ } else {
+ var owner = target.self,
+ name, value;
+
+ if (owner && owner.$isClass) { // if (instance of Ext.define'd class)
+ for (name in overrides) {
+ if (overrides.hasOwnProperty(name)) {
+ value = overrides[name];
+
+ if (typeof value == 'function') {
+ if (owner.$className) {
+ value.displayName = owner.$className + '#' + name;
+ }
+
+ value.$name = name;
+ value.$owner = owner;
+ value.$previous = target.hasOwnProperty(name)
+ ? target[name] // already hooked, so call previous hook
+ : callOverrideParent; // calls by name on prototype
+ }
+
+ target[name] = value;
+ }
+ }
+ } else {
+ Ext.apply(target, overrides);
+ }
+ }
+
+ return target;
+ }
+ });
+
+ // A full set of static methods to do type checking
+ Ext.apply(Ext, {
+
+ /**
+ * Returns the given value itself if it's not empty, as described in {@link Ext#isEmpty}; returns the default
+ * value (second argument) otherwise.
+ *
+ * @param {Object} value The value to test
+ * @param {Object} defaultValue The value to return if the original value is empty
+ * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
+ * @return {Object} value, if non-empty, else defaultValue
+ */
+ valueFrom: function(value, defaultValue, allowBlank){
+ return Ext.isEmpty(value, allowBlank) ? defaultValue : value;
+ },
+
+ /**
+ * Returns the type of the given variable in string format. List of possible values are:
+ *
+ * - `undefined`: If the given value is `undefined`
+ * - `null`: If the given value is `null`
+ * - `string`: If the given value is a string
+ * - `number`: If the given value is a number
+ * - `boolean`: If the given value is a boolean value
+ * - `date`: If the given value is a `Date` object
+ * - `function`: If the given value is a function reference
+ * - `object`: If the given value is an object
+ * - `array`: If the given value is an array
+ * - `regexp`: If the given value is a regular expression
+ * - `element`: If the given value is a DOM Element
+ * - `textnode`: If the given value is a DOM text node and contains something other than whitespace
+ * - `whitespace`: If the given value is a DOM text node and contains only whitespace
+ *
+ * @param {Object} value
+ * @return {String}
+ * @markdown
+ */
+ typeOf: function(value) {
+ var type,
+ typeToString;
+
+ if (value === null) {
+ return 'null';
+ }
+
+ type = typeof value;
+
+ if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') {
+ return type;
+ }
+
+ typeToString = toString.call(value);
+
+ switch(typeToString) {
+ case '[object Array]':
+ return 'array';
+ case '[object Date]':
+ return 'date';
+ case '[object Boolean]':
+ return 'boolean';
+ case '[object Number]':
+ return 'number';
+ case '[object RegExp]':
+ return 'regexp';
+ }
+
+ if (type === 'function') {
+ return 'function';
+ }
+
+ if (type === 'object') {
+ if (value.nodeType !== undefined) {
+ if (value.nodeType === 3) {
+ return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace';
+ }
+ else {
+ return 'element';
+ }
+ }
+
+ return 'object';
+ }
+
+ Ext.Error.raise({
+ sourceClass: 'Ext',
+ sourceMethod: 'typeOf',
+ msg: 'Failed to determine the type of the specified value "' + value + '". This is most likely a bug.'
+ });
+ },
+
+ /**
+ * Returns true if the passed value is empty, false otherwise. The value is deemed to be empty if it is either:
+ *
+ * - `null`
+ * - `undefined`
+ * - a zero-length array
+ * - a zero-length string (Unless the `allowEmptyString` parameter is set to `true`)
+ *
+ * @param {Object} value The value to test
+ * @param {Boolean} allowEmptyString (optional) true to allow empty strings (defaults to false)
+ * @return {Boolean}
+ * @markdown
+ */
+ isEmpty: function(value, allowEmptyString) {
+ return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0);
+ },
+
+ /**
+ * Returns true if the passed value is a JavaScript Array, false otherwise.
+ *
+ * @param {Object} target The target to test
+ * @return {Boolean}
+ * @method
+ */
+ isArray: ('isArray' in Array) ? Array.isArray : function(value) {
+ return toString.call(value) === '[object Array]';
+ },
+
+ /**
+ * Returns true if the passed value is a JavaScript Date object, false otherwise.
+ * @param {Object} object The object to test
+ * @return {Boolean}
+ */
+ isDate: function(value) {
+ return toString.call(value) === '[object Date]';
+ },
+
+ /**
+ * Returns true if the passed value is a JavaScript Object, false otherwise.
+ * @param {Object} value The value to test
+ * @return {Boolean}
+ * @method
+ */
+ isObject: (toString.call(null) === '[object Object]') ?
+ function(value) {
+ // check ownerDocument here as well to exclude DOM nodes
+ return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.ownerDocument === undefined;
+ } :
+ function(value) {
+ return toString.call(value) === '[object Object]';
+ },
+
+ /**
+ * @private
+ */
+ isSimpleObject: function(value) {
+ return value instanceof Object && value.constructor === Object;
+ },
+ /**
+ * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean.
+ * @param {Object} value The value to test
+ * @return {Boolean}
+ */
+ isPrimitive: function(value) {
+ var type = typeof value;
+
+ return type === 'string' || type === 'number' || type === 'boolean';
+ },
+
+ /**
+ * Returns true if the passed value is a JavaScript Function, false otherwise.
+ * @param {Object} value The value to test
+ * @return {Boolean}
+ * @method
+ */
+ isFunction:
+ // Safari 3.x and 4.x returns 'function' for typeof , hence we need to fall back to using
+ // Object.prototype.toString (slower)
+ (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) {
+ return toString.call(value) === '[object Function]';
+ } : function(value) {
+ return typeof value === 'function';
+ },
+
+ /**
+ * Returns true if the passed value is a number. Returns false for non-finite numbers.
+ * @param {Object} value The value to test
+ * @return {Boolean}
+ */
+ isNumber: function(value) {
+ return typeof value === 'number' && isFinite(value);
+ },
+
+ /**
+ * Validates that a value is numeric.
+ * @param {Object} value Examples: 1, '1', '2.34'
+ * @return {Boolean} True if numeric, false otherwise
+ */
+ isNumeric: function(value) {
+ return !isNaN(parseFloat(value)) && isFinite(value);
+ },
+
+ /**
+ * Returns true if the passed value is a string.
+ * @param {Object} value The value to test
+ * @return {Boolean}
+ */
+ isString: function(value) {
+ return typeof value === 'string';
+ },
+
+ /**
+ * Returns true if the passed value is a boolean.
+ *
+ * @param {Object} value The value to test
+ * @return {Boolean}
+ */
+ isBoolean: function(value) {
+ return typeof value === 'boolean';
+ },
+
+ /**
+ * Returns true if the passed value is an HTMLElement
+ * @param {Object} value The value to test
+ * @return {Boolean}
+ */
+ isElement: function(value) {
+ return value ? value.nodeType === 1 : false;
+ },
+
+ /**
+ * Returns true if the passed value is a TextNode
+ * @param {Object} value The value to test
+ * @return {Boolean}
+ */
+ isTextNode: function(value) {
+ return value ? value.nodeName === "#text" : false;
+ },
+
+ /**
+ * Returns true if the passed value is defined.
+ * @param {Object} value The value to test
+ * @return {Boolean}
+ */
+ isDefined: function(value) {
+ return typeof value !== 'undefined';
+ },
+
+ /**
+ * Returns true if the passed value is iterable, false otherwise
+ * @param {Object} value The value to test
+ * @return {Boolean}
+ */
+ isIterable: function(value) {
+ var type = typeof value,
+ checkLength = false;
+ if (value && type != 'string') {
+ // Functions have a length property, so we need to filter them out
+ if (type == 'function') {
+ // In Safari, NodeList/HTMLCollection both return "function" when using typeof, so we need
+ // to explicitly check them here.
+ if (Ext.isSafari) {
+ checkLength = value instanceof NodeList || value instanceof HTMLCollection;
+ }
+ } else {
+ checkLength = true;
+ }
+ }
+ return checkLength ? value.length !== undefined : false;
+ }
+ });
+
+ Ext.apply(Ext, {
+
+ /**
+ * Clone simple variables including array, {}-like objects, DOM nodes and Date without keeping the old reference.
+ * A reference for the object itself is returned if it's not a direct decendant of Object. For model cloning,
+ * see {@link Ext.data.Model#copy Model.copy}.
+ *
+ * @param {Object} item The variable to clone
+ * @return {Object} clone
+ */
+ clone: function(item) {
+ var type,
+ i,
+ j,
+ k,
+ clone,
+ key;
+
+ if (item === null || item === undefined) {
+ return item;
+ }
+
+ // DOM nodes
+ // TODO proxy this to Ext.Element.clone to handle automatic id attribute changing
+ // recursively
+ if (item.nodeType && item.cloneNode) {
+ return item.cloneNode(true);
+ }
+
+ type = toString.call(item);
+
+ // Date
+ if (type === '[object Date]') {
+ return new Date(item.getTime());
+ }
+
+
+ // Array
+ if (type === '[object Array]') {
+ i = item.length;
+
+ clone = [];
+
+ while (i--) {
+ clone[i] = Ext.clone(item[i]);
+ }
+ }
+ // Object
+ else if (type === '[object Object]' && item.constructor === Object) {
+ clone = {};
+
+ for (key in item) {
+ clone[key] = Ext.clone(item[key]);
+ }
+
+ if (enumerables) {
+ for (j = enumerables.length; j--;) {
+ k = enumerables[j];
+ clone[k] = item[k];
+ }
+ }
+ }
+
+ return clone || item;
+ },
+
+ /**
+ * @private
+ * Generate a unique reference of Ext in the global scope, useful for sandboxing
+ */
+ getUniqueGlobalNamespace: function() {
+ var uniqueGlobalNamespace = this.uniqueGlobalNamespace,
+ i;
+
+ if (uniqueGlobalNamespace === undefined) {
+ i = 0;
+
+ do {
+ uniqueGlobalNamespace = 'ExtBox' + (++i);
+ } while (Ext.global[uniqueGlobalNamespace] !== undefined);
+
+ Ext.global[uniqueGlobalNamespace] = Ext;
+ this.uniqueGlobalNamespace = uniqueGlobalNamespace;
+ }
+
+ return uniqueGlobalNamespace;
+ },
+
+ /**
+ * @private
+ */
+ functionFactoryCache: {},
+
+ cacheableFunctionFactory: function() {
+ var me = this,
+ args = Array.prototype.slice.call(arguments),
+ cache = me.functionFactoryCache,
+ idx, fn, ln;
+
+ if (Ext.isSandboxed) {
+ ln = args.length;
+ if (ln > 0) {
+ ln--;
+ args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln];
+ }
+ }
+ idx = args.join('');
+ fn = cache[idx];
+ if (!fn) {
+ fn = Function.prototype.constructor.apply(Function.prototype, args);
+
+ cache[idx] = fn;
+ }
+ return fn;
+ },
+
+ functionFactory: function() {
+ var me = this,
+ args = Array.prototype.slice.call(arguments),
+ ln;
+
+ if (Ext.isSandboxed) {
+ ln = args.length;
+ if (ln > 0) {
+ ln--;
+ args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln];
+ }
+ }
+
+ return Function.prototype.constructor.apply(Function.prototype, args);
+ },
+
+ /**
+ * @private
+ * @property
+ */
+ Logger: {
+ verbose: emptyFn,
+ log: emptyFn,
+ info: emptyFn,
+ warn: emptyFn,
+ error: function(message) {
+ throw new Error(message);
+ },
+ deprecate: emptyFn
+ }
+ });
+
+ /**
+ * Old alias to {@link Ext#typeOf}
+ * @deprecated 4.0.0 Use {@link Ext#typeOf} instead
+ * @method
+ * @inheritdoc Ext#typeOf
+ */
+ Ext.type = Ext.typeOf;
+
+}());
+
+/*
+ * This method evaluates the given code free of any local variable. In some browsers this
+ * will be at global scope, in others it will be in a function.
+ * @parma {String} code The code to evaluate.
+ * @private
+ * @method
+ */
+Ext.globalEval = Ext.global.execScript
+ ? function(code) {
+ execScript(code);
+ }
+ : function($$code) {
+ // IMPORTANT: because we use eval we cannot place this in the above function or it
+ // will break the compressor's ability to rename local variables...
+ (function(){
+ eval($$code);
+ }());
+ };
+
+//@tag foundation,core
+//@require ../Ext.js
+
+/**
+ * @author Jacky Nguyen
+ * @docauthor Jacky Nguyen
+ * @class Ext.Version
+ *
+ * A utility class that wrap around a string version number and provide convenient
+ * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example:
+ *
+ * var version = new Ext.Version('1.0.2beta');
+ * console.log("Version is " + version); // Version is 1.0.2beta
+ *
+ * console.log(version.getMajor()); // 1
+ * console.log(version.getMinor()); // 0
+ * console.log(version.getPatch()); // 2
+ * console.log(version.getBuild()); // 0
+ * console.log(version.getRelease()); // beta
+ *
+ * console.log(version.isGreaterThan('1.0.1')); // True
+ * console.log(version.isGreaterThan('1.0.2alpha')); // True
+ * console.log(version.isGreaterThan('1.0.2RC')); // False
+ * console.log(version.isGreaterThan('1.0.2')); // False
+ * console.log(version.isLessThan('1.0.2')); // True
+ *
+ * console.log(version.match(1.0)); // True
+ * console.log(version.match('1.0.2')); // True
+ *
+ */
+(function() {
+
+// Current core version
+var version = '4.1.1.1', Version;
+ Ext.Version = Version = Ext.extend(Object, {
+
+ /**
+ * @param {String/Number} version The version number in the following standard format:
+ *
+ * major[.minor[.patch[.build[release]]]]
+ *
+ * Examples:
+ *
+ * 1.0
+ * 1.2.3beta
+ * 1.2.3.4RC
+ *
+ * @return {Ext.Version} this
+ */
+ constructor: function(version) {
+ var parts, releaseStartIndex;
+
+ if (version instanceof Version) {
+ return version;
+ }
+
+ this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, '');
+
+ releaseStartIndex = this.version.search(/([^\d\.])/);
+
+ if (releaseStartIndex !== -1) {
+ this.release = this.version.substr(releaseStartIndex, version.length);
+ this.shortVersion = this.version.substr(0, releaseStartIndex);
+ }
+
+ this.shortVersion = this.shortVersion.replace(/[^\d]/g, '');
+
+ parts = this.version.split('.');
+
+ this.major = parseInt(parts.shift() || 0, 10);
+ this.minor = parseInt(parts.shift() || 0, 10);
+ this.patch = parseInt(parts.shift() || 0, 10);
+ this.build = parseInt(parts.shift() || 0, 10);
+
+ return this;
+ },
+
+ /**
+ * Override the native toString method
+ * @private
+ * @return {String} version
+ */
+ toString: function() {
+ return this.version;
+ },
+
+ /**
+ * Override the native valueOf method
+ * @private
+ * @return {String} version
+ */
+ valueOf: function() {
+ return this.version;
+ },
+
+ /**
+ * Returns the major component value
+ * @return {Number} major
+ */
+ getMajor: function() {
+ return this.major || 0;
+ },
+
+ /**
+ * Returns the minor component value
+ * @return {Number} minor
+ */
+ getMinor: function() {
+ return this.minor || 0;
+ },
+
+ /**
+ * Returns the patch component value
+ * @return {Number} patch
+ */
+ getPatch: function() {
+ return this.patch || 0;
+ },
+
+ /**
+ * Returns the build component value
+ * @return {Number} build
+ */
+ getBuild: function() {
+ return this.build || 0;
+ },
+
+ /**
+ * Returns the release component value
+ * @return {Number} release
+ */
+ getRelease: function() {
+ return this.release || '';
+ },
+
+ /**
+ * Returns whether this version if greater than the supplied argument
+ * @param {String/Number} target The version to compare with
+ * @return {Boolean} True if this version if greater than the target, false otherwise
+ */
+ isGreaterThan: function(target) {
+ return Version.compare(this.version, target) === 1;
+ },
+
+ /**
+ * Returns whether this version if greater than or equal to the supplied argument
+ * @param {String/Number} target The version to compare with
+ * @return {Boolean} True if this version if greater than or equal to the target, false otherwise
+ */
+ isGreaterThanOrEqual: function(target) {
+ return Version.compare(this.version, target) >= 0;
+ },
+
+ /**
+ * Returns whether this version if smaller than the supplied argument
+ * @param {String/Number} target The version to compare with
+ * @return {Boolean} True if this version if smaller than the target, false otherwise
+ */
+ isLessThan: function(target) {
+ return Version.compare(this.version, target) === -1;
+ },
+
+ /**
+ * Returns whether this version if less than or equal to the supplied argument
+ * @param {String/Number} target The version to compare with
+ * @return {Boolean} True if this version if less than or equal to the target, false otherwise
+ */
+ isLessThanOrEqual: function(target) {
+ return Version.compare(this.version, target) <= 0;
+ },
+
+ /**
+ * Returns whether this version equals to the supplied argument
+ * @param {String/Number} target The version to compare with
+ * @return {Boolean} True if this version equals to the target, false otherwise
+ */
+ equals: function(target) {
+ return Version.compare(this.version, target) === 0;
+ },
+
+ /**
+ * Returns whether this version matches the supplied argument. Example:
+ *
+ * var version = new Ext.Version('1.0.2beta');
+ * console.log(version.match(1)); // True
+ * console.log(version.match(1.0)); // True
+ * console.log(version.match('1.0.2')); // True
+ * console.log(version.match('1.0.2RC')); // False
+ *
+ * @param {String/Number} target The version to compare with
+ * @return {Boolean} True if this version matches the target, false otherwise
+ */
+ match: function(target) {
+ target = String(target);
+ return this.version.substr(0, target.length) === target;
+ },
+
+ /**
+ * Returns this format: [major, minor, patch, build, release]. Useful for comparison
+ * @return {Number[]}
+ */
+ toArray: function() {
+ return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()];
+ },
+
+ /**
+ * Returns shortVersion version without dots and release
+ * @return {String}
+ */
+ getShortVersion: function() {
+ return this.shortVersion;
+ },
+
+ /**
+ * Convenient alias to {@link Ext.Version#isGreaterThan isGreaterThan}
+ * @param {String/Number} target
+ * @return {Boolean}
+ */
+ gt: function() {
+ return this.isGreaterThan.apply(this, arguments);
+ },
+
+ /**
+ * Convenient alias to {@link Ext.Version#isLessThan isLessThan}
+ * @param {String/Number} target
+ * @return {Boolean}
+ */
+ lt: function() {
+ return this.isLessThan.apply(this, arguments);
+ },
+
+ /**
+ * Convenient alias to {@link Ext.Version#isGreaterThanOrEqual isGreaterThanOrEqual}
+ * @param {String/Number} target
+ * @return {Boolean}
+ */
+ gtEq: function() {
+ return this.isGreaterThanOrEqual.apply(this, arguments);
+ },
+
+ /**
+ * Convenient alias to {@link Ext.Version#isLessThanOrEqual isLessThanOrEqual}
+ * @param {String/Number} target
+ * @return {Boolean}
+ */
+ ltEq: function() {
+ return this.isLessThanOrEqual.apply(this, arguments);
+ }
+ });
+
+ Ext.apply(Version, {
+ // @private
+ releaseValueMap: {
+ 'dev': -6,
+ 'alpha': -5,
+ 'a': -5,
+ 'beta': -4,
+ 'b': -4,
+ 'rc': -3,
+ '#': -2,
+ 'p': -1,
+ 'pl': -1
+ },
+
+ /**
+ * Converts a version component to a comparable value
+ *
+ * @static
+ * @param {Object} value The value to convert
+ * @return {Object}
+ */
+ getComponentValue: function(value) {
+ return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10));
+ },
+
+ /**
+ * Compare 2 specified versions, starting from left to right. If a part contains special version strings,
+ * they are handled in the following order:
+ * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else'
+ *
+ * @static
+ * @param {String} current The current version to compare to
+ * @param {String} target The target version to compare to
+ * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent
+ */
+ compare: function(current, target) {
+ var currentValue, targetValue, i;
+
+ current = new Version(current).toArray();
+ target = new Version(target).toArray();
+
+ for (i = 0; i < Math.max(current.length, target.length); i++) {
+ currentValue = this.getComponentValue(current[i]);
+ targetValue = this.getComponentValue(target[i]);
+
+ if (currentValue < targetValue) {
+ return -1;
+ } else if (currentValue > targetValue) {
+ return 1;
+ }
+ }
+
+ return 0;
+ }
+ });
+
+ /**
+ * @class Ext
+ */
+ Ext.apply(Ext, {
+ /**
+ * @private
+ */
+ versions: {},
+
+ /**
+ * @private
+ */
+ lastRegisteredVersion: null,
+
+ /**
+ * Set version number for the given package name.
+ *
+ * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs'
+ * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev'
+ * @return {Ext}
+ */
+ setVersion: function(packageName, version) {
+ Ext.versions[packageName] = new Version(version);
+ Ext.lastRegisteredVersion = Ext.versions[packageName];
+
+ return this;
+ },
+
+ /**
+ * Get the version number of the supplied package name; will return the last registered version
+ * (last Ext.setVersion call) if there's no package name given.
+ *
+ * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs'
+ * @return {Ext.Version} The version
+ */
+ getVersion: function(packageName) {
+ if (packageName === undefined) {
+ return Ext.lastRegisteredVersion;
+ }
+
+ return Ext.versions[packageName];
+ },
+
+ /**
+ * Create a closure for deprecated code.
+ *
+ * // This means Ext.oldMethod is only supported in 4.0.0beta and older.
+ * // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC',
+ * // the closure will not be invoked
+ * Ext.deprecate('extjs', '4.0.0beta', function() {
+ * Ext.oldMethod = Ext.newMethod;
+ *
+ * ...
+ * });
+ *
+ * @param {String} packageName The package name
+ * @param {String} since The last version before it's deprecated
+ * @param {Function} closure The callback function to be executed with the specified version is less than the current version
+ * @param {Object} scope The execution scope (`this`) if the closure
+ */
+ deprecate: function(packageName, since, closure, scope) {
+ if (Version.compare(Ext.getVersion(packageName), since) < 1) {
+ closure.call(scope);
+ }
+ }
+ }); // End Versioning
+
+ Ext.setVersion('core', version);
+
+}());
+
+//@tag foundation,core
+//@require ../version/Version.js
+
+/**
+ * @class Ext.String
+ *
+ * A collection of useful static methods to deal with strings
+ * @singleton
+ */
+
+Ext.String = (function() {
+ var trimRegex = /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g,
+ escapeRe = /('|\\)/g,
+ formatRe = /\{(\d+)\}/g,
+ escapeRegexRe = /([-.*+?\^${}()|\[\]\/\\])/g,
+ basicTrimRe = /^\s+|\s+$/g,
+ whitespaceRe = /\s+/,
+ varReplace = /(^[^a-z]*|[^\w])/gi,
+ charToEntity,
+ entityToChar,
+ charToEntityRegex,
+ entityToCharRegex,
+ htmlEncodeReplaceFn = function(match, capture) {
+ return charToEntity[capture];
+ },
+ htmlDecodeReplaceFn = function(match, capture) {
+ return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10));
+ };
+
+ return {
+
+ /**
+ * Converts a string of characters into a legal, parseable Javascript `var` name as long as the passed
+ * string contains at least one alphabetic character. Non alphanumeric characters, and *leading* non alphabetic
+ * characters will be removed.
+ * @param {String} s A string to be converted into a `var` name.
+ * @return {String} A legal Javascript `var` name.
+ */
+ createVarName: function(s) {
+ return s.replace(varReplace, '');
+ },
+
+ /**
+ * Convert certain characters (&, <, >, ', and ") to their HTML character equivalents for literal display in web pages.
+ * @param {String} value The string to encode
+ * @return {String} The encoded text
+ * @method
+ */
+ htmlEncode: function(value) {
+ return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn);
+ },
+
+ /**
+ * Convert certain characters (&, <, >, ', and ") from their HTML character equivalents.
+ * @param {String} value The string to decode
+ * @return {String} The decoded text
+ * @method
+ */
+ htmlDecode: function(value) {
+ return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn);
+ },
+
+ /**
+ * Adds a set of character entity definitions to the set used by
+ * {@link Ext.String#htmlEncode} and {@link Ext.String#htmlDecode}.
+ *
+ * This object should be keyed by the entity name sequence,
+ * with the value being the textual representation of the entity.
+ *
+ * Ext.String.addCharacterEntities({
+ * 'Ü':'Ü',
+ * 'ç':'ç',
+ * 'ñ':'ñ',
+ * 'è':'è'
+ * });
+ * var s = Ext.String.htmlEncode("A string with entities: èÜçñ");
+ *
+ * Note: the values of the character entites defined on this object are expected
+ * to be single character values. As such, the actual values represented by the
+ * characters are sensitive to the character encoding of the javascript source
+ * file when defined in string literal form. Script tasgs referencing server
+ * resources with character entities must ensure that the 'charset' attribute
+ * of the script node is consistent with the actual character encoding of the
+ * server resource.
+ *
+ * The set of character entities may be reset back to the default state by using
+ * the {@link Ext.String#resetCharacterEntities} method
+ *
+ * @param {Object} entities The set of character entities to add to the current
+ * definitions.
+ */
+ addCharacterEntities: function(newEntities) {
+ var charKeys = [],
+ entityKeys = [],
+ key, echar;
+ for (key in newEntities) {
+ echar = newEntities[key];
+ entityToChar[key] = echar;
+ charToEntity[echar] = key;
+ charKeys.push(echar);
+ entityKeys.push(key);
+ }
+ charToEntityRegex = new RegExp('(' + charKeys.join('|') + ')', 'g');
+ entityToCharRegex = new RegExp('(' + entityKeys.join('|') + '|[0-9]{1,5};' + ')', 'g');
+ },
+
+ /**
+ * Resets the set of character entity definitions used by
+ * {@link Ext.String#htmlEncode} and {@link Ext.String#htmlDecode} back to the
+ * default state.
+ */
+ resetCharacterEntities: function() {
+ charToEntity = {};
+ entityToChar = {};
+ // add the default set
+ this.addCharacterEntities({
+ '&' : '&',
+ '>' : '>',
+ '<' : '<',
+ '"' : '"',
+ ''' : "'"
+ });
+ },
+
+ /**
+ * Appends content to the query string of a URL, handling logic for whether to place
+ * a question mark or ampersand.
+ * @param {String} url The URL to append to.
+ * @param {String} string The content to append to the URL.
+ * @return {String} The resulting URL
+ */
+ urlAppend : function(url, string) {
+ if (!Ext.isEmpty(string)) {
+ return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
+ }
+
+ return url;
+ },
+
+ /**
+ * Trims whitespace from either end of a string, leaving spaces within the string intact. Example:
+ * @example
+ var s = ' foo bar ';
+ alert('-' + s + '-'); //alerts "- foo bar -"
+ alert('-' + Ext.String.trim(s) + '-'); //alerts "-foo bar-"
+
+ * @param {String} string The string to escape
+ * @return {String} The trimmed string
+ */
+ trim: function(string) {
+ return string.replace(trimRegex, "");
+ },
+
+ /**
+ * Capitalize the given string
+ * @param {String} string
+ * @return {String}
+ */
+ capitalize: function(string) {
+ return string.charAt(0).toUpperCase() + string.substr(1);
+ },
+
+ /**
+ * Uncapitalize the given string
+ * @param {String} string
+ * @return {String}
+ */
+ uncapitalize: function(string) {
+ return string.charAt(0).toLowerCase() + string.substr(1);
+ },
+
+ /**
+ * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
+ * @param {String} value The string to truncate
+ * @param {Number} length The maximum length to allow before truncating
+ * @param {Boolean} word True to try to find a common word break
+ * @return {String} The converted text
+ */
+ ellipsis: function(value, len, word) {
+ if (value && value.length > len) {
+ if (word) {
+ var vs = value.substr(0, len - 2),
+ index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
+ if (index !== -1 && index >= (len - 15)) {
+ return vs.substr(0, index) + "...";
+ }
+ }
+ return value.substr(0, len - 3) + "...";
+ }
+ return value;
+ },
+
+ /**
+ * Escapes the passed string for use in a regular expression
+ * @param {String} string
+ * @return {String}
+ */
+ escapeRegex: function(string) {
+ return string.replace(escapeRegexRe, "\\$1");
+ },
+
+ /**
+ * Escapes the passed string for ' and \
+ * @param {String} string The string to escape
+ * @return {String} The escaped string
+ */
+ escape: function(string) {
+ return string.replace(escapeRe, "\\$1");
+ },
+
+ /**
+ * Utility function that allows you to easily switch a string between two alternating values. The passed value
+ * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
+ * they are already different, the first value passed in is returned. Note that this method returns the new value
+ * but does not change the current string.
+ *
+ // alternate sort directions
+ sort = Ext.String.toggle(sort, 'ASC', 'DESC');
+
+ // instead of conditional logic:
+ sort = (sort == 'ASC' ? 'DESC' : 'ASC');
+
+ * @param {String} string The current string
+ * @param {String} value The value to compare to the current string
+ * @param {String} other The new value to use if the string already equals the first value passed in
+ * @return {String} The new value
+ */
+ toggle: function(string, value, other) {
+ return string === value ? other : value;
+ },
+
+ /**
+ * Pads the left side of a string with a specified character. This is especially useful
+ * for normalizing number and date strings. Example usage:
+ *
+ *
+ var s = Ext.String.leftPad('123', 5, '0');
+ // s now contains the string: '00123'
+
+ * @param {String} string The original string
+ * @param {Number} size The total length of the output string
+ * @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ")
+ * @return {String} The padded string
+ */
+ leftPad: function(string, size, character) {
+ var result = String(string);
+ character = character || " ";
+ while (result.length < size) {
+ result = character + result;
+ }
+ return result;
+ },
+
+ /**
+ * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
+ * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
+ *
+ var cls = 'my-class', text = 'Some text';
+ var s = Ext.String.format('<div class="{0}">{1}</div>', cls, text);
+ // s now contains the string: '<div class="my-class">Some text</div>'
+
+ * @param {String} string The tokenized string to be formatted
+ * @param {String} value1 The value to replace token {0}
+ * @param {String} value2 Etc...
+ * @return {String} The formatted string
+ */
+ format: function(format) {
+ var args = Ext.Array.toArray(arguments, 1);
+ return format.replace(formatRe, function(m, i) {
+ return args[i];
+ });
+ },
+
+ /**
+ * Returns a string with a specified number of repititions a given string pattern.
+ * The pattern be separated by a different string.
+ *
+ * var s = Ext.String.repeat('---', 4); // = '------------'
+ * var t = Ext.String.repeat('--', 3, '/'); // = '--/--/--'
+ *
+ * @param {String} pattern The pattern to repeat.
+ * @param {Number} count The number of times to repeat the pattern (may be 0).
+ * @param {String} sep An option string to separate each pattern.
+ */
+ repeat: function(pattern, count, sep) {
+ for (var buf = [], i = count; i--; ) {
+ buf.push(pattern);
+ }
+ return buf.join(sep || '');
+ },
+
+ /**
+ * Splits a string of space separated words into an array, trimming as needed. If the
+ * words are already an array, it is returned.
+ *
+ * @param {String/Array} words
+ */
+ splitWords: function (words) {
+ if (words && typeof words == 'string') {
+ return words.replace(basicTrimRe, '').split(whitespaceRe);
+ }
+ return words || [];
+ }
+ };
+}());
+
+// initialize the default encode / decode entities
+Ext.String.resetCharacterEntities();
+
+/**
+ * Old alias to {@link Ext.String#htmlEncode}
+ * @deprecated Use {@link Ext.String#htmlEncode} instead
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.String#htmlEncode
+ */
+Ext.htmlEncode = Ext.String.htmlEncode;
+
+
+/**
+ * Old alias to {@link Ext.String#htmlDecode}
+ * @deprecated Use {@link Ext.String#htmlDecode} instead
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.String#htmlDecode
+ */
+Ext.htmlDecode = Ext.String.htmlDecode;
+
+/**
+ * Old alias to {@link Ext.String#urlAppend}
+ * @deprecated Use {@link Ext.String#urlAppend} instead
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.String#urlAppend
+ */
+Ext.urlAppend = Ext.String.urlAppend;
+
+//@tag foundation,core
+//@require String.js
+//@define Ext.Number
+
+/**
+ * @class Ext.Number
+ *
+ * A collection of useful static methods to deal with numbers
+ * @singleton
+ */
+
+Ext.Number = new function() {
+
+ var me = this,
+ isToFixedBroken = (0.9).toFixed() !== '1',
+ math = Math;
+
+ Ext.apply(this, {
+ /**
+ * Checks whether or not the passed number is within a desired range. If the number is already within the
+ * range it is returned, otherwise the min or max value is returned depending on which side of the range is
+ * exceeded. Note that this method returns the constrained value but does not change the current number.
+ * @param {Number} number The number to check
+ * @param {Number} min The minimum number in the range
+ * @param {Number} max The maximum number in the range
+ * @return {Number} The constrained value if outside the range, otherwise the current value
+ */
+ constrain: function(number, min, max) {
+ var x = parseFloat(number);
+
+ // Watch out for NaN in Chrome 18
+ // V8bug: http://code.google.com/p/v8/issues/detail?id=2056
+
+ // Operators are faster than Math.min/max. See http://jsperf.com/number-constrain
+ // ... and (x < Nan) || (x < undefined) == false
+ // ... same for (x > NaN) || (x > undefined)
+ // so if min or max are undefined or NaN, we never return them... sadly, this
+ // is not true of null (but even Math.max(-1,null)==0 and isNaN(null)==false)
+ return (x < min) ? min : ((x > max) ? max : x);
+ },
+
+ /**
+ * Snaps the passed number between stopping points based upon a passed increment value.
+ *
+ * The difference between this and {@link #snapInRange} is that {@link #snapInRange} uses the minValue
+ * when calculating snap points:
+ *
+ * r = Ext.Number.snap(56, 2, 55, 65); // Returns 56 - snap points are zero based
+ *
+ * r = Ext.Number.snapInRange(56, 2, 55, 65); // Returns 57 - snap points are based from minValue
+ *
+ * @param {Number} value The unsnapped value.
+ * @param {Number} increment The increment by which the value must move.
+ * @param {Number} minValue The minimum value to which the returned value must be constrained. Overrides the increment.
+ * @param {Number} maxValue The maximum value to which the returned value must be constrained. Overrides the increment.
+ * @return {Number} The value of the nearest snap target.
+ */
+ snap : function(value, increment, minValue, maxValue) {
+ var m;
+
+ // If no value passed, or minValue was passed and value is less than minValue (anything < undefined is false)
+ // Then use the minValue (or zero if the value was undefined)
+ if (value === undefined || value < minValue) {
+ return minValue || 0;
+ }
+
+ if (increment) {
+ m = value % increment;
+ if (m !== 0) {
+ value -= m;
+ if (m * 2 >= increment) {
+ value += increment;
+ } else if (m * 2 < -increment) {
+ value -= increment;
+ }
+ }
+ }
+ return me.constrain(value, minValue, maxValue);
+ },
+
+ /**
+ * Snaps the passed number between stopping points based upon a passed increment value.
+ *
+ * The difference between this and {@link #snap} is that {@link #snap} does not use the minValue
+ * when calculating snap points:
+ *
+ * r = Ext.Number.snap(56, 2, 55, 65); // Returns 56 - snap points are zero based
+ *
+ * r = Ext.Number.snapInRange(56, 2, 55, 65); // Returns 57 - snap points are based from minValue
+ *
+ * @param {Number} value The unsnapped value.
+ * @param {Number} increment The increment by which the value must move.
+ * @param {Number} [minValue=0] The minimum value to which the returned value must be constrained.
+ * @param {Number} [maxValue=Infinity] The maximum value to which the returned value must be constrained.
+ * @return {Number} The value of the nearest snap target.
+ */
+ snapInRange : function(value, increment, minValue, maxValue) {
+ var tween;
+
+ // default minValue to zero
+ minValue = (minValue || 0);
+
+ // If value is undefined, or less than minValue, use minValue
+ if (value === undefined || value < minValue) {
+ return minValue;
+ }
+
+ // Calculate how many snap points from the minValue the passed value is.
+ if (increment && (tween = ((value - minValue) % increment))) {
+ value -= tween;
+ tween *= 2;
+ if (tween >= increment) {
+ value += increment;
+ }
+ }
+
+ // If constraining within a maximum, ensure the maximum is on a snap point
+ if (maxValue !== undefined) {
+ if (value > (maxValue = me.snapInRange(maxValue, increment, minValue))) {
+ value = maxValue;
+ }
+ }
+
+ return value;
+ },
+
+ /**
+ * Formats a number using fixed-point notation
+ * @param {Number} value The number to format
+ * @param {Number} precision The number of digits to show after the decimal point
+ */
+ toFixed: isToFixedBroken ? function(value, precision) {
+ precision = precision || 0;
+ var pow = math.pow(10, precision);
+ return (math.round(value * pow) / pow).toFixed(precision);
+ } : function(value, precision) {
+ return value.toFixed(precision);
+ },
+
+ /**
+ * Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if
+ * it is not.
+
+ Ext.Number.from('1.23', 1); // returns 1.23
+ Ext.Number.from('abc', 1); // returns 1
+
+ * @param {Object} value
+ * @param {Number} defaultValue The value to return if the original value is non-numeric
+ * @return {Number} value, if numeric, defaultValue otherwise
+ */
+ from: function(value, defaultValue) {
+ if (isFinite(value)) {
+ value = parseFloat(value);
+ }
+
+ return !isNaN(value) ? value : defaultValue;
+ },
+
+ /**
+ * Returns a random integer between the specified range (inclusive)
+ * @param {Number} from Lowest value to return.
+ * @param {Number} to Highst value to return.
+ * @return {Number} A random integer within the specified range.
+ */
+ randomInt: function (from, to) {
+ return math.floor(math.random() * (to - from + 1) + from);
+ }
+ });
+
+ /**
+ * @deprecated 4.0.0 Please use {@link Ext.Number#from} instead.
+ * @member Ext
+ * @method num
+ * @inheritdoc Ext.Number#from
+ */
+ Ext.num = function() {
+ return me.from.apply(this, arguments);
+ };
+};
+
+//@tag foundation,core
+//@require Number.js
+
+/**
+ * @class Ext.Array
+ * @singleton
+ * @author Jacky Nguyen
+ * @docauthor Jacky Nguyen
+ *
+ * A set of useful static methods to deal with arrays; provide missing methods for older browsers.
+ */
+(function() {
+
+ var arrayPrototype = Array.prototype,
+ slice = arrayPrototype.slice,
+ supportsSplice = (function () {
+ var array = [],
+ lengthBefore,
+ j = 20;
+
+ if (!array.splice) {
+ return false;
+ }
+
+ // This detects a bug in IE8 splice method:
+ // see http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/6e946d03-e09f-4b22-a4dd-cd5e276bf05a/
+
+ while (j--) {
+ array.push("A");
+ }
+
+ array.splice(15, 0, "F", "F", "F", "F", "F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F");
+
+ lengthBefore = array.length; //41
+ array.splice(13, 0, "XXX"); // add one element
+
+ if (lengthBefore+1 != array.length) {
+ return false;
+ }
+ // end IE8 bug
+
+ return true;
+ }()),
+ supportsForEach = 'forEach' in arrayPrototype,
+ supportsMap = 'map' in arrayPrototype,
+ supportsIndexOf = 'indexOf' in arrayPrototype,
+ supportsEvery = 'every' in arrayPrototype,
+ supportsSome = 'some' in arrayPrototype,
+ supportsFilter = 'filter' in arrayPrototype,
+ supportsSort = (function() {
+ var a = [1,2,3,4,5].sort(function(){ return 0; });
+ return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
+ }()),
+ supportsSliceOnNodeList = true,
+ ExtArray,
+ erase,
+ replace,
+ splice;
+
+ try {
+ // IE 6 - 8 will throw an error when using Array.prototype.slice on NodeList
+ if (typeof document !== 'undefined') {
+ slice.call(document.getElementsByTagName('body'));
+ }
+ } catch (e) {
+ supportsSliceOnNodeList = false;
+ }
+
+ function fixArrayIndex (array, index) {
+ return (index < 0) ? Math.max(0, array.length + index)
+ : Math.min(array.length, index);
+ }
+
+ /*
+ Does the same work as splice, but with a slightly more convenient signature. The splice
+ method has bugs in IE8, so this is the implementation we use on that platform.
+
+ The rippling of items in the array can be tricky. Consider two use cases:
+
+ index=2
+ removeCount=2
+ /=====\
+ +---+---+---+---+---+---+---+---+
+ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
+ +---+---+---+---+---+---+---+---+
+ / \/ \/ \/ \
+ / /\ /\ /\ \
+ / / \/ \/ \ +--------------------------+
+ / / /\ /\ +--------------------------+ \
+ / / / \/ +--------------------------+ \ \
+ / / / /+--------------------------+ \ \ \
+ / / / / \ \ \ \
+ v v v v v v v v
+ +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
+ | 0 | 1 | 4 | 5 | 6 | 7 | | 0 | 1 | a | b | c | 4 | 5 | 6 | 7 |
+ +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+
+ A B \=========/
+ insert=[a,b,c]
+
+ In case A, it is obvious that copying of [4,5,6,7] must be left-to-right so
+ that we don't end up with [0,1,6,7,6,7]. In case B, we have the opposite; we
+ must go right-to-left or else we would end up with [0,1,a,b,c,4,4,4,4].
+ */
+ function replaceSim (array, index, removeCount, insert) {
+ var add = insert ? insert.length : 0,
+ length = array.length,
+ pos = fixArrayIndex(array, index),
+ remove,
+ tailOldPos,
+ tailNewPos,
+ tailCount,
+ lengthAfterRemove,
+ i;
+
+ // we try to use Array.push when we can for efficiency...
+ if (pos === length) {
+ if (add) {
+ array.push.apply(array, insert);
+ }
+ } else {
+ remove = Math.min(removeCount, length - pos);
+ tailOldPos = pos + remove;
+ tailNewPos = tailOldPos + add - remove;
+ tailCount = length - tailOldPos;
+ lengthAfterRemove = length - remove;
+
+ if (tailNewPos < tailOldPos) { // case A
+ for (i = 0; i < tailCount; ++i) {
+ array[tailNewPos+i] = array[tailOldPos+i];
+ }
+ } else if (tailNewPos > tailOldPos) { // case B
+ for (i = tailCount; i--; ) {
+ array[tailNewPos+i] = array[tailOldPos+i];
+ }
+ } // else, add == remove (nothing to do)
+
+ if (add && pos === lengthAfterRemove) {
+ array.length = lengthAfterRemove; // truncate array
+ array.push.apply(array, insert);
+ } else {
+ array.length = lengthAfterRemove + add; // reserves space
+ for (i = 0; i < add; ++i) {
+ array[pos+i] = insert[i];
+ }
+ }
+ }
+
+ return array;
+ }
+
+ function replaceNative (array, index, removeCount, insert) {
+ if (insert && insert.length) {
+ if (index < array.length) {
+ array.splice.apply(array, [index, removeCount].concat(insert));
+ } else {
+ array.push.apply(array, insert);
+ }
+ } else {
+ array.splice(index, removeCount);
+ }
+ return array;
+ }
+
+ function eraseSim (array, index, removeCount) {
+ return replaceSim(array, index, removeCount);
+ }
+
+ function eraseNative (array, index, removeCount) {
+ array.splice(index, removeCount);
+ return array;
+ }
+
+ function spliceSim (array, index, removeCount) {
+ var pos = fixArrayIndex(array, index),
+ removed = array.slice(index, fixArrayIndex(array, pos+removeCount));
+
+ if (arguments.length < 4) {
+ replaceSim(array, pos, removeCount);
+ } else {
+ replaceSim(array, pos, removeCount, slice.call(arguments, 3));
+ }
+
+ return removed;
+ }
+
+ function spliceNative (array) {
+ return array.splice.apply(array, slice.call(arguments, 1));
+ }
+
+ erase = supportsSplice ? eraseNative : eraseSim;
+ replace = supportsSplice ? replaceNative : replaceSim;
+ splice = supportsSplice ? spliceNative : spliceSim;
+
+ // NOTE: from here on, use erase, replace or splice (not native methods)...
+
+ ExtArray = Ext.Array = {
+ /**
+ * Iterates an array or an iterable value and invoke the given callback function for each item.
+ *
+ * var countries = ['Vietnam', 'Singapore', 'United States', 'Russia'];
+ *
+ * Ext.Array.each(countries, function(name, index, countriesItSelf) {
+ * console.log(name);
+ * });
+ *
+ * var sum = function() {
+ * var sum = 0;
+ *
+ * Ext.Array.each(arguments, function(value) {
+ * sum += value;
+ * });
+ *
+ * return sum;
+ * };
+ *
+ * sum(1, 2, 3); // returns 6
+ *
+ * The iteration can be stopped by returning false in the function callback.
+ *
+ * Ext.Array.each(countries, function(name, index, countriesItSelf) {
+ * if (name === 'Singapore') {
+ * return false; // break here
+ * }
+ * });
+ *
+ * {@link Ext#each Ext.each} is alias for {@link Ext.Array#each Ext.Array.each}
+ *
+ * @param {Array/NodeList/Object} iterable The value to be iterated. If this
+ * argument is not iterable, the callback function is called once.
+ * @param {Function} fn The callback function. If it returns false, the iteration stops and this method returns
+ * the current `index`.
+ * @param {Object} fn.item The item at the current `index` in the passed `array`
+ * @param {Number} fn.index The current `index` within the `array`
+ * @param {Array} fn.allItems The `array` itself which was passed as the first argument
+ * @param {Boolean} fn.return Return false to stop iteration.
+ * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
+ * @param {Boolean} reverse (Optional) Reverse the iteration order (loop from the end to the beginning)
+ * Defaults false
+ * @return {Boolean} See description for the `fn` parameter.
+ */
+ each: function(array, fn, scope, reverse) {
+ array = ExtArray.from(array);
+
+ var i,
+ ln = array.length;
+
+ if (reverse !== true) {
+ for (i = 0; i < ln; i++) {
+ if (fn.call(scope || array[i], array[i], i, array) === false) {
+ return i;
+ }
+ }
+ }
+ else {
+ for (i = ln - 1; i > -1; i--) {
+ if (fn.call(scope || array[i], array[i], i, array) === false) {
+ return i;
+ }
+ }
+ }
+
+ return true;
+ },
+
+ /**
+ * Iterates an array and invoke the given callback function for each item. Note that this will simply
+ * delegate to the native Array.prototype.forEach method if supported. It doesn't support stopping the
+ * iteration by returning false in the callback function like {@link Ext.Array#each}. However, performance
+ * could be much better in modern browsers comparing with {@link Ext.Array#each}
+ *
+ * @param {Array} array The array to iterate
+ * @param {Function} fn The callback function.
+ * @param {Object} fn.item The item at the current `index` in the passed `array`
+ * @param {Number} fn.index The current `index` within the `array`
+ * @param {Array} fn.allItems The `array` itself which was passed as the first argument
+ * @param {Object} scope (Optional) The execution scope (`this`) in which the specified function is executed.
+ */
+ forEach: supportsForEach ? function(array, fn, scope) {
+ return array.forEach(fn, scope);
+ } : function(array, fn, scope) {
+ var i = 0,
+ ln = array.length;
+
+ for (; i < ln; i++) {
+ fn.call(scope, array[i], i, array);
+ }
+ },
+
+ /**
+ * Get the index of the provided `item` in the given `array`, a supplement for the
+ * missing arrayPrototype.indexOf in Internet Explorer.
+ *
+ * @param {Array} array The array to check
+ * @param {Object} item The item to look for
+ * @param {Number} from (Optional) The index at which to begin the search
+ * @return {Number} The index of item in the array (or -1 if it is not found)
+ */
+ indexOf: supportsIndexOf ? function(array, item, from) {
+ return array.indexOf(item, from);
+ } : function(array, item, from) {
+ var i, length = array.length;
+
+ for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) {
+ if (array[i] === item) {
+ return i;
+ }
+ }
+
+ return -1;
+ },
+
+ /**
+ * Checks whether or not the given `array` contains the specified `item`
+ *
+ * @param {Array} array The array to check
+ * @param {Object} item The item to look for
+ * @return {Boolean} True if the array contains the item, false otherwise
+ */
+ contains: supportsIndexOf ? function(array, item) {
+ return array.indexOf(item) !== -1;
+ } : function(array, item) {
+ var i, ln;
+
+ for (i = 0, ln = array.length; i < ln; i++) {
+ if (array[i] === item) {
+ return true;
+ }
+ }
+
+ return false;
+ },
+
+ /**
+ * Converts any iterable (numeric indices and a length property) into a true array.
+ *
+ * function test() {
+ * var args = Ext.Array.toArray(arguments),
+ * fromSecondToLastArgs = Ext.Array.toArray(arguments, 1);
+ *
+ * alert(args.join(' '));
+ * alert(fromSecondToLastArgs.join(' '));
+ * }
+ *
+ * test('just', 'testing', 'here'); // alerts 'just testing here';
+ * // alerts 'testing here';
+ *
+ * Ext.Array.toArray(document.getElementsByTagName('div')); // will convert the NodeList into an array
+ * Ext.Array.toArray('splitted'); // returns ['s', 'p', 'l', 'i', 't', 't', 'e', 'd']
+ * Ext.Array.toArray('splitted', 0, 3); // returns ['s', 'p', 'l']
+ *
+ * {@link Ext#toArray Ext.toArray} is alias for {@link Ext.Array#toArray Ext.Array.toArray}
+ *
+ * @param {Object} iterable the iterable object to be turned into a true Array.
+ * @param {Number} start (Optional) a zero-based index that specifies the start of extraction. Defaults to 0
+ * @param {Number} end (Optional) a 1-based index that specifies the end of extraction. Defaults to the last
+ * index of the iterable value
+ * @return {Array} array
+ */
+ toArray: function(iterable, start, end){
+ if (!iterable || !iterable.length) {
+ return [];
+ }
+
+ if (typeof iterable === 'string') {
+ iterable = iterable.split('');
+ }
+
+ if (supportsSliceOnNodeList) {
+ return slice.call(iterable, start || 0, end || iterable.length);
+ }
+
+ var array = [],
+ i;
+
+ start = start || 0;
+ end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length;
+
+ for (i = start; i < end; i++) {
+ array.push(iterable[i]);
+ }
+
+ return array;
+ },
+
+ /**
+ * Plucks the value of a property from each item in the Array. Example:
+ *
+ * Ext.Array.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className]
+ *
+ * @param {Array/NodeList} array The Array of items to pluck the value from.
+ * @param {String} propertyName The property name to pluck from each element.
+ * @return {Array} The value from each item in the Array.
+ */
+ pluck: function(array, propertyName) {
+ var ret = [],
+ i, ln, item;
+
+ for (i = 0, ln = array.length; i < ln; i++) {
+ item = array[i];
+
+ ret.push(item[propertyName]);
+ }
+
+ return ret;
+ },
+
+ /**
+ * Creates a new array with the results of calling a provided function on every element in this array.
+ *
+ * @param {Array} array
+ * @param {Function} fn Callback function for each item
+ * @param {Object} scope Callback function scope
+ * @return {Array} results
+ */
+ map: supportsMap ? function(array, fn, scope) {
+ if (!fn) {
+ Ext.Error.raise('Ext.Array.map must have a callback function passed as second argument.');
+ }
+ return array.map(fn, scope);
+ } : function(array, fn, scope) {
+ if (!fn) {
+ Ext.Error.raise('Ext.Array.map must have a callback function passed as second argument.');
+ }
+ var results = [],
+ i = 0,
+ len = array.length;
+
+ for (; i < len; i++) {
+ results[i] = fn.call(scope, array[i], i, array);
+ }
+
+ return results;
+ },
+
+ /**
+ * Executes the specified function for each array element until the function returns a falsy value.
+ * If such an item is found, the function will return false immediately.
+ * Otherwise, it will return true.
+ *
+ * @param {Array} array
+ * @param {Function} fn Callback function for each item
+ * @param {Object} scope Callback function scope
+ * @return {Boolean} True if no false value is returned by the callback function.
+ */
+ every: supportsEvery ? function(array, fn, scope) {
+ if (!fn) {
+ Ext.Error.raise('Ext.Array.every must have a callback function passed as second argument.');
+ }
+ return array.every(fn, scope);
+ } : function(array, fn, scope) {
+ if (!fn) {
+ Ext.Error.raise('Ext.Array.every must have a callback function passed as second argument.');
+ }
+ var i = 0,
+ ln = array.length;
+
+ for (; i < ln; ++i) {
+ if (!fn.call(scope, array[i], i, array)) {
+ return false;
+ }
+ }
+
+ return true;
+ },
+
+ /**
+ * Executes the specified function for each array element until the function returns a truthy value.
+ * If such an item is found, the function will return true immediately. Otherwise, it will return false.
+ *
+ * @param {Array} array
+ * @param {Function} fn Callback function for each item
+ * @param {Object} scope Callback function scope
+ * @return {Boolean} True if the callback function returns a truthy value.
+ */
+ some: supportsSome ? function(array, fn, scope) {
+ if (!fn) {
+ Ext.Error.raise('Ext.Array.some must have a callback function passed as second argument.');
+ }
+ return array.some(fn, scope);
+ } : function(array, fn, scope) {
+ if (!fn) {
+ Ext.Error.raise('Ext.Array.some must have a callback function passed as second argument.');
+ }
+ var i = 0,
+ ln = array.length;
+
+ for (; i < ln; ++i) {
+ if (fn.call(scope, array[i], i, array)) {
+ return true;
+ }
+ }
+
+ return false;
+ },
+
+ /**
+ * Filter through an array and remove empty item as defined in {@link Ext#isEmpty Ext.isEmpty}
+ *
+ * See {@link Ext.Array#filter}
+ *
+ * @param {Array} array
+ * @return {Array} results
+ */
+ clean: function(array) {
+ var results = [],
+ i = 0,
+ ln = array.length,
+ item;
+
+ for (; i < ln; i++) {
+ item = array[i];
+
+ if (!Ext.isEmpty(item)) {
+ results.push(item);
+ }
+ }
+
+ return results;
+ },
+
+ /**
+ * Returns a new array with unique items
+ *
+ * @param {Array} array
+ * @return {Array} results
+ */
+ unique: function(array) {
+ var clone = [],
+ i = 0,
+ ln = array.length,
+ item;
+
+ for (; i < ln; i++) {
+ item = array[i];
+
+ if (ExtArray.indexOf(clone, item) === -1) {
+ clone.push(item);
+ }
+ }
+
+ return clone;
+ },
+
+ /**
+ * Creates a new array with all of the elements of this array for which
+ * the provided filtering function returns true.
+ *
+ * @param {Array} array
+ * @param {Function} fn Callback function for each item
+ * @param {Object} scope Callback function scope
+ * @return {Array} results
+ */
+ filter: supportsFilter ? function(array, fn, scope) {
+ if (!fn) {
+ Ext.Error.raise('Ext.Array.filter must have a callback function passed as second argument.');
+ }
+ return array.filter(fn, scope);
+ } : function(array, fn, scope) {
+ if (!fn) {
+ Ext.Error.raise('Ext.Array.filter must have a callback function passed as second argument.');
+ }
+ var results = [],
+ i = 0,
+ ln = array.length;
+
+ for (; i < ln; i++) {
+ if (fn.call(scope, array[i], i, array)) {
+ results.push(array[i]);
+ }
+ }
+
+ return results;
+ },
+
+ /**
+ * Converts a value to an array if it's not already an array; returns:
+ *
+ * - An empty array if given value is `undefined` or `null`
+ * - Itself if given value is already an array
+ * - An array copy if given value is {@link Ext#isIterable iterable} (arguments, NodeList and alike)
+ * - An array with one item which is the given value, otherwise
+ *
+ * @param {Object} value The value to convert to an array if it's not already is an array
+ * @param {Boolean} newReference (Optional) True to clone the given array and return a new reference if necessary,
+ * defaults to false
+ * @return {Array} array
+ */
+ from: function(value, newReference) {
+ if (value === undefined || value === null) {
+ return [];
+ }
+
+ if (Ext.isArray(value)) {
+ return (newReference) ? slice.call(value) : value;
+ }
+
+ var type = typeof value;
+ // Both strings and functions will have a length property. In phantomJS, NodeList
+ // instances report typeof=='function' but don't have an apply method...
+ if (value && value.length !== undefined && type !== 'string' && (type !== 'function' || !value.apply)) {
+ return ExtArray.toArray(value);
+ }
+
+ return [value];
+ },
+
+ /**
+ * Removes the specified item from the array if it exists
+ *
+ * @param {Array} array The array
+ * @param {Object} item The item to remove
+ * @return {Array} The passed array itself
+ */
+ remove: function(array, item) {
+ var index = ExtArray.indexOf(array, item);
+
+ if (index !== -1) {
+ erase(array, index, 1);
+ }
+
+ return array;
+ },
+
+ /**
+ * Push an item into the array only if the array doesn't contain it yet
+ *
+ * @param {Array} array The array
+ * @param {Object} item The item to include
+ */
+ include: function(array, item) {
+ if (!ExtArray.contains(array, item)) {
+ array.push(item);
+ }
+ },
+
+ /**
+ * Clone a flat array without referencing the previous one. Note that this is different
+ * from Ext.clone since it doesn't handle recursive cloning. It's simply a convenient, easy-to-remember method
+ * for Array.prototype.slice.call(array)
+ *
+ * @param {Array} array The array
+ * @return {Array} The clone array
+ */
+ clone: function(array) {
+ return slice.call(array);
+ },
+
+ /**
+ * Merge multiple arrays into one with unique items.
+ *
+ * {@link Ext.Array#union} is alias for {@link Ext.Array#merge}
+ *
+ * @param {Array} array1
+ * @param {Array} array2
+ * @param {Array} etc
+ * @return {Array} merged
+ */
+ merge: function() {
+ var args = slice.call(arguments),
+ array = [],
+ i, ln;
+
+ for (i = 0, ln = args.length; i < ln; i++) {
+ array = array.concat(args[i]);
+ }
+
+ return ExtArray.unique(array);
+ },
+
+ /**
+ * Merge multiple arrays into one with unique items that exist in all of the arrays.
+ *
+ * @param {Array} array1
+ * @param {Array} array2
+ * @param {Array} etc
+ * @return {Array} intersect
+ */
+ intersect: function() {
+ var intersection = [],
+ arrays = slice.call(arguments),
+ arraysLength,
+ array,
+ arrayLength,
+ minArray,
+ minArrayIndex,
+ minArrayCandidate,
+ minArrayLength,
+ element,
+ elementCandidate,
+ elementCount,
+ i, j, k;
+
+ if (!arrays.length) {
+ return intersection;
+ }
+
+ // Find the smallest array
+ arraysLength = arrays.length;
+ for (i = minArrayIndex = 0; i < arraysLength; i++) {
+ minArrayCandidate = arrays[i];
+ if (!minArray || minArrayCandidate.length < minArray.length) {
+ minArray = minArrayCandidate;
+ minArrayIndex = i;
+ }
+ }
+
+ minArray = ExtArray.unique(minArray);
+ erase(arrays, minArrayIndex, 1);
+
+ // Use the smallest unique'd array as the anchor loop. If the other array(s) do contain
+ // an item in the small array, we're likely to find it before reaching the end
+ // of the inner loop and can terminate the search early.
+ minArrayLength = minArray.length;
+ arraysLength = arrays.length;
+ for (i = 0; i < minArrayLength; i++) {
+ element = minArray[i];
+ elementCount = 0;
+
+ for (j = 0; j < arraysLength; j++) {
+ array = arrays[j];
+ arrayLength = array.length;
+ for (k = 0; k < arrayLength; k++) {
+ elementCandidate = array[k];
+ if (element === elementCandidate) {
+ elementCount++;
+ break;
+ }
+ }
+ }
+
+ if (elementCount === arraysLength) {
+ intersection.push(element);
+ }
+ }
+
+ return intersection;
+ },
+
+ /**
+ * Perform a set difference A-B by subtracting all items in array B from array A.
+ *
+ * @param {Array} arrayA
+ * @param {Array} arrayB
+ * @return {Array} difference
+ */
+ difference: function(arrayA, arrayB) {
+ var clone = slice.call(arrayA),
+ ln = clone.length,
+ i, j, lnB;
+
+ for (i = 0,lnB = arrayB.length; i < lnB; i++) {
+ for (j = 0; j < ln; j++) {
+ if (clone[j] === arrayB[i]) {
+ erase(clone, j, 1);
+ j--;
+ ln--;
+ }
+ }
+ }
+
+ return clone;
+ },
+
+ /**
+ * Returns a shallow copy of a part of an array. This is equivalent to the native
+ * call "Array.prototype.slice.call(array, begin, end)". This is often used when "array"
+ * is "arguments" since the arguments object does not supply a slice method but can
+ * be the context object to Array.prototype.slice.
+ *
+ * @param {Array} array The array (or arguments object).
+ * @param {Number} begin The index at which to begin. Negative values are offsets from
+ * the end of the array.
+ * @param {Number} end The index at which to end. The copied items do not include
+ * end. Negative values are offsets from the end of the array. If end is omitted,
+ * all items up to the end of the array are copied.
+ * @return {Array} The copied piece of the array.
+ * @method slice
+ */
+ // Note: IE6 will return [] on slice.call(x, undefined).
+ slice: ([1,2].slice(1, undefined).length ?
+ function (array, begin, end) {
+ return slice.call(array, begin, end);
+ } :
+ // at least IE6 uses arguments.length for variadic signature
+ function (array, begin, end) {
+ // After tested for IE 6, the one below is of the best performance
+ // see http://jsperf.com/slice-fix
+ if (typeof begin === 'undefined') {
+ return slice.call(array);
+ }
+ if (typeof end === 'undefined') {
+ return slice.call(array, begin);
+ }
+ return slice.call(array, begin, end);
+ }
+ ),
+
+ /**
+ * Sorts the elements of an Array.
+ * By default, this method sorts the elements alphabetically and ascending.
+ *
+ * @param {Array} array The array to sort.
+ * @param {Function} sortFn (optional) The comparison function.
+ * @return {Array} The sorted array.
+ */
+ sort: supportsSort ? function(array, sortFn) {
+ if (sortFn) {
+ return array.sort(sortFn);
+ } else {
+ return array.sort();
+ }
+ } : function(array, sortFn) {
+ var length = array.length,
+ i = 0,
+ comparison,
+ j, min, tmp;
+
+ for (; i < length; i++) {
+ min = i;
+ for (j = i + 1; j < length; j++) {
+ if (sortFn) {
+ comparison = sortFn(array[j], array[min]);
+ if (comparison < 0) {
+ min = j;
+ }
+ } else if (array[j] < array[min]) {
+ min = j;
+ }
+ }
+ if (min !== i) {
+ tmp = array[i];
+ array[i] = array[min];
+ array[min] = tmp;
+ }
+ }
+
+ return array;
+ },
+
+ /**
+ * Recursively flattens into 1-d Array. Injects Arrays inline.
+ *
+ * @param {Array} array The array to flatten
+ * @return {Array} The 1-d array.
+ */
+ flatten: function(array) {
+ var worker = [];
+
+ function rFlatten(a) {
+ var i, ln, v;
+
+ for (i = 0, ln = a.length; i < ln; i++) {
+ v = a[i];
+
+ if (Ext.isArray(v)) {
+ rFlatten(v);
+ } else {
+ worker.push(v);
+ }
+ }
+
+ return worker;
+ }
+
+ return rFlatten(array);
+ },
+
+ /**
+ * Returns the minimum value in the Array.
+ *
+ * @param {Array/NodeList} array The Array from which to select the minimum value.
+ * @param {Function} comparisonFn (optional) a function to perform the comparision which determines minimization.
+ * If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1
+ * @return {Object} minValue The minimum value
+ */
+ min: function(array, comparisonFn) {
+ var min = array[0],
+ i, ln, item;
+
+ for (i = 0, ln = array.length; i < ln; i++) {
+ item = array[i];
+
+ if (comparisonFn) {
+ if (comparisonFn(min, item) === 1) {
+ min = item;
+ }
+ }
+ else {
+ if (item < min) {
+ min = item;
+ }
+ }
+ }
+
+ return min;
+ },
+
+ /**
+ * Returns the maximum value in the Array.
+ *
+ * @param {Array/NodeList} array The Array from which to select the maximum value.
+ * @param {Function} comparisonFn (optional) a function to perform the comparision which determines maximization.
+ * If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1
+ * @return {Object} maxValue The maximum value
+ */
+ max: function(array, comparisonFn) {
+ var max = array[0],
+ i, ln, item;
+
+ for (i = 0, ln = array.length; i < ln; i++) {
+ item = array[i];
+
+ if (comparisonFn) {
+ if (comparisonFn(max, item) === -1) {
+ max = item;
+ }
+ }
+ else {
+ if (item > max) {
+ max = item;
+ }
+ }
+ }
+
+ return max;
+ },
+
+ /**
+ * Calculates the mean of all items in the array.
+ *
+ * @param {Array} array The Array to calculate the mean value of.
+ * @return {Number} The mean.
+ */
+ mean: function(array) {
+ return array.length > 0 ? ExtArray.sum(array) / array.length : undefined;
+ },
+
+ /**
+ * Calculates the sum of all items in the given array.
+ *
+ * @param {Array} array The Array to calculate the sum value of.
+ * @return {Number} The sum.
+ */
+ sum: function(array) {
+ var sum = 0,
+ i, ln, item;
+
+ for (i = 0,ln = array.length; i < ln; i++) {
+ item = array[i];
+
+ sum += item;
+ }
+
+ return sum;
+ },
+
+ /**
+ * Creates a map (object) keyed by the elements of the given array. The values in
+ * the map are the index+1 of the array element. For example:
+ *
+ * var map = Ext.Array.toMap(['a','b','c']);
+ *
+ * // map = { a: 1, b: 2, c: 3 };
+ *
+ * Or a key property can be specified:
+ *
+ * var map = Ext.Array.toMap([
+ * { name: 'a' },
+ * { name: 'b' },
+ * { name: 'c' }
+ * ], 'name');
+ *
+ * // map = { a: 1, b: 2, c: 3 };
+ *
+ * Lastly, a key extractor can be provided:
+ *
+ * var map = Ext.Array.toMap([
+ * { name: 'a' },
+ * { name: 'b' },
+ * { name: 'c' }
+ * ], function (obj) { return obj.name.toUpperCase(); });
+ *
+ * // map = { A: 1, B: 2, C: 3 };
+ */
+ toMap: function(array, getKey, scope) {
+ var map = {},
+ i = array.length;
+
+ if (!getKey) {
+ while (i--) {
+ map[array[i]] = i+1;
+ }
+ } else if (typeof getKey == 'string') {
+ while (i--) {
+ map[array[i][getKey]] = i+1;
+ }
+ } else {
+ while (i--) {
+ map[getKey.call(scope, array[i])] = i+1;
+ }
+ }
+
+ return map;
+ },
+
+ _replaceSim: replaceSim, // for unit testing
+ _spliceSim: spliceSim,
+
+ /**
+ * Removes items from an array. This is functionally equivalent to the splice method
+ * of Array, but works around bugs in IE8's splice method and does not copy the
+ * removed elements in order to return them (because very often they are ignored).
+ *
+ * @param {Array} array The Array on which to replace.
+ * @param {Number} index The index in the array at which to operate.
+ * @param {Number} removeCount The number of items to remove at index.
+ * @return {Array} The array passed.
+ * @method
+ */
+ erase: erase,
+
+ /**
+ * Inserts items in to an array.
+ *
+ * @param {Array} array The Array in which to insert.
+ * @param {Number} index The index in the array at which to operate.
+ * @param {Array} items The array of items to insert at index.
+ * @return {Array} The array passed.
+ */
+ insert: function (array, index, items) {
+ return replace(array, index, 0, items);
+ },
+
+ /**
+ * Replaces items in an array. This is functionally equivalent to the splice method
+ * of Array, but works around bugs in IE8's splice method and is often more convenient
+ * to call because it accepts an array of items to insert rather than use a variadic
+ * argument list.
+ *
+ * @param {Array} array The Array on which to replace.
+ * @param {Number} index The index in the array at which to operate.
+ * @param {Number} removeCount The number of items to remove at index (can be 0).
+ * @param {Array} insert (optional) An array of items to insert at index.
+ * @return {Array} The array passed.
+ * @method
+ */
+ replace: replace,
+
+ /**
+ * Replaces items in an array. This is equivalent to the splice method of Array, but
+ * works around bugs in IE8's splice method. The signature is exactly the same as the
+ * splice method except that the array is the first argument. All arguments following
+ * removeCount are inserted in the array at index.
+ *
+ * @param {Array} array The Array on which to replace.
+ * @param {Number} index The index in the array at which to operate.
+ * @param {Number} removeCount The number of items to remove at index (can be 0).
+ * @param {Object...} elements The elements to add to the array. If you don't specify
+ * any elements, splice simply removes elements from the array.
+ * @return {Array} An array containing the removed items.
+ * @method
+ */
+ splice: splice,
+
+ /**
+ * Pushes new items onto the end of an Array.
+ *
+ * Passed parameters may be single items, or arrays of items. If an Array is found in the argument list, all its
+ * elements are pushed into the end of the target Array.
+ *
+ * @param {Array} target The Array onto which to push new items
+ * @param {Object...} elements The elements to add to the array. Each parameter may
+ * be an Array, in which case all the elements of that Array will be pushed into the end of the
+ * destination Array.
+ * @return {Array} An array containing all the new items push onto the end.
+ *
+ */
+ push: function(array) {
+ var len = arguments.length,
+ i = 1,
+ newItem;
+
+ if (array === undefined) {
+ array = [];
+ } else if (!Ext.isArray(array)) {
+ array = [array];
+ }
+ for (; i < len; i++) {
+ newItem = arguments[i];
+ Array.prototype.push[Ext.isArray(newItem) ? 'apply' : 'call'](array, newItem);
+ }
+ return array;
+ }
+ };
+
+ /**
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Array#each
+ */
+ Ext.each = ExtArray.each;
+
+ /**
+ * @method
+ * @member Ext.Array
+ * @inheritdoc Ext.Array#merge
+ */
+ ExtArray.union = ExtArray.merge;
+
+ /**
+ * Old alias to {@link Ext.Array#min}
+ * @deprecated 4.0.0 Use {@link Ext.Array#min} instead
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Array#min
+ */
+ Ext.min = ExtArray.min;
+
+ /**
+ * Old alias to {@link Ext.Array#max}
+ * @deprecated 4.0.0 Use {@link Ext.Array#max} instead
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Array#max
+ */
+ Ext.max = ExtArray.max;
+
+ /**
+ * Old alias to {@link Ext.Array#sum}
+ * @deprecated 4.0.0 Use {@link Ext.Array#sum} instead
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Array#sum
+ */
+ Ext.sum = ExtArray.sum;
+
+ /**
+ * Old alias to {@link Ext.Array#mean}
+ * @deprecated 4.0.0 Use {@link Ext.Array#mean} instead
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Array#mean
+ */
+ Ext.mean = ExtArray.mean;
+
+ /**
+ * Old alias to {@link Ext.Array#flatten}
+ * @deprecated 4.0.0 Use {@link Ext.Array#flatten} instead
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Array#flatten
+ */
+ Ext.flatten = ExtArray.flatten;
+
+ /**
+ * Old alias to {@link Ext.Array#clean}
+ * @deprecated 4.0.0 Use {@link Ext.Array#clean} instead
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Array#clean
+ */
+ Ext.clean = ExtArray.clean;
+
+ /**
+ * Old alias to {@link Ext.Array#unique}
+ * @deprecated 4.0.0 Use {@link Ext.Array#unique} instead
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Array#unique
+ */
+ Ext.unique = ExtArray.unique;
+
+ /**
+ * Old alias to {@link Ext.Array#pluck Ext.Array.pluck}
+ * @deprecated 4.0.0 Use {@link Ext.Array#pluck Ext.Array.pluck} instead
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Array#pluck
+ */
+ Ext.pluck = ExtArray.pluck;
+
+ /**
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Array#toArray
+ */
+ Ext.toArray = function() {
+ return ExtArray.toArray.apply(ExtArray, arguments);
+ };
+}());
+
+//@tag foundation,core
+//@require Array.js
+
+/**
+ * @class Ext.Function
+ *
+ * A collection of useful static methods to deal with function callbacks
+ * @singleton
+ * @alternateClassName Ext.util.Functions
+ */
+Ext.Function = {
+
+ /**
+ * A very commonly used method throughout the framework. It acts as a wrapper around another method
+ * which originally accepts 2 arguments for `name` and `value`.
+ * The wrapped function then allows "flexible" value setting of either:
+ *
+ * - `name` and `value` as 2 arguments
+ * - one single object argument with multiple key - value pairs
+ *
+ * For example:
+ *
+ * var setValue = Ext.Function.flexSetter(function(name, value) {
+ * this[name] = value;
+ * });
+ *
+ * // Afterwards
+ * // Setting a single name - value
+ * setValue('name1', 'value1');
+ *
+ * // Settings multiple name - value pairs
+ * setValue({
+ * name1: 'value1',
+ * name2: 'value2',
+ * name3: 'value3'
+ * });
+ *
+ * @param {Function} setter
+ * @returns {Function} flexSetter
+ */
+ flexSetter: function(fn) {
+ return function(a, b) {
+ var k, i;
+
+ if (a === null) {
+ return this;
+ }
+
+ if (typeof a !== 'string') {
+ for (k in a) {
+ if (a.hasOwnProperty(k)) {
+ fn.call(this, k, a[k]);
+ }
+ }
+
+ if (Ext.enumerables) {
+ for (i = Ext.enumerables.length; i--;) {
+ k = Ext.enumerables[i];
+ if (a.hasOwnProperty(k)) {
+ fn.call(this, k, a[k]);
+ }
+ }
+ }
+ } else {
+ fn.call(this, a, b);
+ }
+
+ return this;
+ };
+ },
+
+ /**
+ * Create a new function from the provided `fn`, change `this` to the provided scope, optionally
+ * overrides arguments for the call. (Defaults to the arguments passed by the caller)
+ *
+ * {@link Ext#bind Ext.bind} is alias for {@link Ext.Function#bind Ext.Function.bind}
+ *
+ * @param {Function} fn The function to delegate.
+ * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
+ * **If omitted, defaults to the default global environment object (usually the browser window).**
+ * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
+ * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
+ * if a number the args are inserted at the specified position
+ * @return {Function} The new function
+ */
+ bind: function(fn, scope, args, appendArgs) {
+ if (arguments.length === 2) {
+ return function() {
+ return fn.apply(scope, arguments);
+ };
+ }
+
+ var method = fn,
+ slice = Array.prototype.slice;
+
+ return function() {
+ var callArgs = args || arguments;
+
+ if (appendArgs === true) {
+ callArgs = slice.call(arguments, 0);
+ callArgs = callArgs.concat(args);
+ }
+ else if (typeof appendArgs == 'number') {
+ callArgs = slice.call(arguments, 0); // copy arguments first
+ Ext.Array.insert(callArgs, appendArgs, args);
+ }
+
+ return method.apply(scope || Ext.global, callArgs);
+ };
+ },
+
+ /**
+ * Create a new function from the provided `fn`, the arguments of which are pre-set to `args`.
+ * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones.
+ * This is especially useful when creating callbacks.
+ *
+ * For example:
+ *
+ * var originalFunction = function(){
+ * alert(Ext.Array.from(arguments).join(' '));
+ * };
+ *
+ * var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']);
+ *
+ * callback(); // alerts 'Hello World'
+ * callback('by Me'); // alerts 'Hello World by Me'
+ *
+ * {@link Ext#pass Ext.pass} is alias for {@link Ext.Function#pass Ext.Function.pass}
+ *
+ * @param {Function} fn The original function
+ * @param {Array} args The arguments to pass to new callback
+ * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
+ * @return {Function} The new callback function
+ */
+ pass: function(fn, args, scope) {
+ if (!Ext.isArray(args)) {
+ if (Ext.isIterable(args)) {
+ args = Ext.Array.clone(args);
+ } else {
+ args = args !== undefined ? [args] : [];
+ }
+ }
+
+ return function() {
+ var fnArgs = [].concat(args);
+ fnArgs.push.apply(fnArgs, arguments);
+ return fn.apply(scope || this, fnArgs);
+ };
+ },
+
+ /**
+ * Create an alias to the provided method property with name `methodName` of `object`.
+ * Note that the execution scope will still be bound to the provided `object` itself.
+ *
+ * @param {Object/Function} object
+ * @param {String} methodName
+ * @return {Function} aliasFn
+ */
+ alias: function(object, methodName) {
+ return function() {
+ return object[methodName].apply(object, arguments);
+ };
+ },
+
+ /**
+ * Create a "clone" of the provided method. The returned method will call the given
+ * method passing along all arguments and the "this" pointer and return its result.
+ *
+ * @param {Function} method
+ * @return {Function} cloneFn
+ */
+ clone: function(method) {
+ return function() {
+ return method.apply(this, arguments);
+ };
+ },
+
+ /**
+ * Creates an interceptor function. The passed function is called before the original one. If it returns false,
+ * the original one is not called. The resulting function returns the results of the original function.
+ * The passed function is called with the parameters of the original function. Example usage:
+ *
+ * var sayHi = function(name){
+ * alert('Hi, ' + name);
+ * }
+ *
+ * sayHi('Fred'); // alerts "Hi, Fred"
+ *
+ * // create a new function that validates input without
+ * // directly modifying the original function:
+ * var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){
+ * return name == 'Brian';
+ * });
+ *
+ * sayHiToFriend('Fred'); // no alert
+ * sayHiToFriend('Brian'); // alerts "Hi, Brian"
+ *
+ * @param {Function} origFn The original function.
+ * @param {Function} newFn The function to call before the original
+ * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
+ * **If omitted, defaults to the scope in which the original function is called or the browser window.**
+ * @param {Object} returnValue (optional) The value to return if the passed function return false (defaults to null).
+ * @return {Function} The new function
+ */
+ createInterceptor: function(origFn, newFn, scope, returnValue) {
+ var method = origFn;
+ if (!Ext.isFunction(newFn)) {
+ return origFn;
+ }
+ else {
+ return function() {
+ var me = this,
+ args = arguments;
+ newFn.target = me;
+ newFn.method = origFn;
+ return (newFn.apply(scope || me || Ext.global, args) !== false) ? origFn.apply(me || Ext.global, args) : returnValue || null;
+ };
+ }
+ },
+
+ /**
+ * Creates a delegate (callback) which, when called, executes after a specific delay.
+ *
+ * @param {Function} fn The function which will be called on a delay when the returned function is called.
+ * Optionally, a replacement (or additional) argument list may be specified.
+ * @param {Number} delay The number of milliseconds to defer execution by whenever called.
+ * @param {Object} scope (optional) The scope (`this` reference) used by the function at execution time.
+ * @param {Array} args (optional) Override arguments for the call. (Defaults to the arguments passed by the caller)
+ * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
+ * if a number the args are inserted at the specified position.
+ * @return {Function} A function which, when called, executes the original function after the specified delay.
+ */
+ createDelayed: function(fn, delay, scope, args, appendArgs) {
+ if (scope || args) {
+ fn = Ext.Function.bind(fn, scope, args, appendArgs);
+ }
+
+ return function() {
+ var me = this,
+ args = Array.prototype.slice.call(arguments);
+
+ setTimeout(function() {
+ fn.apply(me, args);
+ }, delay);
+ };
+ },
+
+ /**
+ * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
+ *
+ * var sayHi = function(name){
+ * alert('Hi, ' + name);
+ * }
+ *
+ * // executes immediately:
+ * sayHi('Fred');
+ *
+ * // executes after 2 seconds:
+ * Ext.Function.defer(sayHi, 2000, this, ['Fred']);
+ *
+ * // this syntax is sometimes useful for deferring
+ * // execution of an anonymous function:
+ * Ext.Function.defer(function(){
+ * alert('Anonymous');
+ * }, 100);
+ *
+ * {@link Ext#defer Ext.defer} is alias for {@link Ext.Function#defer Ext.Function.defer}
+ *
+ * @param {Function} fn The function to defer.
+ * @param {Number} millis The number of milliseconds for the setTimeout call
+ * (if less than or equal to 0 the function is executed immediately)
+ * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed.
+ * **If omitted, defaults to the browser window.**
+ * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
+ * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
+ * if a number the args are inserted at the specified position
+ * @return {Number} The timeout id that can be used with clearTimeout
+ */
+ defer: function(fn, millis, scope, args, appendArgs) {
+ fn = Ext.Function.bind(fn, scope, args, appendArgs);
+ if (millis > 0) {
+ return setTimeout(Ext.supports.TimeoutActualLateness ? function () {
+ fn();
+ } : fn, millis);
+ }
+ fn();
+ return 0;
+ },
+
+ /**
+ * Create a combined function call sequence of the original function + the passed function.
+ * The resulting function returns the results of the original function.
+ * The passed function is called with the parameters of the original function. Example usage:
+ *
+ * var sayHi = function(name){
+ * alert('Hi, ' + name);
+ * }
+ *
+ * sayHi('Fred'); // alerts "Hi, Fred"
+ *
+ * var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){
+ * alert('Bye, ' + name);
+ * });
+ *
+ * sayGoodbye('Fred'); // both alerts show
+ *
+ * @param {Function} originalFn The original function.
+ * @param {Function} newFn The function to sequence
+ * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed.
+ * If omitted, defaults to the scope in which the original function is called or the default global environment object (usually the browser window).
+ * @return {Function} The new function
+ */
+ createSequence: function(originalFn, newFn, scope) {
+ if (!newFn) {
+ return originalFn;
+ }
+ else {
+ return function() {
+ var result = originalFn.apply(this, arguments);
+ newFn.apply(scope || this, arguments);
+ return result;
+ };
+ }
+ },
+
+ /**
+ * Creates a delegate function, optionally with a bound scope which, when called, buffers
+ * the execution of the passed function for the configured number of milliseconds.
+ * If called again within that period, the impending invocation will be canceled, and the
+ * timeout period will begin again.
+ *
+ * @param {Function} fn The function to invoke on a buffered timer.
+ * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the
+ * function.
+ * @param {Object} scope (optional) The scope (`this` reference) in which
+ * the passed function is executed. If omitted, defaults to the scope specified by the caller.
+ * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments
+ * passed by the caller.
+ * @return {Function} A function which invokes the passed function after buffering for the specified time.
+ */
+ createBuffered: function(fn, buffer, scope, args) {
+ var timerId;
+
+ return function() {
+ var callArgs = args || Array.prototype.slice.call(arguments, 0),
+ me = scope || this;
+
+ if (timerId) {
+ clearTimeout(timerId);
+ }
+
+ timerId = setTimeout(function(){
+ fn.apply(me, callArgs);
+ }, buffer);
+ };
+ },
+
+ /**
+ * Creates a throttled version of the passed function which, when called repeatedly and
+ * rapidly, invokes the passed function only after a certain interval has elapsed since the
+ * previous invocation.
+ *
+ * This is useful for wrapping functions which may be called repeatedly, such as
+ * a handler of a mouse move event when the processing is expensive.
+ *
+ * @param {Function} fn The function to execute at a regular time interval.
+ * @param {Number} interval The interval **in milliseconds** on which the passed function is executed.
+ * @param {Object} scope (optional) The scope (`this` reference) in which
+ * the passed function is executed. If omitted, defaults to the scope specified by the caller.
+ * @returns {Function} A function which invokes the passed function at the specified interval.
+ */
+ createThrottled: function(fn, interval, scope) {
+ var lastCallTime, elapsed, lastArgs, timer, execute = function() {
+ fn.apply(scope || this, lastArgs);
+ lastCallTime = new Date().getTime();
+ };
+
+ return function() {
+ elapsed = new Date().getTime() - lastCallTime;
+ lastArgs = arguments;
+
+ clearTimeout(timer);
+ if (!lastCallTime || (elapsed >= interval)) {
+ execute();
+ } else {
+ timer = setTimeout(execute, interval - elapsed);
+ }
+ };
+ },
+
+
+ /**
+ * Adds behavior to an existing method that is executed before the
+ * original behavior of the function. For example:
+ *
+ * var soup = {
+ * contents: [],
+ * add: function(ingredient) {
+ * this.contents.push(ingredient);
+ * }
+ * };
+ * Ext.Function.interceptBefore(soup, "add", function(ingredient){
+ * if (!this.contents.length && ingredient !== "water") {
+ * // Always add water to start with
+ * this.contents.push("water");
+ * }
+ * });
+ * soup.add("onions");
+ * soup.add("salt");
+ * soup.contents; // will contain: water, onions, salt
+ *
+ * @param {Object} object The target object
+ * @param {String} methodName Name of the method to override
+ * @param {Function} fn Function with the new behavior. It will
+ * be called with the same arguments as the original method. The
+ * return value of this function will be the return value of the
+ * new method.
+ * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object.
+ * @return {Function} The new function just created.
+ */
+ interceptBefore: function(object, methodName, fn, scope) {
+ var method = object[methodName] || Ext.emptyFn;
+
+ return (object[methodName] = function() {
+ var ret = fn.apply(scope || this, arguments);
+ method.apply(this, arguments);
+
+ return ret;
+ });
+ },
+
+ /**
+ * Adds behavior to an existing method that is executed after the
+ * original behavior of the function. For example:
+ *
+ * var soup = {
+ * contents: [],
+ * add: function(ingredient) {
+ * this.contents.push(ingredient);
+ * }
+ * };
+ * Ext.Function.interceptAfter(soup, "add", function(ingredient){
+ * // Always add a bit of extra salt
+ * this.contents.push("salt");
+ * });
+ * soup.add("water");
+ * soup.add("onions");
+ * soup.contents; // will contain: water, salt, onions, salt
+ *
+ * @param {Object} object The target object
+ * @param {String} methodName Name of the method to override
+ * @param {Function} fn Function with the new behavior. It will
+ * be called with the same arguments as the original method. The
+ * return value of this function will be the return value of the
+ * new method.
+ * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object.
+ * @return {Function} The new function just created.
+ */
+ interceptAfter: function(object, methodName, fn, scope) {
+ var method = object[methodName] || Ext.emptyFn;
+
+ return (object[methodName] = function() {
+ method.apply(this, arguments);
+ return fn.apply(scope || this, arguments);
+ });
+ }
+};
+
+/**
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Function#defer
+ */
+Ext.defer = Ext.Function.alias(Ext.Function, 'defer');
+
+/**
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Function#pass
+ */
+Ext.pass = Ext.Function.alias(Ext.Function, 'pass');
+
+/**
+ * @method
+ * @member Ext
+ * @inheritdoc Ext.Function#bind
+ */
+Ext.bind = Ext.Function.alias(Ext.Function, 'bind');
+
+//@tag foundation,core
+//@require Function.js
+
+/**
+ * @author Jacky Nguyen
+ * @docauthor Jacky Nguyen
+ * @class Ext.Object
+ *
+ * A collection of useful static methods to deal with objects.
+ *
+ * @singleton
+ */
+
+(function() {
+
+// The "constructor" for chain:
+var TemplateClass = function(){},
+ ExtObject = Ext.Object = {
+
+ /**
+ * Returns a new object with the given object as the prototype chain.
+ * @param {Object} object The prototype chain for the new object.
+ */
+ chain: function (object) {
+ TemplateClass.prototype = object;
+ var result = new TemplateClass();
+ TemplateClass.prototype = null;
+ return result;
+ },
+
+ /**
+ * Converts a `name` - `value` pair to an array of objects with support for nested structures. Useful to construct
+ * query strings. For example:
+ *
+ * var objects = Ext.Object.toQueryObjects('hobbies', ['reading', 'cooking', 'swimming']);
+ *
+ * // objects then equals:
+ * [
+ * { name: 'hobbies', value: 'reading' },
+ * { name: 'hobbies', value: 'cooking' },
+ * { name: 'hobbies', value: 'swimming' },
+ * ];
+ *
+ * var objects = Ext.Object.toQueryObjects('dateOfBirth', {
+ * day: 3,
+ * month: 8,
+ * year: 1987,
+ * extra: {
+ * hour: 4
+ * minute: 30
+ * }
+ * }, true); // Recursive
+ *
+ * // objects then equals:
+ * [
+ * { name: 'dateOfBirth[day]', value: 3 },
+ * { name: 'dateOfBirth[month]', value: 8 },
+ * { name: 'dateOfBirth[year]', value: 1987 },
+ * { name: 'dateOfBirth[extra][hour]', value: 4 },
+ * { name: 'dateOfBirth[extra][minute]', value: 30 },
+ * ];
+ *
+ * @param {String} name
+ * @param {Object/Array} value
+ * @param {Boolean} [recursive=false] True to traverse object recursively
+ * @return {Array}
+ */
+ toQueryObjects: function(name, value, recursive) {
+ var self = ExtObject.toQueryObjects,
+ objects = [],
+ i, ln;
+
+ if (Ext.isArray(value)) {
+ for (i = 0, ln = value.length; i < ln; i++) {
+ if (recursive) {
+ objects = objects.concat(self(name + '[' + i + ']', value[i], true));
+ }
+ else {
+ objects.push({
+ name: name,
+ value: value[i]
+ });
+ }
+ }
+ }
+ else if (Ext.isObject(value)) {
+ for (i in value) {
+ if (value.hasOwnProperty(i)) {
+ if (recursive) {
+ objects = objects.concat(self(name + '[' + i + ']', value[i], true));
+ }
+ else {
+ objects.push({
+ name: name,
+ value: value[i]
+ });
+ }
+ }
+ }
+ }
+ else {
+ objects.push({
+ name: name,
+ value: value
+ });
+ }
+
+ return objects;
+ },
+
+ /**
+ * Takes an object and converts it to an encoded query string.
+ *
+ * Non-recursive:
+ *
+ * Ext.Object.toQueryString({foo: 1, bar: 2}); // returns "foo=1&bar=2"
+ * Ext.Object.toQueryString({foo: null, bar: 2}); // returns "foo=&bar=2"
+ * Ext.Object.toQueryString({'some price': '$300'}); // returns "some%20price=%24300"
+ * Ext.Object.toQueryString({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22"
+ * Ext.Object.toQueryString({colors: ['red', 'green', 'blue']}); // returns "colors=red&colors=green&colors=blue"
+ *
+ * Recursive:
+ *
+ * Ext.Object.toQueryString({
+ * username: 'Jacky',
+ * dateOfBirth: {
+ * day: 1,
+ * month: 2,
+ * year: 1911
+ * },
+ * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
+ * }, true); // returns the following string (broken down and url-decoded for ease of reading purpose):
+ * // username=Jacky
+ * // &dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911
+ * // &hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff
+ *
+ * @param {Object} object The object to encode
+ * @param {Boolean} [recursive=false] Whether or not to interpret the object in recursive format.
+ * (PHP / Ruby on Rails servers and similar).
+ * @return {String} queryString
+ */
+ toQueryString: function(object, recursive) {
+ var paramObjects = [],
+ params = [],
+ i, j, ln, paramObject, value;
+
+ for (i in object) {
+ if (object.hasOwnProperty(i)) {
+ paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive));
+ }
+ }
+
+ for (j = 0, ln = paramObjects.length; j < ln; j++) {
+ paramObject = paramObjects[j];
+ value = paramObject.value;
+
+ if (Ext.isEmpty(value)) {
+ value = '';
+ }
+ else if (Ext.isDate(value)) {
+ value = Ext.Date.toString(value);
+ }
+
+ params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value)));
+ }
+
+ return params.join('&');
+ },
+
+ /**
+ * Converts a query string back into an object.
+ *
+ * Non-recursive:
+ *
+ * Ext.Object.fromQueryString("foo=1&bar=2"); // returns {foo: 1, bar: 2}
+ * Ext.Object.fromQueryString("foo=&bar=2"); // returns {foo: null, bar: 2}
+ * Ext.Object.fromQueryString("some%20price=%24300"); // returns {'some price': '$300'}
+ * Ext.Object.fromQueryString("colors=red&colors=green&colors=blue"); // returns {colors: ['red', 'green', 'blue']}
+ *
+ * Recursive:
+ *
+ * Ext.Object.fromQueryString(
+ * "username=Jacky&"+
+ * "dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911&"+
+ * "hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&"+
+ * "hobbies[3][0]=nested&hobbies[3][1]=stuff", true);
+ *
+ * // returns
+ * {
+ * username: 'Jacky',
+ * dateOfBirth: {
+ * day: '1',
+ * month: '2',
+ * year: '1911'
+ * },
+ * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
+ * }
+ *
+ * @param {String} queryString The query string to decode
+ * @param {Boolean} [recursive=false] Whether or not to recursively decode the string. This format is supported by
+ * PHP / Ruby on Rails servers and similar.
+ * @return {Object}
+ */
+ fromQueryString: function(queryString, recursive) {
+ var parts = queryString.replace(/^\?/, '').split('&'),
+ object = {},
+ temp, components, name, value, i, ln,
+ part, j, subLn, matchedKeys, matchedName,
+ keys, key, nextKey;
+
+ for (i = 0, ln = parts.length; i < ln; i++) {
+ part = parts[i];
+
+ if (part.length > 0) {
+ components = part.split('=');
+ name = decodeURIComponent(components[0]);
+ value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : '';
+
+ if (!recursive) {
+ if (object.hasOwnProperty(name)) {
+ if (!Ext.isArray(object[name])) {
+ object[name] = [object[name]];
+ }
+
+ object[name].push(value);
+ }
+ else {
+ object[name] = value;
+ }
+ }
+ else {
+ matchedKeys = name.match(/(\[):?([^\]]*)\]/g);
+ matchedName = name.match(/^([^\[]+)/);
+
+ if (!matchedName) {
+ throw new Error('[Ext.Object.fromQueryString] Malformed query string given, failed parsing name from "' + part + '"');
+ }
+
+ name = matchedName[0];
+ keys = [];
+
+ if (matchedKeys === null) {
+ object[name] = value;
+ continue;
+ }
+
+ for (j = 0, subLn = matchedKeys.length; j < subLn; j++) {
+ key = matchedKeys[j];
+ key = (key.length === 2) ? '' : key.substring(1, key.length - 1);
+ keys.push(key);
+ }
+
+ keys.unshift(name);
+
+ temp = object;
+
+ for (j = 0, subLn = keys.length; j < subLn; j++) {
+ key = keys[j];
+
+ if (j === subLn - 1) {
+ if (Ext.isArray(temp) && key === '') {
+ temp.push(value);
+ }
+ else {
+ temp[key] = value;
+ }
+ }
+ else {
+ if (temp[key] === undefined || typeof temp[key] === 'string') {
+ nextKey = keys[j+1];
+
+ temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {};
+ }
+
+ temp = temp[key];
+ }
+ }
+ }
+ }
+ }
+
+ return object;
+ },
+
+ /**
+ * Iterates through an object and invokes the given callback function for each iteration.
+ * The iteration can be stopped by returning `false` in the callback function. For example:
+ *
+ * var person = {
+ * name: 'Jacky'
+ * hairColor: 'black'
+ * loves: ['food', 'sleeping', 'wife']
+ * };
+ *
+ * Ext.Object.each(person, function(key, value, myself) {
+ * console.log(key + ":" + value);
+ *
+ * if (key === 'hairColor') {
+ * return false; // stop the iteration
+ * }
+ * });
+ *
+ * @param {Object} object The object to iterate
+ * @param {Function} fn The callback function.
+ * @param {String} fn.key
+ * @param {Object} fn.value
+ * @param {Object} fn.object The object itself
+ * @param {Object} [scope] The execution scope (`this`) of the callback function
+ */
+ each: function(object, fn, scope) {
+ for (var property in object) {
+ if (object.hasOwnProperty(property)) {
+ if (fn.call(scope || object, property, object[property], object) === false) {
+ return;
+ }
+ }
+ }
+ },
+
+ /**
+ * Merges any number of objects recursively without referencing them or their children.
+ *
+ * var extjs = {
+ * companyName: 'Ext JS',
+ * products: ['Ext JS', 'Ext GWT', 'Ext Designer'],
+ * isSuperCool: true,
+ * office: {
+ * size: 2000,
+ * location: 'Palo Alto',
+ * isFun: true
+ * }
+ * };
+ *
+ * var newStuff = {
+ * companyName: 'Sencha Inc.',
+ * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
+ * office: {
+ * size: 40000,
+ * location: 'Redwood City'
+ * }
+ * };
+ *
+ * var sencha = Ext.Object.merge(extjs, newStuff);
+ *
+ * // extjs and sencha then equals to
+ * {
+ * companyName: 'Sencha Inc.',
+ * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
+ * isSuperCool: true,
+ * office: {
+ * size: 40000,
+ * location: 'Redwood City',
+ * isFun: true
+ * }
+ * }
+ *
+ * @param {Object} destination The object into which all subsequent objects are merged.
+ * @param {Object...} object Any number of objects to merge into the destination.
+ * @return {Object} merged The destination object with all passed objects merged in.
+ */
+ merge: function(destination) {
+ var i = 1,
+ ln = arguments.length,
+ mergeFn = ExtObject.merge,
+ cloneFn = Ext.clone,
+ object, key, value, sourceKey;
+
+ for (; i < ln; i++) {
+ object = arguments[i];
+
+ for (key in object) {
+ value = object[key];
+ if (value && value.constructor === Object) {
+ sourceKey = destination[key];
+ if (sourceKey && sourceKey.constructor === Object) {
+ mergeFn(sourceKey, value);
+ }
+ else {
+ destination[key] = cloneFn(value);
+ }
+ }
+ else {
+ destination[key] = value;
+ }
+ }
+ }
+
+ return destination;
+ },
+
+ /**
+ * @private
+ * @param destination
+ */
+ mergeIf: function(destination) {
+ var i = 1,
+ ln = arguments.length,
+ cloneFn = Ext.clone,
+ object, key, value;
+
+ for (; i < ln; i++) {
+ object = arguments[i];
+
+ for (key in object) {
+ if (!(key in destination)) {
+ value = object[key];
+
+ if (value && value.constructor === Object) {
+ destination[key] = cloneFn(value);
+ }
+ else {
+ destination[key] = value;
+ }
+ }
+ }
+ }
+
+ return destination;
+ },
+
+ /**
+ * Returns the first matching key corresponding to the given value.
+ * If no matching value is found, null is returned.
+ *
+ * var person = {
+ * name: 'Jacky',
+ * loves: 'food'
+ * };
+ *
+ * alert(Ext.Object.getKey(person, 'food')); // alerts 'loves'
+ *
+ * @param {Object} object
+ * @param {Object} value The value to find
+ */
+ getKey: function(object, value) {
+ for (var property in object) {
+ if (object.hasOwnProperty(property) && object[property] === value) {
+ return property;
+ }
+ }
+
+ return null;
+ },
+
+ /**
+ * Gets all values of the given object as an array.
+ *
+ * var values = Ext.Object.getValues({
+ * name: 'Jacky',
+ * loves: 'food'
+ * }); // ['Jacky', 'food']
+ *
+ * @param {Object} object
+ * @return {Array} An array of values from the object
+ */
+ getValues: function(object) {
+ var values = [],
+ property;
+
+ for (property in object) {
+ if (object.hasOwnProperty(property)) {
+ values.push(object[property]);
+ }
+ }
+
+ return values;
+ },
+
+ /**
+ * Gets all keys of the given object as an array.
+ *
+ * var values = Ext.Object.getKeys({
+ * name: 'Jacky',
+ * loves: 'food'
+ * }); // ['name', 'loves']
+ *
+ * @param {Object} object
+ * @return {String[]} An array of keys from the object
+ * @method
+ */
+ getKeys: (typeof Object.keys == 'function')
+ ? function(object){
+ if (!object) {
+ return [];
+ }
+ return Object.keys(object);
+ }
+ : function(object) {
+ var keys = [],
+ property;
+
+ for (property in object) {
+ if (object.hasOwnProperty(property)) {
+ keys.push(property);
+ }
+ }
+
+ return keys;
+ },
+
+ /**
+ * Gets the total number of this object's own properties
+ *
+ * var size = Ext.Object.getSize({
+ * name: 'Jacky',
+ * loves: 'food'
+ * }); // size equals 2
+ *
+ * @param {Object} object
+ * @return {Number} size
+ */
+ getSize: function(object) {
+ var size = 0,
+ property;
+
+ for (property in object) {
+ if (object.hasOwnProperty(property)) {
+ size++;
+ }
+ }
+
+ return size;
+ },
+
+ /**
+ * @private
+ */
+ classify: function(object) {
+ var prototype = object,
+ objectProperties = [],
+ propertyClassesMap = {},
+ objectClass = function() {
+ var i = 0,
+ ln = objectProperties.length,
+ property;
+
+ for (; i < ln; i++) {
+ property = objectProperties[i];
+ this[property] = new propertyClassesMap[property]();
+ }
+ },
+ key, value;
+
+ for (key in object) {
+ if (object.hasOwnProperty(key)) {
+ value = object[key];
+
+ if (value && value.constructor === Object) {
+ objectProperties.push(key);
+ propertyClassesMap[key] = ExtObject.classify(value);
+ }
+ }
+ }
+
+ objectClass.prototype = prototype;
+
+ return objectClass;
+ }
+};
+
+/**
+ * A convenient alias method for {@link Ext.Object#merge}.
+ *
+ * @member Ext
+ * @method merge
+ * @inheritdoc Ext.Object#merge
+ */
+Ext.merge = Ext.Object.merge;
+
+/**
+ * @private
+ * @member Ext
+ */
+Ext.mergeIf = Ext.Object.mergeIf;
+
+/**
+ *
+ * @member Ext
+ * @method urlEncode
+ * @inheritdoc Ext.Object#toQueryString
+ * @deprecated 4.0.0 Use {@link Ext.Object#toQueryString} instead
+ */
+Ext.urlEncode = function() {
+ var args = Ext.Array.from(arguments),
+ prefix = '';
+
+ // Support for the old `pre` argument
+ if ((typeof args[1] === 'string')) {
+ prefix = args[1] + '&';
+ args[1] = false;
+ }
+
+ return prefix + ExtObject.toQueryString.apply(ExtObject, args);
+};
+
+/**
+ * Alias for {@link Ext.Object#fromQueryString}.
+ *
+ * @member Ext
+ * @method urlDecode
+ * @inheritdoc Ext.Object#fromQueryString
+ * @deprecated 4.0.0 Use {@link Ext.Object#fromQueryString} instead
+ */
+Ext.urlDecode = function() {
+ return ExtObject.fromQueryString.apply(ExtObject, arguments);
+};
+
+}());
+
+//@tag foundation,core
+//@require Object.js
+//@define Ext.Date
+
+/**
+ * @class Ext.Date
+ * A set of useful static methods to deal with date
+ * Note that if Ext.Date is required and loaded, it will copy all methods / properties to
+ * this object for convenience
+ *
+ * The date parsing and formatting syntax contains a subset of
+ * PHP's date() function , and the formats that are
+ * supported will provide results equivalent to their PHP versions.
+ *
+ * The following is a list of all currently supported formats:
+ *
+Format Description Example returned values
+------ ----------------------------------------------------------------------- -----------------------
+ d Day of the month, 2 digits with leading zeros 01 to 31
+ D A short textual representation of the day of the week Mon to Sun
+ j Day of the month without leading zeros 1 to 31
+ l A full textual representation of the day of the week Sunday to Saturday
+ N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
+ S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
+ w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
+ z The day of the year (starting from 0) 0 to 364 (365 in leap years)
+ W ISO-8601 week number of year, weeks starting on Monday 01 to 53
+ F A full textual representation of a month, such as January or March January to December
+ m Numeric representation of a month, with leading zeros 01 to 12
+ M A short textual representation of a month Jan to Dec
+ n Numeric representation of a month, without leading zeros 1 to 12
+ t Number of days in the given month 28 to 31
+ L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
+ o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
+ belongs to the previous or next year, that year is used instead)
+ Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
+ y A two digit representation of a year Examples: 99 or 03
+ a Lowercase Ante meridiem and Post meridiem am or pm
+ A Uppercase Ante meridiem and Post meridiem AM or PM
+ g 12-hour format of an hour without leading zeros 1 to 12
+ G 24-hour format of an hour without leading zeros 0 to 23
+ h 12-hour format of an hour with leading zeros 01 to 12
+ H 24-hour format of an hour with leading zeros 00 to 23
+ i Minutes, with leading zeros 00 to 59
+ s Seconds, with leading zeros 00 to 59
+ u Decimal fraction of a second Examples:
+ (minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
+ 100 (i.e. 0.100s) or
+ 999 (i.e. 0.999s) or
+ 999876543210 (i.e. 0.999876543210s)
+ O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
+ P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
+ T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
+ Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
+ c ISO 8601 date
+ Notes: Examples:
+ 1) If unspecified, the month / day defaults to the current month / day, 1991 or
+ the time defaults to midnight, while the timezone defaults to the 1992-10 or
+ browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
+ and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
+ are optional. 1995-07-18T17:21:28-02:00 or
+ 2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
+ least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
+ of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
+ Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
+ date-time granularity which are supported, or see 2000-02-13T21:25:33
+ http://www.w3.org/TR/NOTE-datetime for more info. 2001-01-12 22:26:34
+ U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
+ MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
+ \/Date(1238606590509+0800)\/
+
+ *
+ * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
+ *
+// Sample date:
+// 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
+
+var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
+console.log(Ext.Date.format(dt, 'Y-m-d')); // 2007-01-10
+console.log(Ext.Date.format(dt, 'F j, Y, g:i a')); // January 10, 2007, 3:05 pm
+console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
+
+ *
+ * Here are some standard date/time patterns that you might find helpful. They
+ * are not part of the source of Ext.Date, but to use them you can simply copy this
+ * block of code into any script that is included after Ext.Date and they will also become
+ * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
+ *
+Ext.Date.patterns = {
+ ISO8601Long:"Y-m-d H:i:s",
+ ISO8601Short:"Y-m-d",
+ ShortDate: "n/j/Y",
+ LongDate: "l, F d, Y",
+ FullDateTime: "l, F d, Y g:i:s A",
+ MonthDay: "F d",
+ ShortTime: "g:i A",
+ LongTime: "g:i:s A",
+ SortableDateTime: "Y-m-d\\TH:i:s",
+ UniversalSortableDateTime: "Y-m-d H:i:sO",
+ YearMonth: "F, Y"
+};
+
+ *
+ * Example usage:
+ *
+var dt = new Date();
+console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
+
+ * Developer-written, custom formats may be used by supplying both a formatting and a parsing function
+ * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.
+ * @singleton
+ */
+
+/*
+ * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
+ * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
+ * They generate precompiled functions from format patterns instead of parsing and
+ * processing each pattern every time a date is formatted. These functions are available
+ * on every Date object.
+ */
+
+(function() {
+
+// create private copy of Ext's Ext.util.Format.format() method
+// - to remove unnecessary dependency
+// - to resolve namespace conflict with MS-Ajax's implementation
+function xf(format) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return format.replace(/\{(\d+)\}/g, function(m, i) {
+ return args[i];
+ });
+}
+
+Ext.Date = {
+ /**
+ * Returns the current timestamp.
+ * @return {Number} Milliseconds since UNIX epoch.
+ * @method
+ */
+ now: Date.now || function() {
+ return +new Date();
+ },
+
+ /**
+ * @private
+ * Private for now
+ */
+ toString: function(date) {
+ var pad = Ext.String.leftPad;
+
+ return date.getFullYear() + "-"
+ + pad(date.getMonth() + 1, 2, '0') + "-"
+ + pad(date.getDate(), 2, '0') + "T"
+ + pad(date.getHours(), 2, '0') + ":"
+ + pad(date.getMinutes(), 2, '0') + ":"
+ + pad(date.getSeconds(), 2, '0');
+ },
+
+ /**
+ * Returns the number of milliseconds between two dates
+ * @param {Date} dateA The first date
+ * @param {Date} dateB (optional) The second date, defaults to now
+ * @return {Number} The difference in milliseconds
+ */
+ getElapsed: function(dateA, dateB) {
+ return Math.abs(dateA - (dateB || new Date()));
+ },
+
+ /**
+ * Global flag which determines if strict date parsing should be used.
+ * Strict date parsing will not roll-over invalid dates, which is the
+ * default behaviour of javascript Date objects.
+ * (see {@link #parse} for more information)
+ * Defaults to false .
+ * @type Boolean
+ */
+ useStrict: false,
+
+ // private
+ formatCodeToRegex: function(character, currentGroup) {
+ // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below)
+ var p = utilDate.parseCodes[character];
+
+ if (p) {
+ p = typeof p == 'function'? p() : p;
+ utilDate.parseCodes[character] = p; // reassign function result to prevent repeated execution
+ }
+
+ return p ? Ext.applyIf({
+ c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
+ }, p) : {
+ g: 0,
+ c: null,
+ s: Ext.String.escapeRegex(character) // treat unrecognised characters as literals
+ };
+ },
+
+ /**
+ * An object hash in which each property is a date parsing function. The property name is the
+ * format string which that function parses.
+ * This object is automatically populated with date parsing functions as
+ * date formats are requested for Ext standard formatting strings.
+ * Custom parsing functions may be inserted into this object, keyed by a name which from then on
+ * may be used as a format string to {@link #parse}.
+ *
Example:
+Ext.Date.parseFunctions['x-date-format'] = myDateParser;
+
+ * A parsing function should return a Date object, and is passed the following parameters:
+ * date : StringThe date string to parse.
+ * strict : BooleanTrue to validate date strings while parsing
+ * (i.e. prevent javascript Date "rollover") (The default must be false).
+ * Invalid date strings should return null when parsed.
+ *
+ * To enable Dates to also be formatted according to that format, a corresponding
+ * formatting function must be placed into the {@link #formatFunctions} property.
+ * @property parseFunctions
+ * @type Object
+ */
+ parseFunctions: {
+ "MS": function(input, strict) {
+ // note: the timezone offset is ignored since the MS Ajax server sends
+ // a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
+ var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/'),
+ r = (input || '').match(re);
+ return r? new Date(((r[1] || '') + r[2]) * 1) : null;
+ }
+ },
+ parseRegexes: [],
+
+ /**
+ *
An object hash in which each property is a date formatting function. The property name is the
+ * format string which corresponds to the produced formatted date string.
+ * This object is automatically populated with date formatting functions as
+ * date formats are requested for Ext standard formatting strings.
+ * Custom formatting functions may be inserted into this object, keyed by a name which from then on
+ * may be used as a format string to {@link #format}. Example:
+Ext.Date.formatFunctions['x-date-format'] = myDateFormatter;
+
+ * A formatting function should return a string representation of the passed Date object, and is passed the following parameters:
+ * date : DateThe Date to format.
+ *
+ * To enable date strings to also be parsed according to that format, a corresponding
+ * parsing function must be placed into the {@link #parseFunctions} property.
+ * @property formatFunctions
+ * @type Object
+ */
+ formatFunctions: {
+ "MS": function() {
+ // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF))
+ return '\\/Date(' + this.getTime() + ')\\/';
+ }
+ },
+
+ y2kYear : 50,
+
+ /**
+ * Date interval constant
+ * @type String
+ */
+ MILLI : "ms",
+
+ /**
+ * Date interval constant
+ * @type String
+ */
+ SECOND : "s",
+
+ /**
+ * Date interval constant
+ * @type String
+ */
+ MINUTE : "mi",
+
+ /** Date interval constant
+ * @type String
+ */
+ HOUR : "h",
+
+ /**
+ * Date interval constant
+ * @type String
+ */
+ DAY : "d",
+
+ /**
+ * Date interval constant
+ * @type String
+ */
+ MONTH : "mo",
+
+ /**
+ * Date interval constant
+ * @type String
+ */
+ YEAR : "y",
+
+ /**
+ *
An object hash containing default date values used during date parsing.
+ * The following properties are available:
+ * y : NumberThe default year value. (defaults to undefined)
+ * m : NumberThe default 1-based month value. (defaults to undefined)
+ * d : NumberThe default day value. (defaults to undefined)
+ * h : NumberThe default hour value. (defaults to undefined)
+ * i : NumberThe default minute value. (defaults to undefined)
+ * s : NumberThe default second value. (defaults to undefined)
+ * ms : NumberThe default millisecond value. (defaults to undefined)
+ *
+ * Override these properties to customize the default date values used by the {@link #parse} method.
+ * Note: In countries which experience Daylight Saving Time (i.e. DST), the h , i , s
+ * and ms properties may coincide with the exact time in which DST takes effect.
+ * It is the responsiblity of the developer to account for this.
+ * Example Usage:
+ *
+// set default day value to the first day of the month
+Ext.Date.defaults.d = 1;
+
+// parse a February date string containing only year and month values.
+// setting the default day value to 1 prevents weird date rollover issues
+// when attempting to parse the following date string on, for example, March 31st 2009.
+Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
+
+ * @property defaults
+ * @type Object
+ */
+ defaults: {},
+
+ //
+ /**
+ * @property {String[]} dayNames
+ * An array of textual day names.
+ * Override these values for international dates.
+ * Example:
+ *
+Ext.Date.dayNames = [
+ 'SundayInYourLang',
+ 'MondayInYourLang',
+ ...
+];
+
+ */
+ dayNames : [
+ "Sunday",
+ "Monday",
+ "Tuesday",
+ "Wednesday",
+ "Thursday",
+ "Friday",
+ "Saturday"
+ ],
+ //
+
+ //
+ /**
+ * @property {String[]} monthNames
+ * An array of textual month names.
+ * Override these values for international dates.
+ * Example:
+ *
+Ext.Date.monthNames = [
+ 'JanInYourLang',
+ 'FebInYourLang',
+ ...
+];
+
+ */
+ monthNames : [
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December"
+ ],
+ //
+
+ //
+ /**
+ * @property {Object} monthNumbers
+ * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
+ * Override these values for international dates.
+ * Example:
+ *
+Ext.Date.monthNumbers = {
+ 'LongJanNameInYourLang': 0,
+ 'ShortJanNameInYourLang':0,
+ 'LongFebNameInYourLang':1,
+ 'ShortFebNameInYourLang':1,
+ ...
+};
+
+ */
+ monthNumbers : {
+ January: 0,
+ Jan: 0,
+ February: 1,
+ Feb: 1,
+ March: 2,
+ Mar: 2,
+ April: 3,
+ Apr: 3,
+ May: 4,
+ June: 5,
+ Jun: 5,
+ July: 6,
+ Jul: 6,
+ August: 7,
+ Aug: 7,
+ September: 8,
+ Sep: 8,
+ October: 9,
+ Oct: 9,
+ November: 10,
+ Nov: 10,
+ December: 11,
+ Dec: 11
+ },
+ //
+
+ //
+ /**
+ * @property {String} defaultFormat
+ * The date format string that the {@link Ext.util.Format#dateRenderer}
+ * and {@link Ext.util.Format#date} functions use. See {@link Ext.Date} for details.
+ * This may be overridden in a locale file.
+ */
+ defaultFormat : "m/d/Y",
+ //
+ //
+ /**
+ * Get the short month name for the given month number.
+ * Override this function for international dates.
+ * @param {Number} month A zero-based javascript month number.
+ * @return {String} The short month name.
+ */
+ getShortMonthName : function(month) {
+ return Ext.Date.monthNames[month].substring(0, 3);
+ },
+ //
+
+ //
+ /**
+ * Get the short day name for the given day number.
+ * Override this function for international dates.
+ * @param {Number} day A zero-based javascript day number.
+ * @return {String} The short day name.
+ */
+ getShortDayName : function(day) {
+ return Ext.Date.dayNames[day].substring(0, 3);
+ },
+ //
+
+ //
+ /**
+ * Get the zero-based javascript month number for the given short/full month name.
+ * Override this function for international dates.
+ * @param {String} name The short/full month name.
+ * @return {Number} The zero-based javascript month number.
+ */
+ getMonthNumber : function(name) {
+ // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive)
+ return Ext.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
+ },
+ //
+
+ /**
+ * Checks if the specified format contains hour information
+ * @param {String} format The format to check
+ * @return {Boolean} True if the format contains hour information
+ * @method
+ */
+ formatContainsHourInfo : (function(){
+ var stripEscapeRe = /(\\.)/g,
+ hourInfoRe = /([gGhHisucUOPZ]|MS)/;
+ return function(format){
+ return hourInfoRe.test(format.replace(stripEscapeRe, ''));
+ };
+ }()),
+
+ /**
+ * Checks if the specified format contains information about
+ * anything other than the time.
+ * @param {String} format The format to check
+ * @return {Boolean} True if the format contains information about
+ * date/day information.
+ * @method
+ */
+ formatContainsDateInfo : (function(){
+ var stripEscapeRe = /(\\.)/g,
+ dateInfoRe = /([djzmnYycU]|MS)/;
+
+ return function(format){
+ return dateInfoRe.test(format.replace(stripEscapeRe, ''));
+ };
+ }()),
+
+ /**
+ * Removes all escaping for a date format string. In date formats,
+ * using a '\' can be used to escape special characters.
+ * @param {String} format The format to unescape
+ * @return {String} The unescaped format
+ * @method
+ */
+ unescapeFormat: (function() {
+ var slashRe = /\\/gi;
+ return function(format) {
+ // Escape the format, since \ can be used to escape special
+ // characters in a date format. For example, in a spanish
+ // locale the format may be: 'd \\de F \\de Y'
+ return format.replace(slashRe, '');
+ }
+ }()),
+
+ /**
+ * The base format-code to formatting-function hashmap used by the {@link #format} method.
+ * Formatting functions are strings (or functions which return strings) which
+ * will return the appropriate value when evaluated in the context of the Date object
+ * from which the {@link #format} method is called.
+ * Add to / override these mappings for custom date formatting.
+ * Note: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found.
+ * Example:
+ *
+Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
+console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
+
+ * @type Object
+ */
+ formatCodes : {
+ d: "Ext.String.leftPad(this.getDate(), 2, '0')",
+ D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name
+ j: "this.getDate()",
+ l: "Ext.Date.dayNames[this.getDay()]",
+ N: "(this.getDay() ? this.getDay() : 7)",
+ S: "Ext.Date.getSuffix(this)",
+ w: "this.getDay()",
+ z: "Ext.Date.getDayOfYear(this)",
+ W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')",
+ F: "Ext.Date.monthNames[this.getMonth()]",
+ m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')",
+ M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name
+ n: "(this.getMonth() + 1)",
+ t: "Ext.Date.getDaysInMonth(this)",
+ L: "(Ext.Date.isLeapYear(this) ? 1 : 0)",
+ o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",
+ Y: "Ext.String.leftPad(this.getFullYear(), 4, '0')",
+ y: "('' + this.getFullYear()).substring(2, 4)",
+ a: "(this.getHours() < 12 ? 'am' : 'pm')",
+ A: "(this.getHours() < 12 ? 'AM' : 'PM')",
+ g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
+ G: "this.getHours()",
+ h: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
+ H: "Ext.String.leftPad(this.getHours(), 2, '0')",
+ i: "Ext.String.leftPad(this.getMinutes(), 2, '0')",
+ s: "Ext.String.leftPad(this.getSeconds(), 2, '0')",
+ u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')",
+ O: "Ext.Date.getGMTOffset(this)",
+ P: "Ext.Date.getGMTOffset(this, true)",
+ T: "Ext.Date.getTimezone(this)",
+ Z: "(this.getTimezoneOffset() * -60)",
+
+ c: function() { // ISO-8601 -- GMT format
+ var c, code, i, l, e;
+ for (c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
+ e = c.charAt(i);
+ code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal
+ }
+ return code.join(" + ");
+ },
+ /*
+ c: function() { // ISO-8601 -- UTC format
+ return [
+ "this.getUTCFullYear()", "'-'",
+ "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
+ "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')",
+ "'T'",
+ "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'",
+ "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
+ "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')",
+ "'Z'"
+ ].join(" + ");
+ },
+ */
+
+ U: "Math.round(this.getTime() / 1000)"
+ },
+
+ /**
+ * Checks if the passed Date parameters will cause a javascript Date "rollover".
+ * @param {Number} year 4-digit year
+ * @param {Number} month 1-based month-of-year
+ * @param {Number} day Day of month
+ * @param {Number} hour (optional) Hour
+ * @param {Number} minute (optional) Minute
+ * @param {Number} second (optional) Second
+ * @param {Number} millisecond (optional) Millisecond
+ * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
+ */
+ isValid : function(y, m, d, h, i, s, ms) {
+ // setup defaults
+ h = h || 0;
+ i = i || 0;
+ s = s || 0;
+ ms = ms || 0;
+
+ // Special handling for year < 100
+ var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.YEAR, y < 100 ? y - 100 : 0);
+
+ return y == dt.getFullYear() &&
+ m == dt.getMonth() + 1 &&
+ d == dt.getDate() &&
+ h == dt.getHours() &&
+ i == dt.getMinutes() &&
+ s == dt.getSeconds() &&
+ ms == dt.getMilliseconds();
+ },
+
+ /**
+ * Parses the passed string using the specified date format.
+ * Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
+ * The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
+ * which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
+ * the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
+ * Keep in mind that the input date string must precisely match the specified format string
+ * in order for the parse operation to be successful (failed parse operations return a null value).
+ * Example:
+//dt = Fri May 25 2007 (current date)
+var dt = new Date();
+
+//dt = Thu May 25 2006 (today's month/day in 2006)
+dt = Ext.Date.parse("2006", "Y");
+
+//dt = Sun Jan 15 2006 (all date parts specified)
+dt = Ext.Date.parse("2006-01-15", "Y-m-d");
+
+//dt = Sun Jan 15 2006 15:20:01
+dt = Ext.Date.parse("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
+
+// attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
+dt = Ext.Date.parse("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
+
+ * @param {String} input The raw date string.
+ * @param {String} format The expected date string format.
+ * @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
+ (defaults to false). Invalid date strings will return null when parsed.
+ * @return {Date} The parsed Date.
+ */
+ parse : function(input, format, strict) {
+ var p = utilDate.parseFunctions;
+ if (p[format] == null) {
+ utilDate.createParser(format);
+ }
+ return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict);
+ },
+
+ // Backwards compat
+ parseDate: function(input, format, strict){
+ return utilDate.parse(input, format, strict);
+ },
+
+
+ // private
+ getFormatCode : function(character) {
+ var f = utilDate.formatCodes[character];
+
+ if (f) {
+ f = typeof f == 'function'? f() : f;
+ utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution
+ }
+
+ // note: unknown characters are treated as literals
+ return f || ("'" + Ext.String.escape(character) + "'");
+ },
+
+ // private
+ createFormat : function(format) {
+ var code = [],
+ special = false,
+ ch = '',
+ i;
+
+ for (i = 0; i < format.length; ++i) {
+ ch = format.charAt(i);
+ if (!special && ch == "\\") {
+ special = true;
+ } else if (special) {
+ special = false;
+ code.push("'" + Ext.String.escape(ch) + "'");
+ } else {
+ code.push(utilDate.getFormatCode(ch));
+ }
+ }
+ utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+'));
+ },
+
+ // private
+ createParser : (function() {
+ var code = [
+ "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
+ "def = Ext.Date.defaults,",
+ "results = String(input).match(Ext.Date.parseRegexes[{0}]);", // either null, or an array of matched strings
+
+ "if(results){",
+ "{1}",
+
+ "if(u != null){", // i.e. unix time is defined
+ "v = new Date(u * 1000);", // give top priority to UNIX time
+ "}else{",
+ // create Date object representing midnight of the current day;
+ // this will provide us with our date defaults
+ // (note: clearTime() handles Daylight Saving Time automatically)
+ "dt = Ext.Date.clearTime(new Date);",
+
+ // date calculations (note: these calculations create a dependency on Ext.Number.from())
+ "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));",
+ "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));",
+ "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));",
+
+ // time calculations (note: these calculations create a dependency on Ext.Number.from())
+ "h = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));",
+ "i = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));",
+ "s = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));",
+ "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));",
+
+ "if(z >= 0 && y >= 0){",
+ // both the year and zero-based day of year are defined and >= 0.
+ // these 2 values alone provide sufficient info to create a full date object
+
+ // create Date object representing January 1st for the given year
+ // handle years < 100 appropriately
+ "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
+
+ // then add day of year, checking for Date "rollover" if necessary
+ "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);",
+ "}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
+ "v = null;", // invalid date, so return null
+ "}else{",
+ // plain old Date object
+ // handle years < 100 properly
+ "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
+ "}",
+ "}",
+ "}",
+
+ "if(v){",
+ // favour UTC offset over GMT offset
+ "if(zz != null){",
+ // reset to UTC, then add offset
+ "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
+ "}else if(o){",
+ // reset to GMT, then add offset
+ "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
+ "}",
+ "}",
+
+ "return v;"
+ ].join('\n');
+
+ return function(format) {
+ var regexNum = utilDate.parseRegexes.length,
+ currentGroup = 1,
+ calc = [],
+ regex = [],
+ special = false,
+ ch = "",
+ i = 0,
+ len = format.length,
+ atEnd = [],
+ obj;
+
+ for (; i < len; ++i) {
+ ch = format.charAt(i);
+ if (!special && ch == "\\") {
+ special = true;
+ } else if (special) {
+ special = false;
+ regex.push(Ext.String.escape(ch));
+ } else {
+ obj = utilDate.formatCodeToRegex(ch, currentGroup);
+ currentGroup += obj.g;
+ regex.push(obj.s);
+ if (obj.g && obj.c) {
+ if (obj.calcAtEnd) {
+ atEnd.push(obj.c);
+ } else {
+ calc.push(obj.c);
+ }
+ }
+ }
+ }
+
+ calc = calc.concat(atEnd);
+
+ utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
+ utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join('')));
+ };
+ }()),
+
+ // private
+ parseCodes : {
+ /*
+ * Notes:
+ * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
+ * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
+ * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
+ */
+ d: {
+ g:1,
+ c:"d = parseInt(results[{0}], 10);\n",
+ s:"(3[0-1]|[1-2][0-9]|0[1-9])" // day of month with leading zeroes (01 - 31)
+ },
+ j: {
+ g:1,
+ c:"d = parseInt(results[{0}], 10);\n",
+ s:"(3[0-1]|[1-2][0-9]|[1-9])" // day of month without leading zeroes (1 - 31)
+ },
+ D: function() {
+ for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names
+ return {
+ g:0,
+ c:null,
+ s:"(?:" + a.join("|") +")"
+ };
+ },
+ l: function() {
+ return {
+ g:0,
+ c:null,
+ s:"(?:" + utilDate.dayNames.join("|") + ")"
+ };
+ },
+ N: {
+ g:0,
+ c:null,
+ s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
+ },
+ //
+ S: {
+ g:0,
+ c:null,
+ s:"(?:st|nd|rd|th)"
+ },
+ //
+ w: {
+ g:0,
+ c:null,
+ s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
+ },
+ z: {
+ g:1,
+ c:"z = parseInt(results[{0}], 10);\n",
+ s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
+ },
+ W: {
+ g:0,
+ c:null,
+ s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)
+ },
+ F: function() {
+ return {
+ g:1,
+ c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
+ s:"(" + utilDate.monthNames.join("|") + ")"
+ };
+ },
+ M: function() {
+ for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names
+ return Ext.applyIf({
+ s:"(" + a.join("|") + ")"
+ }, utilDate.formatCodeToRegex("F"));
+ },
+ m: {
+ g:1,
+ c:"m = parseInt(results[{0}], 10) - 1;\n",
+ s:"(1[0-2]|0[1-9])" // month number with leading zeros (01 - 12)
+ },
+ n: {
+ g:1,
+ c:"m = parseInt(results[{0}], 10) - 1;\n",
+ s:"(1[0-2]|[1-9])" // month number without leading zeros (1 - 12)
+ },
+ t: {
+ g:0,
+ c:null,
+ s:"(?:\\d{2})" // no. of days in the month (28 - 31)
+ },
+ L: {
+ g:0,
+ c:null,
+ s:"(?:1|0)"
+ },
+ o: function() {
+ return utilDate.formatCodeToRegex("Y");
+ },
+ Y: {
+ g:1,
+ c:"y = parseInt(results[{0}], 10);\n",
+ s:"(\\d{4})" // 4-digit year
+ },
+ y: {
+ g:1,
+ c:"var ty = parseInt(results[{0}], 10);\n"
+ + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
+ s:"(\\d{1,2})"
+ },
+ /*
+ * In the am/pm parsing routines, we allow both upper and lower case
+ * even though it doesn't exactly match the spec. It gives much more flexibility
+ * in being able to specify case insensitive regexes.
+ */
+ //
+ a: {
+ g:1,
+ c:"if (/(am)/i.test(results[{0}])) {\n"
+ + "if (!h || h == 12) { h = 0; }\n"
+ + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
+ s:"(am|pm|AM|PM)",
+ calcAtEnd: true
+ },
+ //
+ //
+ A: {
+ g:1,
+ c:"if (/(am)/i.test(results[{0}])) {\n"
+ + "if (!h || h == 12) { h = 0; }\n"
+ + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
+ s:"(AM|PM|am|pm)",
+ calcAtEnd: true
+ },
+ //
+ g: {
+ g:1,
+ c:"h = parseInt(results[{0}], 10);\n",
+ s:"(1[0-2]|[0-9])" // 12-hr format of an hour without leading zeroes (1 - 12)
+ },
+ G: {
+ g:1,
+ c:"h = parseInt(results[{0}], 10);\n",
+ s:"(2[0-3]|1[0-9]|[0-9])" // 24-hr format of an hour without leading zeroes (0 - 23)
+ },
+ h: {
+ g:1,
+ c:"h = parseInt(results[{0}], 10);\n",
+ s:"(1[0-2]|0[1-9])" // 12-hr format of an hour with leading zeroes (01 - 12)
+ },
+ H: {
+ g:1,
+ c:"h = parseInt(results[{0}], 10);\n",
+ s:"(2[0-3]|[0-1][0-9])" // 24-hr format of an hour with leading zeroes (00 - 23)
+ },
+ i: {
+ g:1,
+ c:"i = parseInt(results[{0}], 10);\n",
+ s:"([0-5][0-9])" // minutes with leading zeros (00 - 59)
+ },
+ s: {
+ g:1,
+ c:"s = parseInt(results[{0}], 10);\n",
+ s:"([0-5][0-9])" // seconds with leading zeros (00 - 59)
+ },
+ u: {
+ g:1,
+ c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
+ s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
+ },
+ O: {
+ g:1,
+ c:[
+ "o = results[{0}];",
+ "var sn = o.substring(0,1),", // get + / - sign
+ "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
+ "mn = o.substring(3,5) % 60;", // get minutes
+ "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
+ ].join("\n"),
+ s: "([+-]\\d{4})" // GMT offset in hrs and mins
+ },
+ P: {
+ g:1,
+ c:[
+ "o = results[{0}];",
+ "var sn = o.substring(0,1),", // get + / - sign
+ "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
+ "mn = o.substring(4,6) % 60;", // get minutes
+ "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
+ ].join("\n"),
+ s: "([+-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
+ },
+ T: {
+ g:0,
+ c:null,
+ s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
+ },
+ Z: {
+ g:1,
+ c:"zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
+ + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
+ s:"([+-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
+ },
+ c: function() {
+ var calc = [],
+ arr = [
+ utilDate.formatCodeToRegex("Y", 1), // year
+ utilDate.formatCodeToRegex("m", 2), // month
+ utilDate.formatCodeToRegex("d", 3), // day
+ utilDate.formatCodeToRegex("H", 4), // hour
+ utilDate.formatCodeToRegex("i", 5), // minute
+ utilDate.formatCodeToRegex("s", 6), // second
+ {c:"ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n"}, // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
+ {c:[ // allow either "Z" (i.e. UTC) or "-0530" or "+08:00" (i.e. UTC offset) timezone delimiters. assumes local timezone if no timezone is specified
+ "if(results[8]) {", // timezone specified
+ "if(results[8] == 'Z'){",
+ "zz = 0;", // UTC
+ "}else if (results[8].indexOf(':') > -1){",
+ utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator
+ "}else{",
+ utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator
+ "}",
+ "}"
+ ].join('\n')}
+ ],
+ i,
+ l;
+
+ for (i = 0, l = arr.length; i < l; ++i) {
+ calc.push(arr[i].c);
+ }
+
+ return {
+ g:1,
+ c:calc.join(""),
+ s:[
+ arr[0].s, // year (required)
+ "(?:", "-", arr[1].s, // month (optional)
+ "(?:", "-", arr[2].s, // day (optional)
+ "(?:",
+ "(?:T| )?", // time delimiter -- either a "T" or a single blank space
+ arr[3].s, ":", arr[4].s, // hour AND minute, delimited by a single colon (optional). MUST be preceded by either a "T" or a single blank space
+ "(?::", arr[5].s, ")?", // seconds (optional)
+ "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
+ "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
+ ")?",
+ ")?",
+ ")?"
+ ].join("")
+ };
+ },
+ U: {
+ g:1,
+ c:"u = parseInt(results[{0}], 10);\n",
+ s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
+ }
+ },
+
+ //Old Ext.Date prototype methods.
+ // private
+ dateFormat: function(date, format) {
+ return utilDate.format(date, format);
+ },
+
+ /**
+ * Compares if two dates are equal by comparing their values.
+ * @param {Date} date1
+ * @param {Date} date2
+ * @return {Boolean} True if the date values are equal
+ */
+ isEqual: function(date1, date2) {
+ // check we have 2 date objects
+ if (date1 && date2) {
+ return (date1.getTime() === date2.getTime());
+ }
+ // one or both isn't a date, only equal if both are falsey
+ return !(date1 || date2);
+ },
+
+ /**
+ * Formats a date given the supplied format string.
+ * @param {Date} date The date to format
+ * @param {String} format The format string
+ * @return {String} The formatted date or an empty string if date parameter is not a JavaScript Date object
+ */
+ format: function(date, format) {
+ var formatFunctions = utilDate.formatFunctions;
+
+ if (!Ext.isDate(date)) {
+ return '';
+ }
+
+ if (formatFunctions[format] == null) {
+ utilDate.createFormat(format);
+ }
+
+ return formatFunctions[format].call(date) + '';
+ },
+
+ /**
+ * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
+ *
+ * Note: The date string returned by the javascript Date object's toString() method varies
+ * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
+ * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
+ * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
+ * (which may or may not be present), failing which it proceeds to get the timezone abbreviation
+ * from the GMT offset portion of the date string.
+ * @param {Date} date The date
+ * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
+ */
+ getTimezone : function(date) {
+ // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
+ //
+ // Opera : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
+ // Safari : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone (same as FF)
+ // FF : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
+ // IE : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
+ // IE : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
+ //
+ // this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
+ // step 1: (?:\((.*)\) -- find timezone in parentheses
+ // step 2: ([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?) -- if nothing was found in step 1, find timezone from timezone offset portion of date string
+ // step 3: remove all non uppercase characters found in step 1 and 2
+ return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
+ },
+
+ /**
+ * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
+ * @param {Date} date The date
+ * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
+ * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
+ */
+ getGMTOffset : function(date, colon) {
+ var offset = date.getTimezoneOffset();
+ return (offset > 0 ? "-" : "+")
+ + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0")
+ + (colon ? ":" : "")
+ + Ext.String.leftPad(Math.abs(offset % 60), 2, "0");
+ },
+
+ /**
+ * Get the numeric day number of the year, adjusted for leap year.
+ * @param {Date} date The date
+ * @return {Number} 0 to 364 (365 in leap years).
+ */
+ getDayOfYear: function(date) {
+ var num = 0,
+ d = Ext.Date.clone(date),
+ m = date.getMonth(),
+ i;
+
+ for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
+ num += utilDate.getDaysInMonth(d);
+ }
+ return num + date.getDate() - 1;
+ },
+
+ /**
+ * Get the numeric ISO-8601 week number of the year.
+ * (equivalent to the format specifier 'W', but without a leading zero).
+ * @param {Date} date The date
+ * @return {Number} 1 to 53
+ * @method
+ */
+ getWeekOfYear : (function() {
+ // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
+ var ms1d = 864e5, // milliseconds in a day
+ ms7d = 7 * ms1d; // milliseconds in a week
+
+ return function(date) { // return a closure so constants get calculated only once
+ var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number
+ AWN = Math.floor(DC3 / 7), // an Absolute Week Number
+ Wyr = new Date(AWN * ms7d).getUTCFullYear();
+
+ return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
+ };
+ }()),
+
+ /**
+ * Checks if the current date falls within a leap year.
+ * @param {Date} date The date
+ * @return {Boolean} True if the current date falls within a leap year, false otherwise.
+ */
+ isLeapYear : function(date) {
+ var year = date.getFullYear();
+ return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
+ },
+
+ /**
+ * Get the first day of the current month, adjusted for leap year. The returned value
+ * is the numeric day index within the week (0-6) which can be used in conjunction with
+ * the {@link #monthNames} array to retrieve the textual day name.
+ * Example:
+ *
+var dt = new Date('1/10/2007'),
+ firstDay = Ext.Date.getFirstDayOfMonth(dt);
+console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
+ *
+ * @param {Date} date The date
+ * @return {Number} The day number (0-6).
+ */
+ getFirstDayOfMonth : function(date) {
+ var day = (date.getDay() - (date.getDate() - 1)) % 7;
+ return (day < 0) ? (day + 7) : day;
+ },
+
+ /**
+ * Get the last day of the current month, adjusted for leap year. The returned value
+ * is the numeric day index within the week (0-6) which can be used in conjunction with
+ * the {@link #monthNames} array to retrieve the textual day name.
+ * Example:
+ *
+var dt = new Date('1/10/2007'),
+ lastDay = Ext.Date.getLastDayOfMonth(dt);
+console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
+ *
+ * @param {Date} date The date
+ * @return {Number} The day number (0-6).
+ */
+ getLastDayOfMonth : function(date) {
+ return utilDate.getLastDateOfMonth(date).getDay();
+ },
+
+
+ /**
+ * Get the date of the first day of the month in which this date resides.
+ * @param {Date} date The date
+ * @return {Date}
+ */
+ getFirstDateOfMonth : function(date) {
+ return new Date(date.getFullYear(), date.getMonth(), 1);
+ },
+
+ /**
+ * Get the date of the last day of the month in which this date resides.
+ * @param {Date} date The date
+ * @return {Date}
+ */
+ getLastDateOfMonth : function(date) {
+ return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date));
+ },
+
+ /**
+ * Get the number of days in the current month, adjusted for leap year.
+ * @param {Date} date The date
+ * @return {Number} The number of days in the month.
+ * @method
+ */
+ getDaysInMonth: (function() {
+ var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+
+ return function(date) { // return a closure for efficiency
+ var m = date.getMonth();
+
+ return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m];
+ };
+ }()),
+
+ //
+ /**
+ * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
+ * @param {Date} date The date
+ * @return {String} 'st, 'nd', 'rd' or 'th'.
+ */
+ getSuffix : function(date) {
+ switch (date.getDate()) {
+ case 1:
+ case 21:
+ case 31:
+ return "st";
+ case 2:
+ case 22:
+ return "nd";
+ case 3:
+ case 23:
+ return "rd";
+ default:
+ return "th";
+ }
+ },
+ //
+
+ /**
+ * Creates and returns a new Date instance with the exact same date value as the called instance.
+ * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
+ * variable will also be changed. When the intention is to create a new variable that will not
+ * modify the original instance, you should create a clone.
+ *
+ * Example of correctly cloning a date:
+ *
+//wrong way:
+var orig = new Date('10/1/2006');
+var copy = orig;
+copy.setDate(5);
+console.log(orig); //returns 'Thu Oct 05 2006'!
+
+//correct way:
+var orig = new Date('10/1/2006'),
+ copy = Ext.Date.clone(orig);
+copy.setDate(5);
+console.log(orig); //returns 'Thu Oct 01 2006'
+ *
+ * @param {Date} date The date
+ * @return {Date} The new Date instance.
+ */
+ clone : function(date) {
+ return new Date(date.getTime());
+ },
+
+ /**
+ * Checks if the current date is affected by Daylight Saving Time (DST).
+ * @param {Date} date The date
+ * @return {Boolean} True if the current date is affected by DST.
+ */
+ isDST : function(date) {
+ // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172
+ // courtesy of @geoffrey.mcgill
+ return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset();
+ },
+
+ /**
+ * Attempts to clear all time information from this Date by setting the time to midnight of the same day,
+ * automatically adjusting for Daylight Saving Time (DST) where applicable.
+ * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
+ * @param {Date} date The date
+ * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
+ * @return {Date} this or the clone.
+ */
+ clearTime : function(date, clone) {
+ if (clone) {
+ return Ext.Date.clearTime(Ext.Date.clone(date));
+ }
+
+ // get current date before clearing time
+ var d = date.getDate(),
+ hr,
+ c;
+
+ // clear time
+ date.setHours(0);
+ date.setMinutes(0);
+ date.setSeconds(0);
+ date.setMilliseconds(0);
+
+ if (date.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
+ // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
+ // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
+
+ // increment hour until cloned date == current date
+ for (hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr));
+
+ date.setDate(d);
+ date.setHours(c.getHours());
+ }
+
+ return date;
+ },
+
+ /**
+ * Provides a convenient method for performing basic date arithmetic. This method
+ * does not modify the Date instance being called - it creates and returns
+ * a new Date instance containing the resulting date value.
+ *
+ * Examples:
+ *
+// Basic usage:
+var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
+console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
+
+// Negative values will be subtracted:
+var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
+console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
+
+ *
+ *
+ * @param {Date} date The date to modify
+ * @param {String} interval A valid date interval enum value.
+ * @param {Number} value The amount to add to the current date.
+ * @return {Date} The new Date instance.
+ */
+ add : function(date, interval, value) {
+ var d = Ext.Date.clone(date),
+ Date = Ext.Date,
+ day;
+ if (!interval || value === 0) {
+ return d;
+ }
+
+ switch(interval.toLowerCase()) {
+ case Ext.Date.MILLI:
+ d.setMilliseconds(d.getMilliseconds() + value);
+ break;
+ case Ext.Date.SECOND:
+ d.setSeconds(d.getSeconds() + value);
+ break;
+ case Ext.Date.MINUTE:
+ d.setMinutes(d.getMinutes() + value);
+ break;
+ case Ext.Date.HOUR:
+ d.setHours(d.getHours() + value);
+ break;
+ case Ext.Date.DAY:
+ d.setDate(d.getDate() + value);
+ break;
+ case Ext.Date.MONTH:
+ day = date.getDate();
+ if (day > 28) {
+ day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.MONTH, value)).getDate());
+ }
+ d.setDate(day);
+ d.setMonth(date.getMonth() + value);
+ break;
+ case Ext.Date.YEAR:
+ day = date.getDate();
+ if (day > 28) {
+ day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.YEAR, value)).getDate());
+ }
+ d.setDate(day);
+ d.setFullYear(date.getFullYear() + value);
+ break;
+ }
+ return d;
+ },
+
+ /**
+ * Checks if a date falls on or between the given start and end dates.
+ * @param {Date} date The date to check
+ * @param {Date} start Start date
+ * @param {Date} end End date
+ * @return {Boolean} true if this date falls on or between the given start and end dates.
+ */
+ between : function(date, start, end) {
+ var t = date.getTime();
+ return start.getTime() <= t && t <= end.getTime();
+ },
+
+ //Maintains compatibility with old static and prototype window.Date methods.
+ compat: function() {
+ var nativeDate = window.Date,
+ p, u,
+ statics = ['useStrict', 'formatCodeToRegex', 'parseFunctions', 'parseRegexes', 'formatFunctions', 'y2kYear', 'MILLI', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR', 'defaults', 'dayNames', 'monthNames', 'monthNumbers', 'getShortMonthName', 'getShortDayName', 'getMonthNumber', 'formatCodes', 'isValid', 'parseDate', 'getFormatCode', 'createFormat', 'createParser', 'parseCodes'],
+ proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'],
+ sLen = statics.length,
+ pLen = proto.length,
+ stat, prot, s;
+
+ //Append statics
+ for (s = 0; s < sLen; s++) {
+ stat = statics[s];
+ nativeDate[stat] = utilDate[stat];
+ }
+
+ //Append to prototype
+ for (p = 0; p < pLen; p++) {
+ prot = proto[p];
+ nativeDate.prototype[prot] = function() {
+ var args = Array.prototype.slice.call(arguments);
+ args.unshift(this);
+ return utilDate[prot].apply(utilDate, args);
+ };
+ }
+ }
+};
+
+var utilDate = Ext.Date;
+
+}());
+
+//@tag foundation,core
+//@require ../lang/Date.js
+
+/**
+ * @author Jacky Nguyen
+ * @docauthor Jacky Nguyen
+ * @class Ext.Base
+ *
+ * The root of all classes created with {@link Ext#define}.
+ *
+ * Ext.Base is the building block of all Ext classes. All classes in Ext inherit from Ext.Base.
+ * All prototype and static members of this class are inherited by all other classes.
+ */
+(function(flexSetter) {
+
+var noArgs = [],
+ Base = function(){};
+
+ // These static properties will be copied to every newly created class with {@link Ext#define}
+ Ext.apply(Base, {
+ $className: 'Ext.Base',
+
+ $isClass: true,
+
+ /**
+ * Create a new instance of this Class.
+ *
+ * Ext.define('My.cool.Class', {
+ * ...
+ * });
+ *
+ * My.cool.Class.create({
+ * someConfig: true
+ * });
+ *
+ * All parameters are passed to the constructor of the class.
+ *
+ * @return {Object} the created instance.
+ * @static
+ * @inheritable
+ */
+ create: function() {
+ return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0)));
+ },
+
+ /**
+ * @private
+ * @static
+ * @inheritable
+ * @param config
+ */
+ extend: function(parent) {
+ var parentPrototype = parent.prototype,
+ basePrototype, prototype, i, ln, name, statics;
+
+ prototype = this.prototype = Ext.Object.chain(parentPrototype);
+ prototype.self = this;
+
+ this.superclass = prototype.superclass = parentPrototype;
+
+ if (!parent.$isClass) {
+ basePrototype = Ext.Base.prototype;
+
+ for (i in basePrototype) {
+ if (i in prototype) {
+ prototype[i] = basePrototype[i];
+ }
+ }
+ }
+
+ // Statics inheritance
+ statics = parentPrototype.$inheritableStatics;
+
+ if (statics) {
+ for (i = 0,ln = statics.length; i < ln; i++) {
+ name = statics[i];
+
+ if (!this.hasOwnProperty(name)) {
+ this[name] = parent[name];
+ }
+ }
+ }
+
+ if (parent.$onExtended) {
+ this.$onExtended = parent.$onExtended.slice();
+ }
+
+ prototype.config = new prototype.configClass();
+ prototype.initConfigList = prototype.initConfigList.slice();
+ prototype.initConfigMap = Ext.clone(prototype.initConfigMap);
+ prototype.configMap = Ext.Object.chain(prototype.configMap);
+ },
+
+ /**
+ * @private
+ * @static
+ * @inheritable
+ */
+ $onExtended: [],
+
+ /**
+ * @private
+ * @static
+ * @inheritable
+ */
+ triggerExtended: function() {
+ var callbacks = this.$onExtended,
+ ln = callbacks.length,
+ i, callback;
+
+ if (ln > 0) {
+ for (i = 0; i < ln; i++) {
+ callback = callbacks[i];
+ callback.fn.apply(callback.scope || this, arguments);
+ }
+ }
+ },
+
+ /**
+ * @private
+ * @static
+ * @inheritable
+ */
+ onExtended: function(fn, scope) {
+ this.$onExtended.push({
+ fn: fn,
+ scope: scope
+ });
+
+ return this;
+ },
+
+ /**
+ * @private
+ * @static
+ * @inheritable
+ * @param config
+ */
+ addConfig: function(config, fullMerge) {
+ var prototype = this.prototype,
+ configNameCache = Ext.Class.configNameCache,
+ hasConfig = prototype.configMap,
+ initConfigList = prototype.initConfigList,
+ initConfigMap = prototype.initConfigMap,
+ defaultConfig = prototype.config,
+ initializedName, name, value;
+
+ for (name in config) {
+ if (config.hasOwnProperty(name)) {
+ if (!hasConfig[name]) {
+ hasConfig[name] = true;
+ }
+
+ value = config[name];
+
+ initializedName = configNameCache[name].initialized;
+
+ if (!initConfigMap[name] && value !== null && !prototype[initializedName]) {
+ initConfigMap[name] = true;
+ initConfigList.push(name);
+ }
+ }
+ }
+
+ if (fullMerge) {
+ Ext.merge(defaultConfig, config);
+ }
+ else {
+ Ext.mergeIf(defaultConfig, config);
+ }
+
+ prototype.configClass = Ext.Object.classify(defaultConfig);
+ },
+
+ /**
+ * Add / override static properties of this class.
+ *
+ * Ext.define('My.cool.Class', {
+ * ...
+ * });
+ *
+ * My.cool.Class.addStatics({
+ * someProperty: 'someValue', // My.cool.Class.someProperty = 'someValue'
+ * method1: function() { ... }, // My.cool.Class.method1 = function() { ... };
+ * method2: function() { ... } // My.cool.Class.method2 = function() { ... };
+ * });
+ *
+ * @param {Object} members
+ * @return {Ext.Base} this
+ * @static
+ * @inheritable
+ */
+ addStatics: function(members) {
+ var member, name;
+
+ for (name in members) {
+ if (members.hasOwnProperty(name)) {
+ member = members[name];
+ if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn && member !== Ext.identityFn) {
+ member.$owner = this;
+ member.$name = name;
+ member.displayName = Ext.getClassName(this) + '.' + name;
+ }
+ this[name] = member;
+ }
+ }
+
+ return this;
+ },
+
+ /**
+ * @private
+ * @static
+ * @inheritable
+ * @param {Object} members
+ */
+ addInheritableStatics: function(members) {
+ var inheritableStatics,
+ hasInheritableStatics,
+ prototype = this.prototype,
+ name, member;
+
+ inheritableStatics = prototype.$inheritableStatics;
+ hasInheritableStatics = prototype.$hasInheritableStatics;
+
+ if (!inheritableStatics) {
+ inheritableStatics = prototype.$inheritableStatics = [];
+ hasInheritableStatics = prototype.$hasInheritableStatics = {};
+ }
+
+ for (name in members) {
+ if (members.hasOwnProperty(name)) {
+ member = members[name];
+ if (typeof member == 'function') {
+ member.displayName = Ext.getClassName(this) + '.' + name;
+ }
+ this[name] = member;
+
+ if (!hasInheritableStatics[name]) {
+ hasInheritableStatics[name] = true;
+ inheritableStatics.push(name);
+ }
+ }
+ }
+
+ return this;
+ },
+
+ /**
+ * Add methods / properties to the prototype of this class.
+ *
+ * Ext.define('My.awesome.Cat', {
+ * constructor: function() {
+ * ...
+ * }
+ * });
+ *
+ * My.awesome.Cat.addMembers({
+ * meow: function() {
+ * alert('Meowww...');
+ * }
+ * });
+ *
+ * var kitty = new My.awesome.Cat;
+ * kitty.meow();
+ *
+ * @param {Object} members
+ * @static
+ * @inheritable
+ */
+ addMembers: function(members) {
+ var prototype = this.prototype,
+ enumerables = Ext.enumerables,
+ names = [],
+ i, ln, name, member;
+
+ for (name in members) {
+ names.push(name);
+ }
+
+ if (enumerables) {
+ names.push.apply(names, enumerables);
+ }
+
+ for (i = 0,ln = names.length; i < ln; i++) {
+ name = names[i];
+
+ if (members.hasOwnProperty(name)) {
+ member = members[name];
+
+ if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) {
+ member.$owner = this;
+ member.$name = name;
+ member.displayName = (this.$className || '') + '#' + name;
+ }
+
+ prototype[name] = member;
+ }
+ }
+
+ return this;
+ },
+
+ /**
+ * @private
+ * @static
+ * @inheritable
+ * @param name
+ * @param member
+ */
+ addMember: function(name, member) {
+ if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) {
+ member.$owner = this;
+ member.$name = name;
+ member.displayName = (this.$className || '') + '#' + name;
+ }
+
+ this.prototype[name] = member;
+
+ return this;
+ },
+
+ /**
+ * Adds members to class.
+ * @static
+ * @inheritable
+ * @deprecated 4.1 Use {@link #addMembers} instead.
+ */
+ implement: function() {
+ this.addMembers.apply(this, arguments);
+ },
+
+ /**
+ * Borrow another class' members to the prototype of this class.
+ *
+ * Ext.define('Bank', {
+ * money: '$$$',
+ * printMoney: function() {
+ * alert('$$$$$$$');
+ * }
+ * });
+ *
+ * Ext.define('Thief', {
+ * ...
+ * });
+ *
+ * Thief.borrow(Bank, ['money', 'printMoney']);
+ *
+ * var steve = new Thief();
+ *
+ * alert(steve.money); // alerts '$$$'
+ * steve.printMoney(); // alerts '$$$$$$$'
+ *
+ * @param {Ext.Base} fromClass The class to borrow members from
+ * @param {Array/String} members The names of the members to borrow
+ * @return {Ext.Base} this
+ * @static
+ * @inheritable
+ * @private
+ */
+ borrow: function(fromClass, members) {
+ var prototype = this.prototype,
+ fromPrototype = fromClass.prototype,
+ className = Ext.getClassName(this),
+ i, ln, name, fn, toBorrow;
+
+ members = Ext.Array.from(members);
+
+ for (i = 0,ln = members.length; i < ln; i++) {
+ name = members[i];
+
+ toBorrow = fromPrototype[name];
+
+ if (typeof toBorrow == 'function') {
+ fn = Ext.Function.clone(toBorrow);
+
+ if (className) {
+ fn.displayName = className + '#' + name;
+ }
+
+ fn.$owner = this;
+ fn.$name = name;
+
+ prototype[name] = fn;
+ }
+ else {
+ prototype[name] = toBorrow;
+ }
+ }
+
+ return this;
+ },
+
+ /**
+ * Override members of this class. Overridden methods can be invoked via
+ * {@link Ext.Base#callParent}.
+ *
+ * Ext.define('My.Cat', {
+ * constructor: function() {
+ * alert("I'm a cat!");
+ * }
+ * });
+ *
+ * My.Cat.override({
+ * constructor: function() {
+ * alert("I'm going to be a cat!");
+ *
+ * this.callParent(arguments);
+ *
+ * alert("Meeeeoooowwww");
+ * }
+ * });
+ *
+ * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
+ * // alerts "I'm a cat!"
+ * // alerts "Meeeeoooowwww"
+ *
+ * As of 4.1, direct use of this method is deprecated. Use {@link Ext#define Ext.define}
+ * instead:
+ *
+ * Ext.define('My.CatOverride', {
+ * override: 'My.Cat',
+ * constructor: function() {
+ * alert("I'm going to be a cat!");
+ *
+ * this.callParent(arguments);
+ *
+ * alert("Meeeeoooowwww");
+ * }
+ * });
+ *
+ * The above accomplishes the same result but can be managed by the {@link Ext.Loader}
+ * which can properly order the override and its target class and the build process
+ * can determine whether the override is needed based on the required state of the
+ * target class (My.Cat).
+ *
+ * @param {Object} members The properties to add to this class. This should be
+ * specified as an object literal containing one or more properties.
+ * @return {Ext.Base} this class
+ * @static
+ * @inheritable
+ * @markdown
+ * @deprecated 4.1.0 Use {@link Ext#define Ext.define} instead
+ */
+ override: function(members) {
+ var me = this,
+ enumerables = Ext.enumerables,
+ target = me.prototype,
+ cloneFunction = Ext.Function.clone,
+ name, index, member, statics, names, previous;
+
+ if (arguments.length === 2) {
+ name = members;
+ members = {};
+ members[name] = arguments[1];
+ enumerables = null;
+ }
+
+ do {
+ names = []; // clean slate for prototype (1st pass) and static (2nd pass)
+ statics = null; // not needed 1st pass, but needs to be cleared for 2nd pass
+
+ for (name in members) { // hasOwnProperty is checked in the next loop...
+ if (name == 'statics') {
+ statics = members[name];
+ } else if (name == 'config') {
+ me.addConfig(members[name], true);
+ } else {
+ names.push(name);
+ }
+ }
+
+ if (enumerables) {
+ names.push.apply(names, enumerables);
+ }
+
+ for (index = names.length; index--; ) {
+ name = names[index];
+
+ if (members.hasOwnProperty(name)) {
+ member = members[name];
+
+ if (typeof member == 'function' && !member.$className && member !== Ext.emptyFn) {
+ if (typeof member.$owner != 'undefined') {
+ member = cloneFunction(member);
+ }
+
+ if (me.$className) {
+ member.displayName = me.$className + '#' + name;
+ }
+
+ member.$owner = me;
+ member.$name = name;
+
+ previous = target[name];
+ if (previous) {
+ member.$previous = previous;
+ }
+ }
+
+ target[name] = member;
+ }
+ }
+
+ target = me; // 2nd pass is for statics
+ members = statics; // statics will be null on 2nd pass
+ } while (members);
+
+ return this;
+ },
+
+ // Documented downwards
+ callParent: function(args) {
+ var method;
+
+ // This code is intentionally inlined for the least number of debugger stepping
+ return (method = this.callParent.caller) && (method.$previous ||
+ ((method = method.$owner ? method : method.caller) &&
+ method.$owner.superclass.self[method.$name])).apply(this, args || noArgs);
+ },
+
+ // Documented downwards
+ callSuper: function(args) {
+ var method;
+
+ // This code is intentionally inlined for the least number of debugger stepping
+ return (method = this.callSuper.caller) &&
+ ((method = method.$owner ? method : method.caller) &&
+ method.$owner.superclass.self[method.$name]).apply(this, args || noArgs);
+ },
+
+ /**
+ * Used internally by the mixins pre-processor
+ * @private
+ * @static
+ * @inheritable
+ */
+ mixin: function(name, mixinClass) {
+ var mixin = mixinClass.prototype,
+ prototype = this.prototype,
+ key;
+
+ if (typeof mixin.onClassMixedIn != 'undefined') {
+ mixin.onClassMixedIn.call(mixinClass, this);
+ }
+
+ if (!prototype.hasOwnProperty('mixins')) {
+ if ('mixins' in prototype) {
+ prototype.mixins = Ext.Object.chain(prototype.mixins);
+ }
+ else {
+ prototype.mixins = {};
+ }
+ }
+
+ for (key in mixin) {
+ if (key === 'mixins') {
+ Ext.merge(prototype.mixins, mixin[key]);
+ }
+ else if (typeof prototype[key] == 'undefined' && key != 'mixinId' && key != 'config') {
+ prototype[key] = mixin[key];
+ }
+ }
+
+ if ('config' in mixin) {
+ this.addConfig(mixin.config, false);
+ }
+
+ prototype.mixins[name] = mixin;
+ },
+
+ /**
+ * Get the current class' name in string format.
+ *
+ * Ext.define('My.cool.Class', {
+ * constructor: function() {
+ * alert(this.self.getName()); // alerts 'My.cool.Class'
+ * }
+ * });
+ *
+ * My.cool.Class.getName(); // 'My.cool.Class'
+ *
+ * @return {String} className
+ * @static
+ * @inheritable
+ */
+ getName: function() {
+ return Ext.getClassName(this);
+ },
+
+ /**
+ * Create aliases for existing prototype methods. Example:
+ *
+ * Ext.define('My.cool.Class', {
+ * method1: function() { ... },
+ * method2: function() { ... }
+ * });
+ *
+ * var test = new My.cool.Class();
+ *
+ * My.cool.Class.createAlias({
+ * method3: 'method1',
+ * method4: 'method2'
+ * });
+ *
+ * test.method3(); // test.method1()
+ *
+ * My.cool.Class.createAlias('method5', 'method3');
+ *
+ * test.method5(); // test.method3() -> test.method1()
+ *
+ * @param {String/Object} alias The new method name, or an object to set multiple aliases. See
+ * {@link Ext.Function#flexSetter flexSetter}
+ * @param {String/Object} origin The original method name
+ * @static
+ * @inheritable
+ * @method
+ */
+ createAlias: flexSetter(function(alias, origin) {
+ this.override(alias, function() {
+ return this[origin].apply(this, arguments);
+ });
+ }),
+
+ /**
+ * @private
+ * @static
+ * @inheritable
+ */
+ addXtype: function(xtype) {
+ var prototype = this.prototype,
+ xtypesMap = prototype.xtypesMap,
+ xtypes = prototype.xtypes,
+ xtypesChain = prototype.xtypesChain;
+
+ if (!prototype.hasOwnProperty('xtypesMap')) {
+ xtypesMap = prototype.xtypesMap = Ext.merge({}, prototype.xtypesMap || {});
+ xtypes = prototype.xtypes = prototype.xtypes ? [].concat(prototype.xtypes) : [];
+ xtypesChain = prototype.xtypesChain = prototype.xtypesChain ? [].concat(prototype.xtypesChain) : [];
+ prototype.xtype = xtype;
+ }
+
+ if (!xtypesMap[xtype]) {
+ xtypesMap[xtype] = true;
+ xtypes.push(xtype);
+ xtypesChain.push(xtype);
+ Ext.ClassManager.setAlias(this, 'widget.' + xtype);
+ }
+
+ return this;
+ }
+ });
+
+ Base.implement({
+ /** @private */
+ isInstance: true,
+
+ /** @private */
+ $className: 'Ext.Base',
+
+ /** @private */
+ configClass: Ext.emptyFn,
+
+ /** @private */
+ initConfigList: [],
+
+ /** @private */
+ configMap: {},
+
+ /** @private */
+ initConfigMap: {},
+
+ /**
+ * Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self},
+ * `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what
+ * `this` points to during run-time
+ *
+ * Ext.define('My.Cat', {
+ * statics: {
+ * totalCreated: 0,
+ * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
+ * },
+ *
+ * constructor: function() {
+ * var statics = this.statics();
+ *
+ * alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to
+ * // equivalent to: My.Cat.speciesName
+ *
+ * alert(this.self.speciesName); // dependent on 'this'
+ *
+ * statics.totalCreated++;
+ * },
+ *
+ * clone: function() {
+ * var cloned = new this.self; // dependent on 'this'
+ *
+ * cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName
+ *
+ * return cloned;
+ * }
+ * });
+ *
+ *
+ * Ext.define('My.SnowLeopard', {
+ * extend: 'My.Cat',
+ *
+ * statics: {
+ * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
+ * },
+ *
+ * constructor: function() {
+ * this.callParent();
+ * }
+ * });
+ *
+ * var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat'
+ *
+ * var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
+ *
+ * var clone = snowLeopard.clone();
+ * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
+ * alert(clone.groupName); // alerts 'Cat'
+ *
+ * alert(My.Cat.totalCreated); // alerts 3
+ *
+ * @protected
+ * @return {Ext.Class}
+ */
+ statics: function() {
+ var method = this.statics.caller,
+ self = this.self;
+
+ if (!method) {
+ return self;
+ }
+
+ return method.$owner;
+ },
+
+ /**
+ * Call the "parent" method of the current method. That is the method previously
+ * overridden by derivation or by an override (see {@link Ext#define}).
+ *
+ * Ext.define('My.Base', {
+ * constructor: function (x) {
+ * this.x = x;
+ * },
+ *
+ * statics: {
+ * method: function (x) {
+ * return x;
+ * }
+ * }
+ * });
+ *
+ * Ext.define('My.Derived', {
+ * extend: 'My.Base',
+ *
+ * constructor: function () {
+ * this.callParent([21]);
+ * }
+ * });
+ *
+ * var obj = new My.Derived();
+ *
+ * alert(obj.x); // alerts 21
+ *
+ * This can be used with an override as follows:
+ *
+ * Ext.define('My.DerivedOverride', {
+ * override: 'My.Derived',
+ *
+ * constructor: function (x) {
+ * this.callParent([x*2]); // calls original My.Derived constructor
+ * }
+ * });
+ *
+ * var obj = new My.Derived();
+ *
+ * alert(obj.x); // now alerts 42
+ *
+ * This also works with static methods.
+ *
+ * Ext.define('My.Derived2', {
+ * extend: 'My.Base',
+ *
+ * statics: {
+ * method: function (x) {
+ * return this.callParent([x*2]); // calls My.Base.method
+ * }
+ * }
+ * });
+ *
+ * alert(My.Base.method(10); // alerts 10
+ * alert(My.Derived2.method(10); // alerts 20
+ *
+ * Lastly, it also works with overridden static methods.
+ *
+ * Ext.define('My.Derived2Override', {
+ * override: 'My.Derived2',
+ *
+ * statics: {
+ * method: function (x) {
+ * return this.callParent([x*2]); // calls My.Derived2.method
+ * }
+ * }
+ * });
+ *
+ * alert(My.Derived2.method(10); // now alerts 40
+ *
+ * To override a method and replace it and also call the superclass method, use
+ * {@link #callSuper}. This is often done to patch a method to fix a bug.
+ *
+ * @protected
+ * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
+ * from the current method, for example: `this.callParent(arguments)`
+ * @return {Object} Returns the result of calling the parent method
+ */
+ callParent: function(args) {
+ // NOTE: this code is deliberately as few expressions (and no function calls)
+ // as possible so that a debugger can skip over this noise with the minimum number
+ // of steps. Basically, just hit Step Into until you are where you really wanted
+ // to be.
+ var method,
+ superMethod = (method = this.callParent.caller) && (method.$previous ||
+ ((method = method.$owner ? method : method.caller) &&
+ method.$owner.superclass[method.$name]));
+
+ if (!superMethod) {
+ method = this.callParent.caller;
+ var parentClass, methodName;
+
+ if (!method.$owner) {
+ if (!method.caller) {
+ throw new Error("Attempting to call a protected method from the public scope, which is not allowed");
+ }
+
+ method = method.caller;
+ }
+
+ parentClass = method.$owner.superclass;
+ methodName = method.$name;
+
+ if (!(methodName in parentClass)) {
+ throw new Error("this.callParent() was called but there's no such method (" + methodName +
+ ") found in the parent class (" + (Ext.getClassName(parentClass) || 'Object') + ")");
+ }
+ }
+
+ return superMethod.apply(this, args || noArgs);
+ },
+
+ /**
+ * This method is used by an override to call the superclass method but bypass any
+ * overridden method. This is often done to "patch" a method that contains a bug
+ * but for whatever reason cannot be fixed directly.
+ *
+ * Consider:
+ *
+ * Ext.define('Ext.some.Class', {
+ * method: function () {
+ * console.log('Good');
+ * }
+ * });
+ *
+ * Ext.define('Ext.some.DerivedClass', {
+ * method: function () {
+ * console.log('Bad');
+ *
+ * // ... logic but with a bug ...
+ *
+ * this.callParent();
+ * }
+ * });
+ *
+ * To patch the bug in `DerivedClass.method`, the typical solution is to create an
+ * override:
+ *
+ * Ext.define('App.paches.DerivedClass', {
+ * override: 'Ext.some.DerivedClass',
+ *
+ * method: function () {
+ * console.log('Fixed');
+ *
+ * // ... logic but with bug fixed ...
+ *
+ * this.callSuper();
+ * }
+ * });
+ *
+ * The patch method cannot use `callParent` to call the superclass `method` since
+ * that would call the overridden method containing the bug. In other words, the
+ * above patch would only produce "Fixed" then "Good" in the console log, whereas,
+ * using `callParent` would produce "Fixed" then "Bad" then "Good".
+ *
+ * @protected
+ * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
+ * from the current method, for example: `this.callSuper(arguments)`
+ * @return {Object} Returns the result of calling the superclass method
+ */
+ callSuper: function(args) {
+ // NOTE: this code is deliberately as few expressions (and no function calls)
+ // as possible so that a debugger can skip over this noise with the minimum number
+ // of steps. Basically, just hit Step Into until you are where you really wanted
+ // to be.
+ var method,
+ superMethod = (method = this.callSuper.caller) &&
+ ((method = method.$owner ? method : method.caller) &&
+ method.$owner.superclass[method.$name]);
+
+ if (!superMethod) {
+ method = this.callSuper.caller;
+ var parentClass, methodName;
+
+ if (!method.$owner) {
+ if (!method.caller) {
+ throw new Error("Attempting to call a protected method from the public scope, which is not allowed");
+ }
+
+ method = method.caller;
+ }
+
+ parentClass = method.$owner.superclass;
+ methodName = method.$name;
+
+ if (!(methodName in parentClass)) {
+ throw new Error("this.callSuper() was called but there's no such method (" + methodName +
+ ") found in the parent class (" + (Ext.getClassName(parentClass) || 'Object') + ")");
+ }
+ }
+
+ return superMethod.apply(this, args || noArgs);
+ },
+
+ /**
+ * @property {Ext.Class} self
+ *
+ * Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics},
+ * `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics}
+ * for a detailed comparison
+ *
+ * Ext.define('My.Cat', {
+ * statics: {
+ * speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
+ * },
+ *
+ * constructor: function() {
+ * alert(this.self.speciesName); // dependent on 'this'
+ * },
+ *
+ * clone: function() {
+ * return new this.self();
+ * }
+ * });
+ *
+ *
+ * Ext.define('My.SnowLeopard', {
+ * extend: 'My.Cat',
+ * statics: {
+ * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
+ * }
+ * });
+ *
+ * var cat = new My.Cat(); // alerts 'Cat'
+ * var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'
+ *
+ * var clone = snowLeopard.clone();
+ * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
+ *
+ * @protected
+ */
+ self: Base,
+
+ // Default constructor, simply returns `this`
+ constructor: function() {
+ return this;
+ },
+
+ /**
+ * Initialize configuration for this class. a typical example:
+ *
+ * Ext.define('My.awesome.Class', {
+ * // The default config
+ * config: {
+ * name: 'Awesome',
+ * isAwesome: true
+ * },
+ *
+ * constructor: function(config) {
+ * this.initConfig(config);
+ * }
+ * });
+ *
+ * var awesome = new My.awesome.Class({
+ * name: 'Super Awesome'
+ * });
+ *
+ * alert(awesome.getName()); // 'Super Awesome'
+ *
+ * @protected
+ * @param {Object} config
+ * @return {Ext.Base} this
+ */
+ initConfig: function(config) {
+ var instanceConfig = config,
+ configNameCache = Ext.Class.configNameCache,
+ defaultConfig = new this.configClass(),
+ defaultConfigList = this.initConfigList,
+ hasConfig = this.configMap,
+ nameMap, i, ln, name, initializedName;
+
+ this.initConfig = Ext.emptyFn;
+
+ this.initialConfig = instanceConfig || {};
+
+ this.config = config = (instanceConfig) ? Ext.merge(defaultConfig, config) : defaultConfig;
+
+ if (instanceConfig) {
+ defaultConfigList = defaultConfigList.slice();
+
+ for (name in instanceConfig) {
+ if (hasConfig[name]) {
+ if (instanceConfig[name] !== null) {
+ defaultConfigList.push(name);
+ this[configNameCache[name].initialized] = false;
+ }
+ }
+ }
+ }
+
+ for (i = 0,ln = defaultConfigList.length; i < ln; i++) {
+ name = defaultConfigList[i];
+ nameMap = configNameCache[name];
+ initializedName = nameMap.initialized;
+
+ if (!this[initializedName]) {
+ this[initializedName] = true;
+ this[nameMap.set].call(this, config[name]);
+ }
+ }
+
+ return this;
+ },
+
+ /**
+ * @private
+ * @param config
+ */
+ hasConfig: function(name) {
+ return Boolean(this.configMap[name]);
+ },
+
+ /**
+ * @private
+ */
+ setConfig: function(config, applyIfNotSet) {
+ if (!config) {
+ return this;
+ }
+
+ var configNameCache = Ext.Class.configNameCache,
+ currentConfig = this.config,
+ hasConfig = this.configMap,
+ initialConfig = this.initialConfig,
+ name, value;
+
+ applyIfNotSet = Boolean(applyIfNotSet);
+
+ for (name in config) {
+ if (applyIfNotSet && initialConfig.hasOwnProperty(name)) {
+ continue;
+ }
+
+ value = config[name];
+ currentConfig[name] = value;
+
+ if (hasConfig[name]) {
+ this[configNameCache[name].set](value);
+ }
+ }
+
+ return this;
+ },
+
+ /**
+ * @private
+ * @param name
+ */
+ getConfig: function(name) {
+ var configNameCache = Ext.Class.configNameCache;
+
+ return this[configNameCache[name].get]();
+ },
+
+ /**
+ * Returns the initial configuration passed to constructor when instantiating
+ * this class.
+ * @param {String} [name] Name of the config option to return.
+ * @return {Object/Mixed} The full config object or a single config value
+ * when `name` parameter specified.
+ */
+ getInitialConfig: function(name) {
+ var config = this.config;
+
+ if (!name) {
+ return config;
+ }
+ else {
+ return config[name];
+ }
+ },
+
+ /**
+ * @private
+ * @param names
+ * @param callback
+ * @param scope
+ */
+ onConfigUpdate: function(names, callback, scope) {
+ var self = this.self,
+ className = self.$className,
+ i, ln, name,
+ updaterName, updater, newUpdater;
+
+ names = Ext.Array.from(names);
+
+ scope = scope || this;
+
+ for (i = 0,ln = names.length; i < ln; i++) {
+ name = names[i];
+ updaterName = 'update' + Ext.String.capitalize(name);
+ updater = this[updaterName] || Ext.emptyFn;
+ newUpdater = function() {
+ updater.apply(this, arguments);
+ scope[callback].apply(scope, arguments);
+ };
+ newUpdater.$name = updaterName;
+ newUpdater.$owner = self;
+ newUpdater.displayName = className + '#' + updaterName;
+
+ this[updaterName] = newUpdater;
+ }
+ },
+
+ /**
+ * @private
+ */
+ destroy: function() {
+ this.destroy = Ext.emptyFn;
+ }
+ });
+
+ /**
+ * Call the original method that was previously overridden with {@link Ext.Base#override}
+ *
+ * Ext.define('My.Cat', {
+ * constructor: function() {
+ * alert("I'm a cat!");
+ * }
+ * });
+ *
+ * My.Cat.override({
+ * constructor: function() {
+ * alert("I'm going to be a cat!");
+ *
+ * this.callOverridden();
+ *
+ * alert("Meeeeoooowwww");
+ * }
+ * });
+ *
+ * var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
+ * // alerts "I'm a cat!"
+ * // alerts "Meeeeoooowwww"
+ *
+ * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
+ * from the current method, for example: `this.callOverridden(arguments)`
+ * @return {Object} Returns the result of calling the overridden method
+ * @protected
+ * @deprecated as of 4.1. Use {@link #callParent} instead.
+ */
+ Base.prototype.callOverridden = Base.prototype.callParent;
+
+ Ext.Base = Base;
+
+}(Ext.Function.flexSetter));
+
+//@tag foundation,core
+//@require Base.js
+
+/**
+ * @author Jacky Nguyen
+ * @docauthor Jacky Nguyen
+ * @class Ext.Class
+ *
+ * Handles class creation throughout the framework. This is a low level factory that is used by Ext.ClassManager and generally
+ * should not be used directly. If you choose to use Ext.Class you will lose out on the namespace, aliasing and depency loading
+ * features made available by Ext.ClassManager. The only time you would use Ext.Class directly is to create an anonymous class.
+ *
+ * If you wish to create a class you should use {@link Ext#define Ext.define} which aliases
+ * {@link Ext.ClassManager#create Ext.ClassManager.create} to enable namespacing and dynamic dependency resolution.
+ *
+ * Ext.Class is the factory and **not** the superclass of everything. For the base class that **all** Ext classes inherit
+ * from, see {@link Ext.Base}.
+ */
+(function() {
+ var ExtClass,
+ Base = Ext.Base,
+ baseStaticMembers = [],
+ baseStaticMember, baseStaticMemberLength;
+
+ for (baseStaticMember in Base) {
+ if (Base.hasOwnProperty(baseStaticMember)) {
+ baseStaticMembers.push(baseStaticMember);
+ }
+ }
+
+ baseStaticMemberLength = baseStaticMembers.length;
+
+ // Creates a constructor that has nothing extra in its scope chain.
+ function makeCtor (className) {
+ function constructor () {
+ // Opera has some problems returning from a constructor when Dragonfly isn't running. The || null seems to
+ // be sufficient to stop it misbehaving. Known to be required against 10.53, 11.51 and 11.61.
+ return this.constructor.apply(this, arguments) || null;
+ }
+ if (className) {
+ constructor.displayName = className;
+ }
+ return constructor;
+ }
+
+ /**
+ * @method constructor
+ * Create a new anonymous class.
+ *
+ * @param {Object} data An object represent the properties of this class
+ * @param {Function} onCreated Optional, the callback function to be executed when this class is fully created.
+ * Note that the creation process can be asynchronous depending on the pre-processors used.
+ *
+ * @return {Ext.Base} The newly created class
+ */
+ Ext.Class = ExtClass = function(Class, data, onCreated) {
+ if (typeof Class != 'function') {
+ onCreated = data;
+ data = Class;
+ Class = null;
+ }
+
+ if (!data) {
+ data = {};
+ }
+
+ Class = ExtClass.create(Class, data);
+
+ ExtClass.process(Class, data, onCreated);
+
+ return Class;
+ };
+
+ Ext.apply(ExtClass, {
+ /**
+ * @private
+ * @param Class
+ * @param data
+ * @param hooks
+ */
+ onBeforeCreated: function(Class, data, hooks) {
+ Class.addMembers(data);
+
+ hooks.onCreated.call(Class, Class);
+ },
+
+ /**
+ * @private
+ * @param Class
+ * @param classData
+ * @param onClassCreated
+ */
+ create: function(Class, data) {
+ var name, i;
+
+ if (!Class) {
+ Class = makeCtor(
+ data.$className
+ );
+ }
+
+ for (i = 0; i < baseStaticMemberLength; i++) {
+ name = baseStaticMembers[i];
+ Class[name] = Base[name];
+ }
+
+ return Class;
+ },
+
+ /**
+ * @private
+ * @param Class
+ * @param data
+ * @param onCreated
+ */
+ process: function(Class, data, onCreated) {
+ var preprocessorStack = data.preprocessors || ExtClass.defaultPreprocessors,
+ registeredPreprocessors = this.preprocessors,
+ hooks = {
+ onBeforeCreated: this.onBeforeCreated
+ },
+ preprocessors = [],
+ preprocessor, preprocessorsProperties,
+ i, ln, j, subLn, preprocessorProperty, process;
+
+ delete data.preprocessors;
+
+ for (i = 0,ln = preprocessorStack.length; i < ln; i++) {
+ preprocessor = preprocessorStack[i];
+
+ if (typeof preprocessor == 'string') {
+ preprocessor = registeredPreprocessors[preprocessor];
+ preprocessorsProperties = preprocessor.properties;
+
+ if (preprocessorsProperties === true) {
+ preprocessors.push(preprocessor.fn);
+ }
+ else if (preprocessorsProperties) {
+ for (j = 0,subLn = preprocessorsProperties.length; j < subLn; j++) {
+ preprocessorProperty = preprocessorsProperties[j];
+
+ if (data.hasOwnProperty(preprocessorProperty)) {
+ preprocessors.push(preprocessor.fn);
+ break;
+ }
+ }
+ }
+ }
+ else {
+ preprocessors.push(preprocessor);
+ }
+ }
+
+ hooks.onCreated = onCreated ? onCreated : Ext.emptyFn;
+ hooks.preprocessors = preprocessors;
+
+ this.doProcess(Class, data, hooks);
+ },
+
+ doProcess: function(Class, data, hooks){
+ var me = this,
+ preprocessor = hooks.preprocessors.shift();
+
+ if (!preprocessor) {
+ hooks.onBeforeCreated.apply(me, arguments);
+ return;
+ }
+
+ if (preprocessor.call(me, Class, data, hooks, me.doProcess) !== false) {
+ me.doProcess(Class, data, hooks);
+ }
+ },
+
+ /** @private */
+ preprocessors: {},
+
+ /**
+ * Register a new pre-processor to be used during the class creation process
+ *
+ * @param {String} name The pre-processor's name
+ * @param {Function} fn The callback function to be executed. Typical format:
+ *
+ * function(cls, data, fn) {
+ * // Your code here
+ *
+ * // Execute this when the processing is finished.
+ * // Asynchronous processing is perfectly ok
+ * if (fn) {
+ * fn.call(this, cls, data);
+ * }
+ * });
+ *
+ * @param {Function} fn.cls The created class
+ * @param {Object} fn.data The set of properties passed in {@link Ext.Class} constructor
+ * @param {Function} fn.fn The callback function that **must** to be executed when this
+ * pre-processor finishes, regardless of whether the processing is synchronous or aynchronous.
+ * @return {Ext.Class} this
+ * @private
+ * @static
+ */
+ registerPreprocessor: function(name, fn, properties, position, relativeTo) {
+ if (!position) {
+ position = 'last';
+ }
+
+ if (!properties) {
+ properties = [name];
+ }
+
+ this.preprocessors[name] = {
+ name: name,
+ properties: properties || false,
+ fn: fn
+ };
+
+ this.setDefaultPreprocessorPosition(name, position, relativeTo);
+
+ return this;
+ },
+
+ /**
+ * Retrieve a pre-processor callback function by its name, which has been registered before
+ *
+ * @param {String} name
+ * @return {Function} preprocessor
+ * @private
+ * @static
+ */
+ getPreprocessor: function(name) {
+ return this.preprocessors[name];
+ },
+
+ /**
+ * @private
+ */
+ getPreprocessors: function() {
+ return this.preprocessors;
+ },
+
+ /**
+ * @private
+ */
+ defaultPreprocessors: [],
+
+ /**
+ * Retrieve the array stack of default pre-processors
+ * @return {Function[]} defaultPreprocessors
+ * @private
+ * @static
+ */
+ getDefaultPreprocessors: function() {
+ return this.defaultPreprocessors;
+ },
+
+ /**
+ * Set the default array stack of default pre-processors
+ *
+ * @private
+ * @param {Array} preprocessors
+ * @return {Ext.Class} this
+ * @static
+ */
+ setDefaultPreprocessors: function(preprocessors) {
+ this.defaultPreprocessors = Ext.Array.from(preprocessors);
+
+ return this;
+ },
+
+ /**
+ * Insert this pre-processor at a specific position in the stack, optionally relative to
+ * any existing pre-processor. For example:
+ *
+ * Ext.Class.registerPreprocessor('debug', function(cls, data, fn) {
+ * // Your code here
+ *
+ * if (fn) {
+ * fn.call(this, cls, data);
+ * }
+ * }).setDefaultPreprocessorPosition('debug', 'last');
+ *
+ * @private
+ * @param {String} name The pre-processor name. Note that it needs to be registered with
+ * {@link Ext.Class#registerPreprocessor registerPreprocessor} before this
+ * @param {String} offset The insertion position. Four possible values are:
+ * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
+ * @param {String} relativeName
+ * @return {Ext.Class} this
+ * @static
+ */
+ setDefaultPreprocessorPosition: function(name, offset, relativeName) {
+ var defaultPreprocessors = this.defaultPreprocessors,
+ index;
+
+ if (typeof offset == 'string') {
+ if (offset === 'first') {
+ defaultPreprocessors.unshift(name);
+
+ return this;
+ }
+ else if (offset === 'last') {
+ defaultPreprocessors.push(name);
+
+ return this;
+ }
+
+ offset = (offset === 'after') ? 1 : -1;
+ }
+
+ index = Ext.Array.indexOf(defaultPreprocessors, relativeName);
+
+ if (index !== -1) {
+ Ext.Array.splice(defaultPreprocessors, Math.max(0, index + offset), 0, name);
+ }
+
+ return this;
+ },
+
+ configNameCache: {},
+
+ getConfigNameMap: function(name) {
+ var cache = this.configNameCache,
+ map = cache[name],
+ capitalizedName;
+
+ if (!map) {
+ capitalizedName = name.charAt(0).toUpperCase() + name.substr(1);
+
+ map = cache[name] = {
+ internal: name,
+ initialized: '_is' + capitalizedName + 'Initialized',
+ apply: 'apply' + capitalizedName,
+ update: 'update' + capitalizedName,
+ 'set': 'set' + capitalizedName,
+ 'get': 'get' + capitalizedName,
+ doSet : 'doSet' + capitalizedName,
+ changeEvent: name.toLowerCase() + 'change'
+ };
+ }
+
+ return map;
+ }
+ });
+
+ /**
+ * @cfg {String} extend
+ * The parent class that this class extends. For example:
+ *
+ * Ext.define('Person', {
+ * say: function(text) { alert(text); }
+ * });
+ *
+ * Ext.define('Developer', {
+ * extend: 'Person',
+ * say: function(text) { this.callParent(["print "+text]); }
+ * });
+ */
+ ExtClass.registerPreprocessor('extend', function(Class, data) {
+ var Base = Ext.Base,
+ basePrototype = Base.prototype,
+ extend = data.extend,
+ Parent, parentPrototype, i;
+
+ delete data.extend;
+
+ if (extend && extend !== Object) {
+ Parent = extend;
+ }
+ else {
+ Parent = Base;
+ }
+
+ parentPrototype = Parent.prototype;
+
+ if (!Parent.$isClass) {
+ for (i in basePrototype) {
+ if (!parentPrototype[i]) {
+ parentPrototype[i] = basePrototype[i];
+ }
+ }
+ }
+
+ Class.extend(Parent);
+
+ Class.triggerExtended.apply(Class, arguments);
+
+ if (data.onClassExtended) {
+ Class.onExtended(data.onClassExtended, Class);
+ delete data.onClassExtended;
+ }
+
+ }, true);
+
+ /**
+ * @cfg {Object} statics
+ * List of static methods for this class. For example:
+ *
+ * Ext.define('Computer', {
+ * statics: {
+ * factory: function(brand) {
+ * // 'this' in static methods refer to the class itself
+ * return new this(brand);
+ * }
+ * },
+ *
+ * constructor: function() { ... }
+ * });
+ *
+ * var dellComputer = Computer.factory('Dell');
+ */
+ ExtClass.registerPreprocessor('statics', function(Class, data) {
+ Class.addStatics(data.statics);
+
+ delete data.statics;
+ });
+
+ /**
+ * @cfg {Object} inheritableStatics
+ * List of inheritable static methods for this class.
+ * Otherwise just like {@link #statics} but subclasses inherit these methods.
+ */
+ ExtClass.registerPreprocessor('inheritableStatics', function(Class, data) {
+ Class.addInheritableStatics(data.inheritableStatics);
+
+ delete data.inheritableStatics;
+ });
+
+ /**
+ * @cfg {Object} config
+ * List of configuration options with their default values, for which automatically
+ * accessor methods are generated. For example:
+ *
+ * Ext.define('SmartPhone', {
+ * config: {
+ * hasTouchScreen: false,
+ * operatingSystem: 'Other',
+ * price: 500
+ * },
+ * constructor: function(cfg) {
+ * this.initConfig(cfg);
+ * }
+ * });
+ *
+ * var iPhone = new SmartPhone({
+ * hasTouchScreen: true,
+ * operatingSystem: 'iOS'
+ * });
+ *
+ * iPhone.getPrice(); // 500;
+ * iPhone.getOperatingSystem(); // 'iOS'
+ * iPhone.getHasTouchScreen(); // true;
+ */
+ ExtClass.registerPreprocessor('config', function(Class, data) {
+ var config = data.config,
+ prototype = Class.prototype;
+
+ delete data.config;
+
+ Ext.Object.each(config, function(name, value) {
+ var nameMap = ExtClass.getConfigNameMap(name),
+ internalName = nameMap.internal,
+ initializedName = nameMap.initialized,
+ applyName = nameMap.apply,
+ updateName = nameMap.update,
+ setName = nameMap.set,
+ getName = nameMap.get,
+ hasOwnSetter = (setName in prototype) || data.hasOwnProperty(setName),
+ hasOwnApplier = (applyName in prototype) || data.hasOwnProperty(applyName),
+ hasOwnUpdater = (updateName in prototype) || data.hasOwnProperty(updateName),
+ optimizedGetter, customGetter;
+
+ if (value === null || (!hasOwnSetter && !hasOwnApplier && !hasOwnUpdater)) {
+ prototype[internalName] = value;
+ prototype[initializedName] = true;
+ }
+ else {
+ prototype[initializedName] = false;
+ }
+
+ if (!hasOwnSetter) {
+ data[setName] = function(value) {
+ var oldValue = this[internalName],
+ applier = this[applyName],
+ updater = this[updateName];
+
+ if (!this[initializedName]) {
+ this[initializedName] = true;
+ }
+
+ if (applier) {
+ value = applier.call(this, value, oldValue);
+ }
+
+ if (typeof value != 'undefined') {
+ this[internalName] = value;
+
+ if (updater && value !== oldValue) {
+ updater.call(this, value, oldValue);
+ }
+ }
+
+ return this;
+ };
+ }
+
+ if (!(getName in prototype) || data.hasOwnProperty(getName)) {
+ customGetter = data[getName] || false;
+
+ if (customGetter) {
+ optimizedGetter = function() {
+ return customGetter.apply(this, arguments);
+ };
+ }
+ else {
+ optimizedGetter = function() {
+ return this[internalName];
+ };
+ }
+
+ data[getName] = function() {
+ var currentGetter;
+
+ if (!this[initializedName]) {
+ this[initializedName] = true;
+ this[setName](this.config[name]);
+ }
+
+ currentGetter = this[getName];
+
+ if ('$previous' in currentGetter) {
+ currentGetter.$previous = optimizedGetter;
+ }
+ else {
+ this[getName] = optimizedGetter;
+ }
+
+ return optimizedGetter.apply(this, arguments);
+ };
+ }
+ });
+
+ Class.addConfig(config, true);
+ });
+
+ /**
+ * @cfg {String[]/Object} mixins
+ * List of classes to mix into this class. For example:
+ *
+ * Ext.define('CanSing', {
+ * sing: function() {
+ * alert("I'm on the highway to hell...")
+ * }
+ * });
+ *
+ * Ext.define('Musician', {
+ * mixins: ['CanSing']
+ * })
+ *
+ * In this case the Musician class will get a `sing` method from CanSing mixin.
+ *
+ * But what if the Musician already has a `sing` method? Or you want to mix
+ * in two classes, both of which define `sing`? In such a cases it's good
+ * to define mixins as an object, where you assign a name to each mixin:
+ *
+ * Ext.define('Musician', {
+ * mixins: {
+ * canSing: 'CanSing'
+ * },
+ *
+ * sing: function() {
+ * // delegate singing operation to mixin
+ * this.mixins.canSing.sing.call(this);
+ * }
+ * })
+ *
+ * In this case the `sing` method of Musician will overwrite the
+ * mixed in `sing` method. But you can access the original mixed in method
+ * through special `mixins` property.
+ */
+ ExtClass.registerPreprocessor('mixins', function(Class, data, hooks) {
+ var mixins = data.mixins,
+ name, mixin, i, ln;
+
+ delete data.mixins;
+
+ Ext.Function.interceptBefore(hooks, 'onCreated', function() {
+ if (mixins instanceof Array) {
+ for (i = 0,ln = mixins.length; i < ln; i++) {
+ mixin = mixins[i];
+ name = mixin.prototype.mixinId || mixin.$className;
+
+ Class.mixin(name, mixin);
+ }
+ }
+ else {
+ for (var mixinName in mixins) {
+ if (mixins.hasOwnProperty(mixinName)) {
+ Class.mixin(mixinName, mixins[mixinName]);
+ }
+ }
+ }
+ });
+ });
+
+ // Backwards compatible
+ Ext.extend = function(Class, Parent, members) {
+ if (arguments.length === 2 && Ext.isObject(Parent)) {
+ members = Parent;
+ Parent = Class;
+ Class = null;
+ }
+
+ var cls;
+
+ if (!Parent) {
+ throw new Error("[Ext.extend] Attempting to extend from a class which has not been loaded on the page.");
+ }
+
+ members.extend = Parent;
+ members.preprocessors = [
+ 'extend'
+ ,'statics'
+ ,'inheritableStatics'
+ ,'mixins'
+ ,'config'
+ ];
+
+ if (Class) {
+ cls = new ExtClass(Class, members);
+ // The 'constructor' is given as 'Class' but also needs to be on prototype
+ cls.prototype.constructor = Class;
+ } else {
+ cls = new ExtClass(members);
+ }
+
+ cls.prototype.override = function(o) {
+ for (var m in o) {
+ if (o.hasOwnProperty(m)) {
+ this[m] = o[m];
+ }
+ }
+ };
+
+ return cls;
+ };
+
+}());
+
+//@tag foundation,core
+//@require Class.js
+
+/**
+ * @author Jacky Nguyen
+ * @docauthor Jacky Nguyen
+ * @class Ext.ClassManager
+ *
+ * Ext.ClassManager manages all classes and handles mapping from string class name to
+ * actual class objects throughout the whole framework. It is not generally accessed directly, rather through
+ * these convenient shorthands:
+ *
+ * - {@link Ext#define Ext.define}
+ * - {@link Ext#create Ext.create}
+ * - {@link Ext#widget Ext.widget}
+ * - {@link Ext#getClass Ext.getClass}
+ * - {@link Ext#getClassName Ext.getClassName}
+ *
+ * # Basic syntax:
+ *
+ * Ext.define(className, properties);
+ *
+ * in which `properties` is an object represent a collection of properties that apply to the class. See
+ * {@link Ext.ClassManager#create} for more detailed instructions.
+ *
+ * Ext.define('Person', {
+ * name: 'Unknown',
+ *
+ * constructor: function(name) {
+ * if (name) {
+ * this.name = name;
+ * }
+ * },
+ *
+ * eat: function(foodType) {
+ * alert("I'm eating: " + foodType);
+ *
+ * return this;
+ * }
+ * });
+ *
+ * var aaron = new Person("Aaron");
+ * aaron.eat("Sandwich"); // alert("I'm eating: Sandwich");
+ *
+ * Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of
+ * everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc.
+ *
+ * # Inheritance:
+ *
+ * Ext.define('Developer', {
+ * extend: 'Person',
+ *
+ * constructor: function(name, isGeek) {
+ * this.isGeek = isGeek;
+ *
+ * // Apply a method from the parent class' prototype
+ * this.callParent([name]);
+ * },
+ *
+ * code: function(language) {
+ * alert("I'm coding in: " + language);
+ *
+ * this.eat("Bugs");
+ *
+ * return this;
+ * }
+ * });
+ *
+ * var jacky = new Developer("Jacky", true);
+ * jacky.code("JavaScript"); // alert("I'm coding in: JavaScript");
+ * // alert("I'm eating: Bugs");
+ *
+ * See {@link Ext.Base#callParent} for more details on calling superclass' methods
+ *
+ * # Mixins:
+ *
+ * Ext.define('CanPlayGuitar', {
+ * playGuitar: function() {
+ * alert("F#...G...D...A");
+ * }
+ * });
+ *
+ * Ext.define('CanComposeSongs', {
+ * composeSongs: function() { ... }
+ * });
+ *
+ * Ext.define('CanSing', {
+ * sing: function() {
+ * alert("I'm on the highway to hell...")
+ * }
+ * });
+ *
+ * Ext.define('Musician', {
+ * extend: 'Person',
+ *
+ * mixins: {
+ * canPlayGuitar: 'CanPlayGuitar',
+ * canComposeSongs: 'CanComposeSongs',
+ * canSing: 'CanSing'
+ * }
+ * })
+ *
+ * Ext.define('CoolPerson', {
+ * extend: 'Person',
+ *
+ * mixins: {
+ * canPlayGuitar: 'CanPlayGuitar',
+ * canSing: 'CanSing'
+ * },
+ *
+ * sing: function() {
+ * alert("Ahem....");
+ *
+ * this.mixins.canSing.sing.call(this);
+ *
+ * alert("[Playing guitar at the same time...]");
+ *
+ * this.playGuitar();
+ * }
+ * });
+ *
+ * var me = new CoolPerson("Jacky");
+ *
+ * me.sing(); // alert("Ahem...");
+ * // alert("I'm on the highway to hell...");
+ * // alert("[Playing guitar at the same time...]");
+ * // alert("F#...G...D...A");
+ *
+ * # Config:
+ *
+ * Ext.define('SmartPhone', {
+ * config: {
+ * hasTouchScreen: false,
+ * operatingSystem: 'Other',
+ * price: 500
+ * },
+ *
+ * isExpensive: false,
+ *
+ * constructor: function(config) {
+ * this.initConfig(config);
+ * },
+ *
+ * applyPrice: function(price) {
+ * this.isExpensive = (price > 500);
+ *
+ * return price;
+ * },
+ *
+ * applyOperatingSystem: function(operatingSystem) {
+ * if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) {
+ * return 'Other';
+ * }
+ *
+ * return operatingSystem;
+ * }
+ * });
+ *
+ * var iPhone = new SmartPhone({
+ * hasTouchScreen: true,
+ * operatingSystem: 'iOS'
+ * });
+ *
+ * iPhone.getPrice(); // 500;
+ * iPhone.getOperatingSystem(); // 'iOS'
+ * iPhone.getHasTouchScreen(); // true;
+ * iPhone.hasTouchScreen(); // true
+ *
+ * iPhone.isExpensive; // false;
+ * iPhone.setPrice(600);
+ * iPhone.getPrice(); // 600
+ * iPhone.isExpensive; // true;
+ *
+ * iPhone.setOperatingSystem('AlienOS');
+ * iPhone.getOperatingSystem(); // 'Other'
+ *
+ * # Statics:
+ *
+ * Ext.define('Computer', {
+ * statics: {
+ * factory: function(brand) {
+ * // 'this' in static methods refer to the class itself
+ * return new this(brand);
+ * }
+ * },
+ *
+ * constructor: function() { ... }
+ * });
+ *
+ * var dellComputer = Computer.factory('Dell');
+ *
+ * Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing
+ * static properties within class methods
+ *
+ * @singleton
+ */
+(function(Class, alias, arraySlice, arrayFrom, global) {
+
+ // Creates a constructor that has nothing extra in its scope chain.
+ function makeCtor () {
+ function constructor () {
+ // Opera has some problems returning from a constructor when Dragonfly isn't running. The || null seems to
+ // be sufficient to stop it misbehaving. Known to be required against 10.53, 11.51 and 11.61.
+ return this.constructor.apply(this, arguments) || null;
+ }
+ return constructor;
+ }
+
+ var Manager = Ext.ClassManager = {
+
+ /**
+ * @property {Object} classes
+ * All classes which were defined through the ClassManager. Keys are the
+ * name of the classes and the values are references to the classes.
+ * @private
+ */
+ classes: {},
+
+ /**
+ * @private
+ */
+ existCache: {},
+
+ /**
+ * @private
+ */
+ namespaceRewrites: [{
+ from: 'Ext.',
+ to: Ext
+ }],
+
+ /**
+ * @private
+ */
+ maps: {
+ alternateToName: {},
+ aliasToName: {},
+ nameToAliases: {},
+ nameToAlternates: {}
+ },
+
+ /** @private */
+ enableNamespaceParseCache: true,
+
+ /** @private */
+ namespaceParseCache: {},
+
+ /** @private */
+ instantiators: [],
+
+ /**
+ * Checks if a class has already been created.
+ *
+ * @param {String} className
+ * @return {Boolean} exist
+ */
+ isCreated: function(className) {
+ var existCache = this.existCache,
+ i, ln, part, root, parts;
+
+ if (typeof className != 'string' || className.length < 1) {
+ throw new Error("[Ext.ClassManager] Invalid classname, must be a string and must not be empty");
+ }
+
+ if (this.classes[className] || existCache[className]) {
+ return true;
+ }
+
+ root = global;
+ parts = this.parseNamespace(className);
+
+ for (i = 0, ln = parts.length; i < ln; i++) {
+ part = parts[i];
+
+ if (typeof part != 'string') {
+ root = part;
+ } else {
+ if (!root || !root[part]) {
+ return false;
+ }
+
+ root = root[part];
+ }
+ }
+
+ existCache[className] = true;
+
+ this.triggerCreated(className);
+
+ return true;
+ },
+
+ /**
+ * @private
+ */
+ createdListeners: [],
+
+ /**
+ * @private
+ */
+ nameCreatedListeners: {},
+
+ /**
+ * @private
+ */
+ triggerCreated: function(className) {
+ var listeners = this.createdListeners,
+ nameListeners = this.nameCreatedListeners,
+ alternateNames = this.maps.nameToAlternates[className],
+ names = [className],
+ i, ln, j, subLn, listener, name;
+
+ for (i = 0,ln = listeners.length; i < ln; i++) {
+ listener = listeners[i];
+ listener.fn.call(listener.scope, className);
+ }
+
+ if (alternateNames) {
+ names.push.apply(names, alternateNames);
+ }
+
+ for (i = 0,ln = names.length; i < ln; i++) {
+ name = names[i];
+ listeners = nameListeners[name];
+
+ if (listeners) {
+ for (j = 0,subLn = listeners.length; j < subLn; j++) {
+ listener = listeners[j];
+ listener.fn.call(listener.scope, name);
+ }
+ delete nameListeners[name];
+ }
+ }
+ },
+
+ /**
+ * @private
+ */
+ onCreated: function(fn, scope, className) {
+ var listeners = this.createdListeners,
+ nameListeners = this.nameCreatedListeners,
+ listener = {
+ fn: fn,
+ scope: scope
+ };
+
+ if (className) {
+ if (this.isCreated(className)) {
+ fn.call(scope, className);
+ return;
+ }
+
+ if (!nameListeners[className]) {
+ nameListeners[className] = [];
+ }
+
+ nameListeners[className].push(listener);
+ }
+ else {
+ listeners.push(listener);
+ }
+ },
+
+ /**
+ * Supports namespace rewriting
+ * @private
+ */
+ parseNamespace: function(namespace) {
+ if (typeof namespace != 'string') {
+ throw new Error("[Ext.ClassManager] Invalid namespace, must be a string");
+ }
+
+ var cache = this.namespaceParseCache,
+ parts,
+ rewrites,
+ root,
+ name,
+ rewrite, from, to, i, ln;
+
+ if (this.enableNamespaceParseCache) {
+ if (cache.hasOwnProperty(namespace)) {
+ return cache[namespace];
+ }
+ }
+
+ parts = [];
+ rewrites = this.namespaceRewrites;
+ root = global;
+ name = namespace;
+
+ for (i = 0, ln = rewrites.length; i < ln; i++) {
+ rewrite = rewrites[i];
+ from = rewrite.from;
+ to = rewrite.to;
+
+ if (name === from || name.substring(0, from.length) === from) {
+ name = name.substring(from.length);
+
+ if (typeof to != 'string') {
+ root = to;
+ } else {
+ parts = parts.concat(to.split('.'));
+ }
+
+ break;
+ }
+ }
+
+ parts.push(root);
+
+ parts = parts.concat(name.split('.'));
+
+ if (this.enableNamespaceParseCache) {
+ cache[namespace] = parts;
+ }
+
+ return parts;
+ },
+
+ /**
+ * Creates a namespace and assign the `value` to the created object
+ *
+ * Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject);
+ *
+ * alert(MyCompany.pkg.Example === someObject); // alerts true
+ *
+ * @param {String} name
+ * @param {Object} value
+ */
+ setNamespace: function(name, value) {
+ var root = global,
+ parts = this.parseNamespace(name),
+ ln = parts.length - 1,
+ leaf = parts[ln],
+ i, part;
+
+ for (i = 0; i < ln; i++) {
+ part = parts[i];
+
+ if (typeof part != 'string') {
+ root = part;
+ } else {
+ if (!root[part]) {
+ root[part] = {};
+ }
+
+ root = root[part];
+ }
+ }
+
+ root[leaf] = value;
+
+ return root[leaf];
+ },
+
+ /**
+ * The new Ext.ns, supports namespace rewriting
+ * @private
+ */
+ createNamespaces: function() {
+ var root = global,
+ parts, part, i, j, ln, subLn;
+
+ for (i = 0, ln = arguments.length; i < ln; i++) {
+ parts = this.parseNamespace(arguments[i]);
+
+ for (j = 0, subLn = parts.length; j < subLn; j++) {
+ part = parts[j];
+
+ if (typeof part != 'string') {
+ root = part;
+ } else {
+ if (!root[part]) {
+ root[part] = {};
+ }
+
+ root = root[part];
+ }
+ }
+ }
+
+ return root;
+ },
+
+ /**
+ * Sets a name reference to a class.
+ *
+ * @param {String} name
+ * @param {Object} value
+ * @return {Ext.ClassManager} this
+ */
+ set: function(name, value) {
+ var me = this,
+ maps = me.maps,
+ nameToAlternates = maps.nameToAlternates,
+ targetName = me.getName(value),
+ alternates;
+
+ me.classes[name] = me.setNamespace(name, value);
+
+ if (targetName && targetName !== name) {
+ maps.alternateToName[name] = targetName;
+ alternates = nameToAlternates[targetName] || (nameToAlternates[targetName] = []);
+ alternates.push(name);
+ }
+
+ return this;
+ },
+
+ /**
+ * Retrieve a class by its name.
+ *
+ * @param {String} name
+ * @return {Ext.Class} class
+ */
+ get: function(name) {
+ var classes = this.classes,
+ root,
+ parts,
+ part, i, ln;
+
+ if (classes[name]) {
+ return classes[name];
+ }
+
+ root = global;
+ parts = this.parseNamespace(name);
+
+ for (i = 0, ln = parts.length; i < ln; i++) {
+ part = parts[i];
+
+ if (typeof part != 'string') {
+ root = part;
+ } else {
+ if (!root || !root[part]) {
+ return null;
+ }
+
+ root = root[part];
+ }
+ }
+
+ return root;
+ },
+
+ /**
+ * Register the alias for a class.
+ *
+ * @param {Ext.Class/String} cls a reference to a class or a className
+ * @param {String} alias Alias to use when referring to this class
+ */
+ setAlias: function(cls, alias) {
+ var aliasToNameMap = this.maps.aliasToName,
+ nameToAliasesMap = this.maps.nameToAliases,
+ className;
+
+ if (typeof cls == 'string') {
+ className = cls;
+ } else {
+ className = this.getName(cls);
+ }
+
+ if (alias && aliasToNameMap[alias] !== className) {
+ if (aliasToNameMap[alias] && Ext.isDefined(global.console)) {
+ global.console.log("[Ext.ClassManager] Overriding existing alias: '" + alias + "' " +
+ "of: '" + aliasToNameMap[alias] + "' with: '" + className + "'. Be sure it's intentional.");
+ }
+
+ aliasToNameMap[alias] = className;
+ }
+
+ if (!nameToAliasesMap[className]) {
+ nameToAliasesMap[className] = [];
+ }
+
+ if (alias) {
+ Ext.Array.include(nameToAliasesMap[className], alias);
+ }
+
+ return this;
+ },
+
+ /**
+ * Adds a batch of class name to alias mappings
+ * @param {Object} aliases The set of mappings of the form
+ * className : [values...]
+ */
+ addNameAliasMappings: function(aliases){
+ var aliasToNameMap = this.maps.aliasToName,
+ nameToAliasesMap = this.maps.nameToAliases,
+ className, aliasList, alias, i;
+
+ for (className in aliases) {
+ aliasList = nameToAliasesMap[className] ||
+ (nameToAliasesMap[className] = []);
+
+ for (i = 0; i < aliases[className].length; i++) {
+ alias = aliases[className][i];
+ if (!aliasToNameMap[alias]) {
+ aliasToNameMap[alias] = className;
+ aliasList.push(alias);
+ }
+ }
+
+ }
+ return this;
+ },
+
+ /**
+ *
+ * @param {Object} alternates The set of mappings of the form
+ * className : [values...]
+ */
+ addNameAlternateMappings: function(alternates) {
+ var alternateToName = this.maps.alternateToName,
+ nameToAlternates = this.maps.nameToAlternates,
+ className, aliasList, alternate, i;
+
+ for (className in alternates) {
+ aliasList = nameToAlternates[className] ||
+ (nameToAlternates[className] = []);
+
+ for (i = 0; i < alternates[className].length; i++) {
+ alternate = alternates[className];
+ if (!alternateToName[alternate]) {
+ alternateToName[alternate] = className;
+ aliasList.push(alternate);
+ }
+ }
+
+ }
+ return this;
+ },
+
+ /**
+ * Get a reference to the class by its alias.
+ *
+ * @param {String} alias
+ * @return {Ext.Class} class
+ */
+ getByAlias: function(alias) {
+ return this.get(this.getNameByAlias(alias));
+ },
+
+ /**
+ * Get the name of a class by its alias.
+ *
+ * @param {String} alias
+ * @return {String} className
+ */
+ getNameByAlias: function(alias) {
+ return this.maps.aliasToName[alias] || '';
+ },
+
+ /**
+ * Get the name of a class by its alternate name.
+ *
+ * @param {String} alternate
+ * @return {String} className
+ */
+ getNameByAlternate: function(alternate) {
+ return this.maps.alternateToName[alternate] || '';
+ },
+
+ /**
+ * Get the aliases of a class by the class name
+ *
+ * @param {String} name
+ * @return {Array} aliases
+ */
+ getAliasesByName: function(name) {
+ return this.maps.nameToAliases[name] || [];
+ },
+
+ /**
+ * Get the name of the class by its reference or its instance;
+ * usually invoked by the shorthand {@link Ext#getClassName Ext.getClassName}
+ *
+ * Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action"
+ *
+ * @param {Ext.Class/Object} object
+ * @return {String} className
+ */
+ getName: function(object) {
+ return object && object.$className || '';
+ },
+
+ /**
+ * Get the class of the provided object; returns null if it's not an instance
+ * of any class created with Ext.define. This is usually invoked by the shorthand {@link Ext#getClass Ext.getClass}
+ *
+ * var component = new Ext.Component();
+ *
+ * Ext.ClassManager.getClass(component); // returns Ext.Component
+ *
+ * @param {Object} object
+ * @return {Ext.Class} class
+ */
+ getClass: function(object) {
+ return object && object.self || null;
+ },
+
+ /**
+ * Defines a class.
+ * @deprecated 4.1.0 Use {@link Ext#define} instead, as that also supports creating overrides.
+ */
+ create: function(className, data, createdFn) {
+ if (className != null && typeof className != 'string') {
+ throw new Error("[Ext.define] Invalid class name '" + className + "' specified, must be a non-empty string");
+ }
+
+ var ctor = makeCtor();
+ if (typeof data == 'function') {
+ data = data(ctor);
+ }
+
+ if (className) {
+ ctor.displayName = className;
+ }
+
+ data.$className = className;
+
+ return new Class(ctor, data, function() {
+ var postprocessorStack = data.postprocessors || Manager.defaultPostprocessors,
+ registeredPostprocessors = Manager.postprocessors,
+ postprocessors = [],
+ postprocessor, i, ln, j, subLn, postprocessorProperties, postprocessorProperty;
+
+ delete data.postprocessors;
+
+ for (i = 0,ln = postprocessorStack.length; i < ln; i++) {
+ postprocessor = postprocessorStack[i];
+
+ if (typeof postprocessor == 'string') {
+ postprocessor = registeredPostprocessors[postprocessor];
+ postprocessorProperties = postprocessor.properties;
+
+ if (postprocessorProperties === true) {
+ postprocessors.push(postprocessor.fn);
+ }
+ else if (postprocessorProperties) {
+ for (j = 0,subLn = postprocessorProperties.length; j < subLn; j++) {
+ postprocessorProperty = postprocessorProperties[j];
+
+ if (data.hasOwnProperty(postprocessorProperty)) {
+ postprocessors.push(postprocessor.fn);
+ break;
+ }
+ }
+ }
+ }
+ else {
+ postprocessors.push(postprocessor);
+ }
+ }
+
+ data.postprocessors = postprocessors;
+ data.createdFn = createdFn;
+ Manager.processCreate(className, this, data);
+ });
+ },
+
+ processCreate: function(className, cls, clsData){
+ var me = this,
+ postprocessor = clsData.postprocessors.shift(),
+ createdFn = clsData.createdFn;
+
+ if (!postprocessor) {
+ if (className) {
+ me.set(className, cls);
+ }
+
+ if (createdFn) {
+ createdFn.call(cls, cls);
+ }
+
+ if (className) {
+ me.triggerCreated(className);
+ }
+ return;
+ }
+
+ if (postprocessor.call(me, className, cls, clsData, me.processCreate) !== false) {
+ me.processCreate(className, cls, clsData);
+ }
+ },
+
+ createOverride: function (className, data, createdFn) {
+ var me = this,
+ overriddenClassName = data.override,
+ requires = data.requires,
+ uses = data.uses,
+ classReady = function () {
+ var cls, temp;
+
+ if (requires) {
+ temp = requires;
+ requires = null; // do the real thing next time (which may be now)
+
+ // Since the override is going to be used (its target class is now
+ // created), we need to fetch the required classes for the override
+ // and call us back once they are loaded:
+ Ext.Loader.require(temp, classReady);
+ } else {
+ // The target class and the required classes for this override are
+ // ready, so we can apply the override now:
+ cls = me.get(overriddenClassName);
+
+ // We don't want to apply these:
+ delete data.override;
+ delete data.requires;
+ delete data.uses;
+
+ Ext.override(cls, data);
+
+ // This pushes the overridding file itself into Ext.Loader.history
+ // Hence if the target class never exists, the overriding file will
+ // never be included in the build.
+ me.triggerCreated(className);
+
+ if (uses) {
+ Ext.Loader.addUsedClasses(uses); // get these classes too!
+ }
+
+ if (createdFn) {
+ createdFn.call(cls); // last but not least!
+ }
+ }
+ };
+
+ me.existCache[className] = true;
+
+ // Override the target class right after it's created
+ me.onCreated(classReady, me, overriddenClassName);
+
+ return me;
+ },
+
+ /**
+ * Instantiate a class by its alias; usually invoked by the convenient shorthand {@link Ext#createByAlias Ext.createByAlias}
+ * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
+ * attempt to load the class via synchronous loading.
+ *
+ * var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... });
+ *
+ * @param {String} alias
+ * @param {Object...} args Additional arguments after the alias will be passed to the
+ * class constructor.
+ * @return {Object} instance
+ */
+ instantiateByAlias: function() {
+ var alias = arguments[0],
+ args = arraySlice.call(arguments),
+ className = this.getNameByAlias(alias);
+
+ if (!className) {
+ className = this.maps.aliasToName[alias];
+
+ if (!className) {
+ throw new Error("[Ext.createByAlias] Cannot create an instance of unrecognized alias: " + alias);
+ }
+
+ if (global.console) {
+ global.console.warn("[Ext.Loader] Synchronously loading '" + className + "'; consider adding " +
+ "Ext.require('" + alias + "') above Ext.onReady");
+ }
+
+ Ext.syncRequire(className);
+ }
+
+ args[0] = className;
+
+ return this.instantiate.apply(this, args);
+ },
+
+ /**
+ * @private
+ */
+ instantiate: function() {
+ var name = arguments[0],
+ nameType = typeof name,
+ args = arraySlice.call(arguments, 1),
+ alias = name,
+ possibleName, cls;
+
+ if (nameType != 'function') {
+ if (nameType != 'string' && args.length === 0) {
+ args = [name];
+ name = name.xclass;
+ }
+
+ if (typeof name != 'string' || name.length < 1) {
+ throw new Error("[Ext.create] Invalid class name or alias '" + name + "' specified, must be a non-empty string");
+ }
+
+ cls = this.get(name);
+ }
+ else {
+ cls = name;
+ }
+
+ // No record of this class name, it's possibly an alias, so look it up
+ if (!cls) {
+ possibleName = this.getNameByAlias(name);
+
+ if (possibleName) {
+ name = possibleName;
+
+ cls = this.get(name);
+ }
+ }
+
+ // Still no record of this class name, it's possibly an alternate name, so look it up
+ if (!cls) {
+ possibleName = this.getNameByAlternate(name);
+
+ if (possibleName) {
+ name = possibleName;
+
+ cls = this.get(name);
+ }
+ }
+
+ // Still not existing at this point, try to load it via synchronous mode as the last resort
+ if (!cls) {
+ if (global.console) {
+ global.console.warn("[Ext.Loader] Synchronously loading '" + name + "'; consider adding " +
+ "Ext.require('" + ((possibleName) ? alias : name) + "') above Ext.onReady");
+ }
+
+ Ext.syncRequire(name);
+
+ cls = this.get(name);
+ }
+
+ if (!cls) {
+ throw new Error("[Ext.create] Cannot create an instance of unrecognized class name / alias: " + alias);
+ }
+
+ if (typeof cls != 'function') {
+ throw new Error("[Ext.create] '" + name + "' is a singleton and cannot be instantiated");
+ }
+
+ return this.getInstantiator(args.length)(cls, args);
+ },
+
+ /**
+ * @private
+ * @param name
+ * @param args
+ */
+ dynInstantiate: function(name, args) {
+ args = arrayFrom(args, true);
+ args.unshift(name);
+
+ return this.instantiate.apply(this, args);
+ },
+
+ /**
+ * @private
+ * @param length
+ */
+ getInstantiator: function(length) {
+ var instantiators = this.instantiators,
+ instantiator,
+ i,
+ args;
+
+ instantiator = instantiators[length];
+
+ if (!instantiator) {
+ i = length;
+ args = [];
+
+ for (i = 0; i < length; i++) {
+ args.push('a[' + i + ']');
+ }
+
+ instantiator = instantiators[length] = new Function('c', 'a', 'return new c(' + args.join(',') + ')');
+ instantiator.displayName = "Ext.ClassManager.instantiate" + length;
+ }
+
+ return instantiator;
+ },
+
+ /**
+ * @private
+ */
+ postprocessors: {},
+
+ /**
+ * @private
+ */
+ defaultPostprocessors: [],
+
+ /**
+ * Register a post-processor function.
+ *
+ * @private
+ * @param {String} name
+ * @param {Function} postprocessor
+ */
+ registerPostprocessor: function(name, fn, properties, position, relativeTo) {
+ if (!position) {
+ position = 'last';
+ }
+
+ if (!properties) {
+ properties = [name];
+ }
+
+ this.postprocessors[name] = {
+ name: name,
+ properties: properties || false,
+ fn: fn
+ };
+
+ this.setDefaultPostprocessorPosition(name, position, relativeTo);
+
+ return this;
+ },
+
+ /**
+ * Set the default post processors array stack which are applied to every class.
+ *
+ * @private
+ * @param {String/Array} The name of a registered post processor or an array of registered names.
+ * @return {Ext.ClassManager} this
+ */
+ setDefaultPostprocessors: function(postprocessors) {
+ this.defaultPostprocessors = arrayFrom(postprocessors);
+
+ return this;
+ },
+
+ /**
+ * Insert this post-processor at a specific position in the stack, optionally relative to
+ * any existing post-processor
+ *
+ * @private
+ * @param {String} name The post-processor name. Note that it needs to be registered with
+ * {@link Ext.ClassManager#registerPostprocessor} before this
+ * @param {String} offset The insertion position. Four possible values are:
+ * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
+ * @param {String} relativeName
+ * @return {Ext.ClassManager} this
+ */
+ setDefaultPostprocessorPosition: function(name, offset, relativeName) {
+ var defaultPostprocessors = this.defaultPostprocessors,
+ index;
+
+ if (typeof offset == 'string') {
+ if (offset === 'first') {
+ defaultPostprocessors.unshift(name);
+
+ return this;
+ }
+ else if (offset === 'last') {
+ defaultPostprocessors.push(name);
+
+ return this;
+ }
+
+ offset = (offset === 'after') ? 1 : -1;
+ }
+
+ index = Ext.Array.indexOf(defaultPostprocessors, relativeName);
+
+ if (index !== -1) {
+ Ext.Array.splice(defaultPostprocessors, Math.max(0, index + offset), 0, name);
+ }
+
+ return this;
+ },
+
+ /**
+ * Converts a string expression to an array of matching class names. An expression can either refers to class aliases
+ * or class names. Expressions support wildcards:
+ *
+ * // returns ['Ext.window.Window']
+ * var window = Ext.ClassManager.getNamesByExpression('widget.window');
+ *
+ * // returns ['widget.panel', 'widget.window', ...]
+ * var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*');
+ *
+ * // returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...]
+ * var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*');
+ *
+ * @param {String} expression
+ * @return {String[]} classNames
+ */
+ getNamesByExpression: function(expression) {
+ var nameToAliasesMap = this.maps.nameToAliases,
+ names = [],
+ name, alias, aliases, possibleName, regex, i, ln;
+
+ if (typeof expression != 'string' || expression.length < 1) {
+ throw new Error("[Ext.ClassManager.getNamesByExpression] Expression " + expression + " is invalid, must be a non-empty string");
+ }
+
+ if (expression.indexOf('*') !== -1) {
+ expression = expression.replace(/\*/g, '(.*?)');
+ regex = new RegExp('^' + expression + '$');
+
+ for (name in nameToAliasesMap) {
+ if (nameToAliasesMap.hasOwnProperty(name)) {
+ aliases = nameToAliasesMap[name];
+
+ if (name.search(regex) !== -1) {
+ names.push(name);
+ }
+ else {
+ for (i = 0, ln = aliases.length; i < ln; i++) {
+ alias = aliases[i];
+
+ if (alias.search(regex) !== -1) {
+ names.push(name);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ } else {
+ possibleName = this.getNameByAlias(expression);
+
+ if (possibleName) {
+ names.push(possibleName);
+ } else {
+ possibleName = this.getNameByAlternate(expression);
+
+ if (possibleName) {
+ names.push(possibleName);
+ } else {
+ names.push(expression);
+ }
+ }
+ }
+
+ return names;
+ }
+ };
+
+ /**
+ * @cfg {String[]} alias
+ * @member Ext.Class
+ * List of short aliases for class names. Most useful for defining xtypes for widgets:
+ *
+ * Ext.define('MyApp.CoolPanel', {
+ * extend: 'Ext.panel.Panel',
+ * alias: ['widget.coolpanel'],
+ * title: 'Yeah!'
+ * });
+ *
+ * // Using Ext.create
+ * Ext.create('widget.coolpanel');
+ *
+ * // Using the shorthand for defining widgets by xtype
+ * Ext.widget('panel', {
+ * items: [
+ * {xtype: 'coolpanel', html: 'Foo'},
+ * {xtype: 'coolpanel', html: 'Bar'}
+ * ]
+ * });
+ *
+ * Besides "widget" for xtype there are alias namespaces like "feature" for ftype and "plugin" for ptype.
+ */
+ Manager.registerPostprocessor('alias', function(name, cls, data) {
+ var aliases = data.alias,
+ i, ln;
+
+ for (i = 0,ln = aliases.length; i < ln; i++) {
+ alias = aliases[i];
+
+ this.setAlias(cls, alias);
+ }
+
+ }, ['xtype', 'alias']);
+
+ /**
+ * @cfg {Boolean} singleton
+ * @member Ext.Class
+ * When set to true, the class will be instantiated as singleton. For example:
+ *
+ * Ext.define('Logger', {
+ * singleton: true,
+ * log: function(msg) {
+ * console.log(msg);
+ * }
+ * });
+ *
+ * Logger.log('Hello');
+ */
+ Manager.registerPostprocessor('singleton', function(name, cls, data, fn) {
+ fn.call(this, name, new cls(), data);
+ return false;
+ });
+
+ /**
+ * @cfg {String/String[]} alternateClassName
+ * @member Ext.Class
+ * Defines alternate names for this class. For example:
+ *
+ * Ext.define('Developer', {
+ * alternateClassName: ['Coder', 'Hacker'],
+ * code: function(msg) {
+ * alert('Typing... ' + msg);
+ * }
+ * });
+ *
+ * var joe = Ext.create('Developer');
+ * joe.code('stackoverflow');
+ *
+ * var rms = Ext.create('Hacker');
+ * rms.code('hack hack');
+ */
+ Manager.registerPostprocessor('alternateClassName', function(name, cls, data) {
+ var alternates = data.alternateClassName,
+ i, ln, alternate;
+
+ if (!(alternates instanceof Array)) {
+ alternates = [alternates];
+ }
+
+ for (i = 0, ln = alternates.length; i < ln; i++) {
+ alternate = alternates[i];
+
+ if (typeof alternate != 'string') {
+ throw new Error("[Ext.define] Invalid alternate of: '" + alternate + "' for class: '" + name + "'; must be a valid string");
+ }
+
+ this.set(alternate, cls);
+ }
+ });
+
+ Ext.apply(Ext, {
+ /**
+ * Instantiate a class by either full name, alias or alternate name.
+ *
+ * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has
+ * not been defined yet, it will attempt to load the class via synchronous loading.
+ *
+ * For example, all these three lines return the same result:
+ *
+ * // alias
+ * var window = Ext.create('widget.window', {
+ * width: 600,
+ * height: 800,
+ * ...
+ * });
+ *
+ * // alternate name
+ * var window = Ext.create('Ext.Window', {
+ * width: 600,
+ * height: 800,
+ * ...
+ * });
+ *
+ * // full class name
+ * var window = Ext.create('Ext.window.Window', {
+ * width: 600,
+ * height: 800,
+ * ...
+ * });
+ *
+ * // single object with xclass property:
+ * var window = Ext.create({
+ * xclass: 'Ext.window.Window', // any valid value for 'name' (above)
+ * width: 600,
+ * height: 800,
+ * ...
+ * });
+ *
+ * @param {String} [name] The class name or alias. Can be specified as `xclass`
+ * property if only one object parameter is specified.
+ * @param {Object...} [args] Additional arguments after the name will be passed to
+ * the class' constructor.
+ * @return {Object} instance
+ * @member Ext
+ * @method create
+ */
+ create: alias(Manager, 'instantiate'),
+
+ /**
+ * Convenient shorthand to create a widget by its xtype or a config object.
+ * See also {@link Ext.ClassManager#instantiateByAlias}.
+ *
+ * var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button');
+ *
+ * var panel = Ext.widget('panel', { // Equivalent to Ext.create('widget.panel')
+ * title: 'Panel'
+ * });
+ *
+ * var grid = Ext.widget({
+ * xtype: 'grid',
+ * ...
+ * });
+ *
+ * If a {@link Ext.Component component} instance is passed, it is simply returned.
+ *
+ * @member Ext
+ * @param {String} [name] The xtype of the widget to create.
+ * @param {Object} [config] The configuration object for the widget constructor.
+ * @return {Object} The widget instance
+ */
+ widget: function(name, config) {
+ // forms:
+ // 1: (xtype)
+ // 2: (xtype, config)
+ // 3: (config)
+ // 4: (xtype, component)
+ // 5: (component)
+ //
+ var xtype = name,
+ alias, className, T, load;
+
+ if (typeof xtype != 'string') { // if (form 3 or 5)
+ // first arg is config or component
+ config = name; // arguments[0]
+ xtype = config.xtype;
+ } else {
+ config = config || {};
+ }
+
+ if (config.isComponent) {
+ return config;
+ }
+
+ alias = 'widget.' + xtype;
+ className = Manager.getNameByAlias(alias);
+
+ // this is needed to support demand loading of the class
+ if (!className) {
+ load = true;
+ }
+
+ T = Manager.get(className);
+ if (load || !T) {
+ return Manager.instantiateByAlias(alias, config);
+ }
+ return new T(config);
+ },
+
+ /**
+ * Convenient shorthand, see {@link Ext.ClassManager#instantiateByAlias}
+ * @member Ext
+ * @method createByAlias
+ */
+ createByAlias: alias(Manager, 'instantiateByAlias'),
+
+ /**
+ * @method
+ * Defines a class or override. A basic class is defined like this:
+ *
+ * Ext.define('My.awesome.Class', {
+ * someProperty: 'something',
+ *
+ * someMethod: function(s) {
+ * alert(s + this.someProperty);
+ * }
+ *
+ * ...
+ * });
+ *
+ * var obj = new My.awesome.Class();
+ *
+ * obj.someMethod('Say '); // alerts 'Say something'
+ *
+ * To create an anonymous class, pass `null` for the `className`:
+ *
+ * Ext.define(null, {
+ * constructor: function () {
+ * // ...
+ * }
+ * });
+ *
+ * In some cases, it is helpful to create a nested scope to contain some private
+ * properties. The best way to do this is to pass a function instead of an object
+ * as the second parameter. This function will be called to produce the class
+ * body:
+ *
+ * Ext.define('MyApp.foo.Bar', function () {
+ * var id = 0;
+ *
+ * return {
+ * nextId: function () {
+ * return ++id;
+ * }
+ * };
+ * });
+ *
+ * When using this form of `Ext.define`, the function is passed a reference to its
+ * class. This can be used as an efficient way to access any static properties you
+ * may have:
+ *
+ * Ext.define('MyApp.foo.Bar', function (Bar) {
+ * return {
+ * statics: {
+ * staticMethod: function () {
+ * // ...
+ * }
+ * },
+ *
+ * method: function () {
+ * return Bar.staticMethod();
+ * }
+ * };
+ * });
+ *
+ * To define an override, include the `override` property. The content of an
+ * override is aggregated with the specified class in order to extend or modify
+ * that class. This can be as simple as setting default property values or it can
+ * extend and/or replace methods. This can also extend the statics of the class.
+ *
+ * One use for an override is to break a large class into manageable pieces.
+ *
+ * // File: /src/app/Panel.js
+ *
+ * Ext.define('My.app.Panel', {
+ * extend: 'Ext.panel.Panel',
+ * requires: [
+ * 'My.app.PanelPart2',
+ * 'My.app.PanelPart3'
+ * ]
+ *
+ * constructor: function (config) {
+ * this.callParent(arguments); // calls Ext.panel.Panel's constructor
+ * //...
+ * },
+ *
+ * statics: {
+ * method: function () {
+ * return 'abc';
+ * }
+ * }
+ * });
+ *
+ * // File: /src/app/PanelPart2.js
+ * Ext.define('My.app.PanelPart2', {
+ * override: 'My.app.Panel',
+ *
+ * constructor: function (config) {
+ * this.callParent(arguments); // calls My.app.Panel's constructor
+ * //...
+ * }
+ * });
+ *
+ * Another use of overrides is to provide optional parts of classes that can be
+ * independently required. In this case, the class may even be unaware of the
+ * override altogether.
+ *
+ * Ext.define('My.ux.CoolTip', {
+ * override: 'Ext.tip.ToolTip',
+ *
+ * constructor: function (config) {
+ * this.callParent(arguments); // calls Ext.tip.ToolTip's constructor
+ * //...
+ * }
+ * });
+ *
+ * The above override can now be required as normal.
+ *
+ * Ext.define('My.app.App', {
+ * requires: [
+ * 'My.ux.CoolTip'
+ * ]
+ * });
+ *
+ * Overrides can also contain statics:
+ *
+ * Ext.define('My.app.BarMod', {
+ * override: 'Ext.foo.Bar',
+ *
+ * statics: {
+ * method: function (x) {
+ * return this.callParent([x * 2]); // call Ext.foo.Bar.method
+ * }
+ * }
+ * });
+ *
+ * IMPORTANT: An override is only included in a build if the class it overrides is
+ * required. Otherwise, the override, like the target class, is not included.
+ *
+ * @param {String} className The class name to create in string dot-namespaced format, for example:
+ * 'My.very.awesome.Class', 'FeedViewer.plugin.CoolPager'
+ * It is highly recommended to follow this simple convention:
+ * - The root and the class name are 'CamelCased'
+ * - Everything else is lower-cased
+ * Pass `null` to create an anonymous class.
+ * @param {Object} data The key - value pairs of properties to apply to this class. Property names can be of any valid
+ * strings, except those in the reserved listed below:
+ * - `mixins`
+ * - `statics`
+ * - `config`
+ * - `alias`
+ * - `self`
+ * - `singleton`
+ * - `alternateClassName`
+ * - `override`
+ *
+ * @param {Function} createdFn Optional callback to execute after the class is created, the execution scope of which
+ * (`this`) will be the newly created class itself.
+ * @return {Ext.Base}
+ * @markdown
+ * @member Ext
+ * @method define
+ */
+ define: function (className, data, createdFn) {
+ if (data.override) {
+ return Manager.createOverride.apply(Manager, arguments);
+ }
+
+ return Manager.create.apply(Manager, arguments);
+ },
+
+ /**
+ * Convenient shorthand, see {@link Ext.ClassManager#getName}
+ * @member Ext
+ * @method getClassName
+ */
+ getClassName: alias(Manager, 'getName'),
+
+ /**
+ * Returns the displayName property or className or object. When all else fails, returns "Anonymous".
+ * @param {Object} object
+ * @return {String}
+ */
+ getDisplayName: function(object) {
+ if (object) {
+ if (object.displayName) {
+ return object.displayName;
+ }
+
+ if (object.$name && object.$class) {
+ return Ext.getClassName(object.$class) + '#' + object.$name;
+ }
+
+ if (object.$className) {
+ return object.$className;
+ }
+ }
+
+ return 'Anonymous';
+ },
+
+ /**
+ * Convenient shorthand, see {@link Ext.ClassManager#getClass}
+ * @member Ext
+ * @method getClass
+ */
+ getClass: alias(Manager, 'getClass'),
+
+ /**
+ * Creates namespaces to be used for scoping variables and classes so that they are not global.
+ * Specifying the last node of a namespace implicitly creates all other nodes. Usage:
+ *
+ * Ext.namespace('Company', 'Company.data');
+ *
+ * // equivalent and preferable to the above syntax
+ * Ext.ns('Company.data');
+ *
+ * Company.Widget = function() { ... };
+ *
+ * Company.data.CustomStore = function(config) { ... };
+ *
+ * @param {String...} namespaces
+ * @return {Object} The namespace object.
+ * (If multiple arguments are passed, this will be the last namespace created)
+ * @member Ext
+ * @method namespace
+ */
+ namespace: alias(Manager, 'createNamespaces')
+ });
+
+ /**
+ * Old name for {@link Ext#widget}.
+ * @deprecated 4.0.0 Use {@link Ext#widget} instead.
+ * @method createWidget
+ * @member Ext
+ */
+ Ext.createWidget = Ext.widget;
+
+ /**
+ * Convenient alias for {@link Ext#namespace Ext.namespace}.
+ * @inheritdoc Ext#namespace
+ * @member Ext
+ * @method ns
+ */
+ Ext.ns = Ext.namespace;
+
+ Class.registerPreprocessor('className', function(cls, data) {
+ if (data.$className) {
+ cls.$className = data.$className;
+ cls.displayName = cls.$className;
+ }
+ }, true, 'first');
+
+ Class.registerPreprocessor('alias', function(cls, data) {
+ var prototype = cls.prototype,
+ xtypes = arrayFrom(data.xtype),
+ aliases = arrayFrom(data.alias),
+ widgetPrefix = 'widget.',
+ widgetPrefixLength = widgetPrefix.length,
+ xtypesChain = Array.prototype.slice.call(prototype.xtypesChain || []),
+ xtypesMap = Ext.merge({}, prototype.xtypesMap || {}),
+ i, ln, alias, xtype;
+
+ for (i = 0,ln = aliases.length; i < ln; i++) {
+ alias = aliases[i];
+
+ if (typeof alias != 'string' || alias.length < 1) {
+ throw new Error("[Ext.define] Invalid alias of: '" + alias + "' for class: '" + name + "'; must be a valid string");
+ }
+
+ if (alias.substring(0, widgetPrefixLength) === widgetPrefix) {
+ xtype = alias.substring(widgetPrefixLength);
+ Ext.Array.include(xtypes, xtype);
+ }
+ }
+
+ cls.xtype = data.xtype = xtypes[0];
+ data.xtypes = xtypes;
+
+ for (i = 0,ln = xtypes.length; i < ln; i++) {
+ xtype = xtypes[i];
+
+ if (!xtypesMap[xtype]) {
+ xtypesMap[xtype] = true;
+ xtypesChain.push(xtype);
+ }
+ }
+
+ data.xtypesChain = xtypesChain;
+ data.xtypesMap = xtypesMap;
+
+ Ext.Function.interceptAfter(data, 'onClassCreated', function() {
+ var mixins = prototype.mixins,
+ key, mixin;
+
+ for (key in mixins) {
+ if (mixins.hasOwnProperty(key)) {
+ mixin = mixins[key];
+
+ xtypes = mixin.xtypes;
+
+ if (xtypes) {
+ for (i = 0,ln = xtypes.length; i < ln; i++) {
+ xtype = xtypes[i];
+
+ if (!xtypesMap[xtype]) {
+ xtypesMap[xtype] = true;
+ xtypesChain.push(xtype);
+ }
+ }
+ }
+ }
+ }
+ });
+
+ for (i = 0,ln = xtypes.length; i < ln; i++) {
+ xtype = xtypes[i];
+
+ if (typeof xtype != 'string' || xtype.length < 1) {
+ throw new Error("[Ext.define] Invalid xtype of: '" + xtype + "' for class: '" + name + "'; must be a valid non-empty string");
+ }
+
+ Ext.Array.include(aliases, widgetPrefix + xtype);
+ }
+
+ data.alias = aliases;
+
+ }, ['xtype', 'alias']);
+
+}(Ext.Class, Ext.Function.alias, Array.prototype.slice, Ext.Array.from, Ext.global));
+
+//@tag foundation,core
+//@require ClassManager.js
+//@define Ext.Loader
+
+/**
+ * @author Jacky Nguyen
+ * @docauthor Jacky Nguyen
+ * @class Ext.Loader
+ *
+ * Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used
+ * via the {@link Ext#require} shorthand. Ext.Loader supports both asynchronous and synchronous loading
+ * approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach:
+ *
+ * # Asynchronous Loading #
+ *
+ * - Advantages:
+ * + Cross-domain
+ * + No web server needed: you can run the application via the file system protocol (i.e: `file://path/to/your/index
+ * .html`)
+ * + Best possible debugging experience: error messages come with the exact file name and line number
+ *
+ * - Disadvantages:
+ * + Dependencies need to be specified before-hand
+ *
+ * ### Method 1: Explicitly include what you need: ###
+ *
+ * // Syntax
+ * Ext.require({String/Array} expressions);
+ *
+ * // Example: Single alias
+ * Ext.require('widget.window');
+ *
+ * // Example: Single class name
+ * Ext.require('Ext.window.Window');
+ *
+ * // Example: Multiple aliases / class names mix
+ * Ext.require(['widget.window', 'layout.border', 'Ext.data.Connection']);
+ *
+ * // Wildcards
+ * Ext.require(['widget.*', 'layout.*', 'Ext.data.*']);
+ *
+ * ### Method 2: Explicitly exclude what you don't need: ###
+ *
+ * // Syntax: Note that it must be in this chaining format.
+ * Ext.exclude({String/Array} expressions)
+ * .require({String/Array} expressions);
+ *
+ * // Include everything except Ext.data.*
+ * Ext.exclude('Ext.data.*').require('*');
+ *
+ * // Include all widgets except widget.checkbox*,
+ * // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc.
+ * Ext.exclude('widget.checkbox*').require('widget.*');
+ *
+ * # Synchronous Loading on Demand #
+ *
+ * - Advantages:
+ * + There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js
+ * before
+ *
+ * - Disadvantages:
+ * + Not as good debugging experience since file name won't be shown (except in Firebug at the moment)
+ * + Must be from the same domain due to XHR restriction
+ * + Need a web server, same reason as above
+ *
+ * There's one simple rule to follow: Instantiate everything with Ext.create instead of the `new` keyword
+ *
+ * Ext.create('widget.window', { ... }); // Instead of new Ext.window.Window({...});
+ *
+ * Ext.create('Ext.window.Window', {}); // Same as above, using full class name instead of alias
+ *
+ * Ext.widget('window', {}); // Same as above, all you need is the traditional `xtype`
+ *
+ * Behind the scene, {@link Ext.ClassManager} will automatically check whether the given class name / alias has already
+ * existed on the page. If it's not, Ext.Loader will immediately switch itself to synchronous mode and automatic load the given
+ * class and all its dependencies.
+ *
+ * # Hybrid Loading - The Best of Both Worlds #
+ *
+ * It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:
+ *
+ * ### Step 1: Start writing your application using synchronous approach.
+ *
+ * Ext.Loader will automatically fetch all dependencies on demand as they're needed during run-time. For example:
+ *
+ * Ext.onReady(function(){
+ * var window = Ext.widget('window', {
+ * width: 500,
+ * height: 300,
+ * layout: {
+ * type: 'border',
+ * padding: 5
+ * },
+ * title: 'Hello Dialog',
+ * items: [{
+ * title: 'Navigation',
+ * collapsible: true,
+ * region: 'west',
+ * width: 200,
+ * html: 'Hello',
+ * split: true
+ * }, {
+ * title: 'TabPanel',
+ * region: 'center'
+ * }]
+ * });
+ *
+ * window.show();
+ * })
+ *
+ * ### Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these: ###
+ *
+ * [Ext.Loader] Synchronously loading 'Ext.window.Window'; consider adding Ext.require('Ext.window.Window') before your application's code
+ * ClassManager.js:432
+ * [Ext.Loader] Synchronously loading 'Ext.layout.container.Border'; consider adding Ext.require('Ext.layout.container.Border') before your application's code
+ *
+ * Simply copy and paste the suggested code above `Ext.onReady`, i.e:
+ *
+ * Ext.require('Ext.window.Window');
+ * Ext.require('Ext.layout.container.Border');
+ *
+ * Ext.onReady(...);
+ *
+ * Everything should now load via asynchronous mode.
+ *
+ * # Deployment #
+ *
+ * It's important to note that dynamic loading should only be used during development on your local machines.
+ * During production, all dependencies should be combined into one single JavaScript file. Ext.Loader makes
+ * the whole process of transitioning from / to between development / maintenance and production as easy as
+ * possible. Internally {@link Ext.Loader#history Ext.Loader.history} maintains the list of all dependencies your application
+ * needs in the exact loading sequence. It's as simple as concatenating all files in this array into one,
+ * then include it on top of your application.
+ *
+ * This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.
+ *
+ * @singleton
+ */
+
+Ext.Loader = new function() {
+ var Loader = this,
+ Manager = Ext.ClassManager,
+ Class = Ext.Class,
+ flexSetter = Ext.Function.flexSetter,
+ alias = Ext.Function.alias,
+ pass = Ext.Function.pass,
+ defer = Ext.Function.defer,
+ arrayErase = Ext.Array.erase,
+ dependencyProperties = ['extend', 'mixins', 'requires'],
+ isInHistory = {},
+ history = [],
+ slashDotSlashRe = /\/\.\//g,
+ dotRe = /\./g;
+
+ Ext.apply(Loader, {
+
+ /**
+ * @private
+ */
+ isInHistory: isInHistory,
+
+ /**
+ * An array of class names to keep track of the dependency loading order.
+ * This is not guaranteed to be the same everytime due to the asynchronous
+ * nature of the Loader.
+ *
+ * @property {Array} history
+ */
+ history: history,
+
+ /**
+ * Configuration
+ * @private
+ */
+ config: {
+ /**
+ * @cfg {Boolean} enabled
+ * Whether or not to enable the dynamic dependency loading feature.
+ */
+ enabled: false,
+
+ /**
+ * @cfg {Boolean} scriptChainDelay
+ * millisecond delay between asynchronous script injection (prevents stack overflow on some user agents)
+ * 'false' disables delay but potentially increases stack load.
+ */
+ scriptChainDelay : false,
+
+ /**
+ * @cfg {Boolean} disableCaching
+ * Appends current timestamp to script files to prevent caching.
+ */
+ disableCaching: true,
+
+ /**
+ * @cfg {String} disableCachingParam
+ * The get parameter name for the cache buster's timestamp.
+ */
+ disableCachingParam: '_dc',
+
+ /**
+ * @cfg {Boolean} garbageCollect
+ * True to prepare an asynchronous script tag for garbage collection (effective only
+ * if {@link #preserveScripts preserveScripts} is false)
+ */
+ garbageCollect : false,
+
+ /**
+ * @cfg {Object} paths
+ * The mapping from namespaces to file paths
+ *
+ * {
+ * 'Ext': '.', // This is set by default, Ext.layout.container.Container will be
+ * // loaded from ./layout/Container.js
+ *
+ * 'My': './src/my_own_folder' // My.layout.Container will be loaded from
+ * // ./src/my_own_folder/layout/Container.js
+ * }
+ *
+ * Note that all relative paths are relative to the current HTML document.
+ * If not being specified, for example, Other.awesome.Class
+ * will simply be loaded from ./Other/awesome/Class.js
+ */
+ paths: {
+ 'Ext': '.'
+ },
+
+ /**
+ * @cfg {Boolean} preserveScripts
+ * False to remove and optionally {@link #garbageCollect garbage-collect} asynchronously loaded scripts,
+ * True to retain script element for browser debugger compatibility and improved load performance.
+ */
+ preserveScripts : true,
+
+ /**
+ * @cfg {String} scriptCharset
+ * Optional charset to specify encoding of dynamic script content.
+ */
+ scriptCharset : undefined
+ },
+
+ /**
+ * Set the configuration for the loader. This should be called right after ext-(debug).js
+ * is included in the page, and before Ext.onReady. i.e:
+ *
+ *
+ *
+ *
+ *
+ * Refer to config options of {@link Ext.Loader} for the list of possible properties
+ *
+ * @param {Object} config The config object to override the default values
+ * @return {Ext.Loader} this
+ */
+ setConfig: function(name, value) {
+ if (Ext.isObject(name) && arguments.length === 1) {
+ Ext.merge(Loader.config, name);
+ }
+ else {
+ Loader.config[name] = (Ext.isObject(value)) ? Ext.merge(Loader.config[name], value) : value;
+ }
+
+ return Loader;
+ },
+
+ /**
+ * Get the config value corresponding to the specified name. If no name is given, will return the config object
+ * @param {String} name The config property name
+ * @return {Object}
+ */
+ getConfig: function(name) {
+ if (name) {
+ return Loader.config[name];
+ }
+
+ return Loader.config;
+ },
+
+ /**
+ * Sets the path of a namespace.
+ * For Example:
+ *
+ * Ext.Loader.setPath('Ext', '.');
+ *
+ * @param {String/Object} name See {@link Ext.Function#flexSetter flexSetter}
+ * @param {String} path See {@link Ext.Function#flexSetter flexSetter}
+ * @return {Ext.Loader} this
+ * @method
+ */
+ setPath: flexSetter(function(name, path) {
+ Loader.config.paths[name] = path;
+
+ return Loader;
+ }),
+
+ /**
+ * Sets a batch of path entries
+ *
+ * @param {Object } paths a set of className: path mappings
+ * @return {Ext.Loader} this
+ */
+ addClassPathMappings: function(paths) {
+ var name;
+
+ for(name in paths){
+ Loader.config.paths[name] = paths[name];
+ }
+ return Loader;
+ },
+
+ /**
+ * Translates a className to a file path by adding the
+ * the proper prefix and converting the .'s to /'s. For example:
+ *
+ * Ext.Loader.setPath('My', '/path/to/My');
+ *
+ * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js'
+ *
+ * Note that the deeper namespace levels, if explicitly set, are always resolved first. For example:
+ *
+ * Ext.Loader.setPath({
+ * 'My': '/path/to/lib',
+ * 'My.awesome': '/other/path/for/awesome/stuff',
+ * 'My.awesome.more': '/more/awesome/path'
+ * });
+ *
+ * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js'
+ *
+ * alert(Ext.Loader.getPath('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js'
+ *
+ * alert(Ext.Loader.getPath('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js'
+ *
+ * alert(Ext.Loader.getPath('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js'
+ *
+ * @param {String} className
+ * @return {String} path
+ */
+ getPath: function(className) {
+ var path = '',
+ paths = Loader.config.paths,
+ prefix = Loader.getPrefix(className);
+
+ if (prefix.length > 0) {
+ if (prefix === className) {
+ return paths[prefix];
+ }
+
+ path = paths[prefix];
+ className = className.substring(prefix.length + 1);
+ }
+
+ if (path.length > 0) {
+ path += '/';
+ }
+
+ return path.replace(slashDotSlashRe, '/') + className.replace(dotRe, "/") + '.js';
+ },
+
+ /**
+ * @private
+ * @param {String} className
+ */
+ getPrefix: function(className) {
+ var paths = Loader.config.paths,
+ prefix, deepestPrefix = '';
+
+ if (paths.hasOwnProperty(className)) {
+ return className;
+ }
+
+ for (prefix in paths) {
+ if (paths.hasOwnProperty(prefix) && prefix + '.' === className.substring(0, prefix.length + 1)) {
+ if (prefix.length > deepestPrefix.length) {
+ deepestPrefix = prefix;
+ }
+ }
+ }
+
+ return deepestPrefix;
+ },
+
+ /**
+ * @private
+ * @param {String} className
+ */
+ isAClassNameWithAKnownPrefix: function(className) {
+ var prefix = Loader.getPrefix(className);
+
+ // we can only say it's really a class if className is not equal to any known namespace
+ return prefix !== '' && prefix !== className;
+ },
+
+ /**
+ * Loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when
+ * finishes, within the optional scope. This method is aliased by {@link Ext#require Ext.require} for convenience
+ * @param {String/Array} expressions Can either be a string or an array of string
+ * @param {Function} fn (Optional) The callback function
+ * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
+ * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
+ */
+ require: function(expressions, fn, scope, excludes) {
+ if (fn) {
+ fn.call(scope);
+ }
+ },
+
+ /**
+ * Synchronously loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when finishes, within the optional scope. This method is aliased by {@link Ext#syncRequire} for convenience
+ * @param {String/Array} expressions Can either be a string or an array of string
+ * @param {Function} fn (Optional) The callback function
+ * @param {Object} scope (Optional) The execution scope (`this`) of the callback function
+ * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
+ */
+ syncRequire: function() {},
+
+ /**
+ * Explicitly exclude files from being loaded. Useful when used in conjunction with a broad include expression.
+ * Can be chained with more `require` and `exclude` methods, eg:
+ *
+ * Ext.exclude('Ext.data.*').require('*');
+ *
+ * Ext.exclude('widget.button*').require('widget.*');
+ *
+ * @param {Array} excludes
+ * @return {Object} object contains `require` method for chaining
+ */
+ exclude: function(excludes) {
+ return {
+ require: function(expressions, fn, scope) {
+ return Loader.require(expressions, fn, scope, excludes);
+ },
+
+ syncRequire: function(expressions, fn, scope) {
+ return Loader.syncRequire(expressions, fn, scope, excludes);
+ }
+ };
+ },
+
+ /**
+ * Add a new listener to be executed when all required scripts are fully loaded
+ *
+ * @param {Function} fn The function callback to be executed
+ * @param {Object} scope The execution scope (this) of the callback function
+ * @param {Boolean} withDomReady Whether or not to wait for document dom ready as well
+ */
+ onReady: function(fn, scope, withDomReady, options) {
+ var oldFn;
+
+ if (withDomReady !== false && Ext.onDocumentReady) {
+ oldFn = fn;
+
+ fn = function() {
+ Ext.onDocumentReady(oldFn, scope, options);
+ };
+ }
+
+ fn.call(scope);
+ }
+ });
+
+ var queue = [],
+ isClassFileLoaded = {},
+ isFileLoaded = {},
+ classNameToFilePathMap = {},
+ scriptElements = {},
+ readyListeners = [],
+ usedClasses = [],
+ requiresMap = {};
+
+ Ext.apply(Loader, {
+ /**
+ * @private
+ */
+ documentHead: typeof document != 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
+
+ /**
+ * Flag indicating whether there are still files being loaded
+ * @private
+ */
+ isLoading: false,
+
+ /**
+ * Maintain the queue for all dependencies. Each item in the array is an object of the format:
+ *
+ * {
+ * requires: [...], // The required classes for this queue item
+ * callback: function() { ... } // The function to execute when all classes specified in requires exist
+ * }
+ *
+ * @private
+ */
+ queue: queue,
+
+ /**
+ * Maintain the list of files that have already been handled so that they never get double-loaded
+ * @private
+ */
+ isClassFileLoaded: isClassFileLoaded,
+
+ /**
+ * @private
+ */
+ isFileLoaded: isFileLoaded,
+
+ /**
+ * Maintain the list of listeners to execute when all required scripts are fully loaded
+ * @private
+ */
+ readyListeners: readyListeners,
+
+ /**
+ * Contains classes referenced in `uses` properties.
+ * @private
+ */
+ optionalRequires: usedClasses,
+
+ /**
+ * Map of fully qualified class names to an array of dependent classes.
+ * @private
+ */
+ requiresMap: requiresMap,
+
+ /**
+ * @private
+ */
+ numPendingFiles: 0,
+
+ /**
+ * @private
+ */
+ numLoadedFiles: 0,
+
+ /** @private */
+ hasFileLoadError: false,
+
+ /**
+ * @private
+ */
+ classNameToFilePathMap: classNameToFilePathMap,
+
+ /**
+ * The number of scripts loading via loadScript.
+ * @private
+ */
+ scriptsLoading: 0,
+
+ /**
+ * @private
+ */
+ syncModeEnabled: false,
+
+ scriptElements: scriptElements,
+
+ /**
+ * Refresh all items in the queue. If all dependencies for an item exist during looping,
+ * it will execute the callback and call refreshQueue again. Triggers onReady when the queue is
+ * empty
+ * @private
+ */
+ refreshQueue: function() {
+ var ln = queue.length,
+ i, item, j, requires;
+
+ // When the queue of loading classes reaches zero, trigger readiness
+
+ if (!ln && !Loader.scriptsLoading) {
+ return Loader.triggerReady();
+ }
+
+ for (i = 0; i < ln; i++) {
+ item = queue[i];
+
+ if (item) {
+ requires = item.requires;
+
+ // Don't bother checking when the number of files loaded
+ // is still less than the array length
+ if (requires.length > Loader.numLoadedFiles) {
+ continue;
+ }
+
+ // Remove any required classes that are loaded
+ for (j = 0; j < requires.length; ) {
+ if (Manager.isCreated(requires[j])) {
+ // Take out from the queue
+ arrayErase(requires, j, 1);
+ }
+ else {
+ j++;
+ }
+ }
+
+ // If we've ended up with no required classes, call the callback
+ if (item.requires.length === 0) {
+ arrayErase(queue, i, 1);
+ item.callback.call(item.scope);
+ Loader.refreshQueue();
+ break;
+ }
+ }
+ }
+
+ return Loader;
+ },
+
+ /**
+ * Inject a script element to document's head, call onLoad and onError accordingly
+ * @private
+ */
+ injectScriptElement: function(url, onLoad, onError, scope, charset) {
+ var script = document.createElement('script'),
+ dispatched = false,
+ config = Loader.config,
+ onLoadFn = function() {
+
+ if(!dispatched) {
+ dispatched = true;
+ script.onload = script.onreadystatechange = script.onerror = null;
+ if (typeof config.scriptChainDelay == 'number') {
+ //free the stack (and defer the next script)
+ defer(onLoad, config.scriptChainDelay, scope);
+ } else {
+ onLoad.call(scope);
+ }
+ Loader.cleanupScriptElement(script, config.preserveScripts === false, config.garbageCollect);
+ }
+
+ },
+ onErrorFn = function(arg) {
+ defer(onError, 1, scope); //free the stack
+ Loader.cleanupScriptElement(script, config.preserveScripts === false, config.garbageCollect);
+ };
+
+ script.type = 'text/javascript';
+ script.onerror = onErrorFn;
+ charset = charset || config.scriptCharset;
+ if (charset) {
+ script.charset = charset;
+ }
+
+ /*
+ * IE9 Standards mode (and others) SHOULD follow the load event only
+ * (Note: IE9 supports both onload AND readystatechange events)
+ */
+ if ('addEventListener' in script ) {
+ script.onload = onLoadFn;
+ } else if ('readyState' in script) { // for = 200 && status < 300) || (status === 304)
+ ) {
+ // Debugger friendly, file names are still shown even though they're eval'ed code
+ // Breakpoints work on both Firebug and Chrome's Web Inspector
+ if (!Ext.isIE) {
+ debugSourceURL = "\n//@ sourceURL=" + url;
+ }
+
+ Ext.globalEval(xhr.responseText + debugSourceURL);
+
+ onLoad.call(scope);
+ }
+ else {
+ onError.call(Loader, "Failed loading synchronously via XHR: '" + url + "'; please " +
+ "verify that the file exists. " +
+ "XHR status code: " + status, synchronous);
+ }
+
+ // Prevent potential IE memory leak
+ xhr = null;
+ }
+ },
+
+ // documented above
+ syncRequire: function() {
+ var syncModeEnabled = Loader.syncModeEnabled;
+
+ if (!syncModeEnabled) {
+ Loader.syncModeEnabled = true;
+ }
+
+ Loader.require.apply(Loader, arguments);
+
+ if (!syncModeEnabled) {
+ Loader.syncModeEnabled = false;
+ }
+
+ Loader.refreshQueue();
+ },
+
+ // documented above
+ require: function(expressions, fn, scope, excludes) {
+ var excluded = {},
+ included = {},
+ excludedClassNames = [],
+ possibleClassNames = [],
+ classNames = [],
+ references = [],
+ callback,
+ syncModeEnabled,
+ filePath, expression, exclude, className,
+ possibleClassName, i, j, ln, subLn;
+
+ if (excludes) {
+ // Convert possible single string to an array.
+ excludes = (typeof excludes === 'string') ? [ excludes ] : excludes;
+
+ for (i = 0,ln = excludes.length; i < ln; i++) {
+ exclude = excludes[i];
+
+ if (typeof exclude == 'string' && exclude.length > 0) {
+ excludedClassNames = Manager.getNamesByExpression(exclude);
+
+ for (j = 0,subLn = excludedClassNames.length; j < subLn; j++) {
+ excluded[excludedClassNames[j]] = true;
+ }
+ }
+ }
+ }
+
+ // Convert possible single string to an array.
+ expressions = (typeof expressions === 'string') ? [ expressions ] : (expressions ? expressions : []);
+
+ if (fn) {
+ if (fn.length > 0) {
+ callback = function() {
+ var classes = [],
+ i, ln;
+
+ for (i = 0,ln = references.length; i < ln; i++) {
+ classes.push(Manager.get(references[i]));
+ }
+
+ return fn.apply(this, classes);
+ };
+ }
+ else {
+ callback = fn;
+ }
+ }
+ else {
+ callback = Ext.emptyFn;
+ }
+
+ scope = scope || Ext.global;
+
+ for (i = 0,ln = expressions.length; i < ln; i++) {
+ expression = expressions[i];
+
+ if (typeof expression == 'string' && expression.length > 0) {
+ possibleClassNames = Manager.getNamesByExpression(expression);
+ subLn = possibleClassNames.length;
+
+ for (j = 0; j < subLn; j++) {
+ possibleClassName = possibleClassNames[j];
+
+ if (excluded[possibleClassName] !== true) {
+ references.push(possibleClassName);
+
+ if (!Manager.isCreated(possibleClassName) && !included[possibleClassName]) {
+ included[possibleClassName] = true;
+ classNames.push(possibleClassName);
+ }
+ }
+ }
+ }
+ }
+
+ // If the dynamic dependency feature is not being used, throw an error
+ // if the dependencies are not defined
+ if (classNames.length > 0) {
+ if (!Loader.config.enabled) {
+ throw new Error("Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. " +
+ "Missing required class" + ((classNames.length > 1) ? "es" : "") + ": " + classNames.join(', '));
+ }
+ }
+ else {
+ callback.call(scope);
+ return Loader;
+ }
+
+ syncModeEnabled = Loader.syncModeEnabled;
+
+ if (!syncModeEnabled) {
+ queue.push({
+ requires: classNames.slice(), // this array will be modified as the queue is processed,
+ // so we need a copy of it
+ callback: callback,
+ scope: scope
+ });
+ }
+
+ ln = classNames.length;
+
+ for (i = 0; i < ln; i++) {
+ className = classNames[i];
+
+ filePath = Loader.getPath(className);
+
+ // If we are synchronously loading a file that has already been asychronously loaded before
+ // we need to destroy the script tag and revert the count
+ // This file will then be forced loaded in synchronous
+ if (syncModeEnabled && isClassFileLoaded.hasOwnProperty(className)) {
+ Loader.numPendingFiles--;
+ Loader.removeScriptElement(filePath);
+ delete isClassFileLoaded[className];
+ }
+
+ if (!isClassFileLoaded.hasOwnProperty(className)) {
+ isClassFileLoaded[className] = false;
+
+ classNameToFilePathMap[className] = filePath;
+
+ Loader.numPendingFiles++;
+ Loader.loadScriptFile(
+ filePath,
+ pass(Loader.onFileLoaded, [className, filePath], Loader),
+ pass(Loader.onFileLoadError, [className, filePath], Loader),
+ Loader,
+ syncModeEnabled
+ );
+ }
+ }
+
+ if (syncModeEnabled) {
+ callback.call(scope);
+
+ if (ln === 1) {
+ return Manager.get(className);
+ }
+ }
+
+ return Loader;
+ },
+
+ /**
+ * @private
+ * @param {String} className
+ * @param {String} filePath
+ */
+ onFileLoaded: function(className, filePath) {
+ Loader.numLoadedFiles++;
+
+ isClassFileLoaded[className] = true;
+ isFileLoaded[filePath] = true;
+
+ Loader.numPendingFiles--;
+
+ if (Loader.numPendingFiles === 0) {
+ Loader.refreshQueue();
+ }
+
+ if (!Loader.syncModeEnabled && Loader.numPendingFiles === 0 && Loader.isLoading && !Loader.hasFileLoadError) {
+ var missingClasses = [],
+ missingPaths = [],
+ requires,
+ i, ln, j, subLn;
+
+ for (i = 0,ln = queue.length; i < ln; i++) {
+ requires = queue[i].requires;
+
+ for (j = 0,subLn = requires.length; j < subLn; j++) {
+ if (isClassFileLoaded[requires[j]]) {
+ missingClasses.push(requires[j]);
+ }
+ }
+ }
+
+ if (missingClasses.length < 1) {
+ return;
+ }
+
+ missingClasses = Ext.Array.filter(Ext.Array.unique(missingClasses), function(item) {
+ return !requiresMap.hasOwnProperty(item);
+ }, Loader);
+
+ for (i = 0,ln = missingClasses.length; i < ln; i++) {
+ missingPaths.push(classNameToFilePathMap[missingClasses[i]]);
+ }
+
+ throw new Error("The following classes are not declared even if their files have been " +
+ "loaded: '" + missingClasses.join("', '") + "'. Please check the source code of their " +
+ "corresponding files for possible typos: '" + missingPaths.join("', '"));
+ }
+ },
+
+ /**
+ * @private
+ */
+ onFileLoadError: function(className, filePath, errorMessage, isSynchronous) {
+ Loader.numPendingFiles--;
+ Loader.hasFileLoadError = true;
+
+ throw new Error("[Ext.Loader] " + errorMessage);
+ },
+
+ /**
+ * @private
+ * Ensure that any classes referenced in the `uses` property are loaded.
+ */
+ addUsedClasses: function (classes) {
+ var cls, i, ln;
+
+ if (classes) {
+ classes = (typeof classes == 'string') ? [classes] : classes;
+ for (i = 0, ln = classes.length; i < ln; i++) {
+ cls = classes[i];
+ if (typeof cls == 'string' && !Ext.Array.contains(usedClasses, cls)) {
+ usedClasses.push(cls);
+ }
+ }
+ }
+
+ return Loader;
+ },
+
+ /**
+ * @private
+ */
+ triggerReady: function() {
+ var listener,
+ i, refClasses = usedClasses;
+
+ if (Loader.isLoading) {
+ Loader.isLoading = false;
+
+ if (refClasses.length !== 0) {
+ // Clone then empty the array to eliminate potential recursive loop issue
+ refClasses = refClasses.slice();
+ usedClasses.length = 0;
+ // this may immediately call us back if all 'uses' classes
+ // have been loaded
+ Loader.require(refClasses, Loader.triggerReady, Loader);
+ return Loader;
+ }
+ }
+
+ // this method can be called with Loader.isLoading either true or false
+ // (can be called with false when all 'uses' classes are already loaded)
+ // this may bypass the above if condition
+ while (readyListeners.length && !Loader.isLoading) {
+ // calls to refreshQueue may re-enter triggerReady
+ // so we cannot necessarily iterate the readyListeners array
+ listener = readyListeners.shift();
+ listener.fn.call(listener.scope);
+ }
+
+ return Loader;
+ },
+
+ // Documented above already
+ onReady: function(fn, scope, withDomReady, options) {
+ var oldFn;
+
+ if (withDomReady !== false && Ext.onDocumentReady) {
+ oldFn = fn;
+
+ fn = function() {
+ Ext.onDocumentReady(oldFn, scope, options);
+ };
+ }
+
+ if (!Loader.isLoading) {
+ fn.call(scope);
+ }
+ else {
+ readyListeners.push({
+ fn: fn,
+ scope: scope
+ });
+ }
+ },
+
+ /**
+ * @private
+ * @param {String} className
+ */
+ historyPush: function(className) {
+ if (className && isClassFileLoaded.hasOwnProperty(className) && !isInHistory[className]) {
+ isInHistory[className] = true;
+ history.push(className);
+ }
+ return Loader;
+ }
+ });
+
+ /**
+ * Turns on or off the "cache buster" applied to dynamically loaded scripts. Normally
+ * dynamically loaded scripts have an extra query parameter appended to avoid stale
+ * cached scripts. This method can be used to disable this mechanism, and is primarily
+ * useful for testing. This is done using a cookie.
+ * @param {Boolean} disable True to disable the cache buster.
+ * @param {String} [path="/"] An optional path to scope the cookie.
+ * @private
+ */
+ Ext.disableCacheBuster = function (disable, path) {
+ var date = new Date();
+ date.setTime(date.getTime() + (disable ? 10*365 : -1) * 24*60*60*1000);
+ date = date.toGMTString();
+ document.cookie = 'ext-cache=1; expires=' + date + '; path='+(path || '/');
+ };
+
+
+ /**
+ * Convenient alias of {@link Ext.Loader#require}. Please see the introduction documentation of
+ * {@link Ext.Loader} for examples.
+ * @member Ext
+ * @method require
+ */
+ Ext.require = alias(Loader, 'require');
+
+ /**
+ * Synchronous version of {@link Ext#require}, convenient alias of {@link Ext.Loader#syncRequire}.
+ *
+ * @member Ext
+ * @method syncRequire
+ */
+ Ext.syncRequire = alias(Loader, 'syncRequire');
+
+ /**
+ * Convenient shortcut to {@link Ext.Loader#exclude}
+ * @member Ext
+ * @method exclude
+ */
+ Ext.exclude = alias(Loader, 'exclude');
+
+ /**
+ * @member Ext
+ * @method onReady
+ * @ignore
+ */
+ Ext.onReady = function(fn, scope, options) {
+ Loader.onReady(fn, scope, true, options);
+ };
+
+ /**
+ * @cfg {String[]} requires
+ * @member Ext.Class
+ * List of classes that have to be loaded before instantiating this class.
+ * For example:
+ *
+ * Ext.define('Mother', {
+ * requires: ['Child'],
+ * giveBirth: function() {
+ * // we can be sure that child class is available.
+ * return new Child();
+ * }
+ * });
+ */
+ Class.registerPreprocessor('loader', function(cls, data, hooks, continueFn) {
+ var me = this,
+ dependencies = [],
+ dependency,
+ className = Manager.getName(cls),
+ i, j, ln, subLn, value, propertyName, propertyValue,
+ requiredMap, requiredDep;
+
+ /*
+ Loop through the dependencyProperties, look for string class names and push
+ them into a stack, regardless of whether the property's value is a string, array or object. For example:
+ {
+ extend: 'Ext.MyClass',
+ requires: ['Ext.some.OtherClass'],
+ mixins: {
+ observable: 'Ext.util.Observable';
+ }
+ }
+ which will later be transformed into:
+ {
+ extend: Ext.MyClass,
+ requires: [Ext.some.OtherClass],
+ mixins: {
+ observable: Ext.util.Observable;
+ }
+ }
+ */
+
+ for (i = 0,ln = dependencyProperties.length; i < ln; i++) {
+ propertyName = dependencyProperties[i];
+
+ if (data.hasOwnProperty(propertyName)) {
+ propertyValue = data[propertyName];
+
+ if (typeof propertyValue == 'string') {
+ dependencies.push(propertyValue);
+ }
+ else if (propertyValue instanceof Array) {
+ for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
+ value = propertyValue[j];
+
+ if (typeof value == 'string') {
+ dependencies.push(value);
+ }
+ }
+ }
+ else if (typeof propertyValue != 'function') {
+ for (j in propertyValue) {
+ if (propertyValue.hasOwnProperty(j)) {
+ value = propertyValue[j];
+
+ if (typeof value == 'string') {
+ dependencies.push(value);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (dependencies.length === 0) {
+ return;
+ }
+
+ var deadlockPath = [],
+ detectDeadlock;
+
+ /*
+ Automatically detect deadlocks before-hand,
+ will throw an error with detailed path for ease of debugging. Examples of deadlock cases:
+
+ - A extends B, then B extends A
+ - A requires B, B requires C, then C requires A
+
+ The detectDeadlock function will recursively transverse till the leaf, hence it can detect deadlocks
+ no matter how deep the path is.
+ */
+
+ if (className) {
+ requiresMap[className] = dependencies;
+ requiredMap = Loader.requiredByMap || (Loader.requiredByMap = {});
+
+ for (i = 0,ln = dependencies.length; i < ln; i++) {
+ dependency = dependencies[i];
+ (requiredMap[dependency] || (requiredMap[dependency] = [])).push(className);
+ }
+ detectDeadlock = function(cls) {
+ deadlockPath.push(cls);
+
+ if (requiresMap[cls]) {
+ if (Ext.Array.contains(requiresMap[cls], className)) {
+ throw new Error("Deadlock detected while loading dependencies! '" + className + "' and '" +
+ deadlockPath[1] + "' " + "mutually require each other. Path: " +
+ deadlockPath.join(' -> ') + " -> " + deadlockPath[0]);
+ }
+
+ for (i = 0,ln = requiresMap[cls].length; i < ln; i++) {
+ detectDeadlock(requiresMap[cls][i]);
+ }
+ }
+ };
+
+ detectDeadlock(className);
+ }
+
+
+ Loader.require(dependencies, function() {
+ for (i = 0,ln = dependencyProperties.length; i < ln; i++) {
+ propertyName = dependencyProperties[i];
+
+ if (data.hasOwnProperty(propertyName)) {
+ propertyValue = data[propertyName];
+
+ if (typeof propertyValue == 'string') {
+ data[propertyName] = Manager.get(propertyValue);
+ }
+ else if (propertyValue instanceof Array) {
+ for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
+ value = propertyValue[j];
+
+ if (typeof value == 'string') {
+ data[propertyName][j] = Manager.get(value);
+ }
+ }
+ }
+ else if (typeof propertyValue != 'function') {
+ for (var k in propertyValue) {
+ if (propertyValue.hasOwnProperty(k)) {
+ value = propertyValue[k];
+
+ if (typeof value == 'string') {
+ data[propertyName][k] = Manager.get(value);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ continueFn.call(me, cls, data, hooks);
+ });
+
+ return false;
+ }, true, 'after', 'className');
+
+ /**
+ * @cfg {String[]} uses
+ * @member Ext.Class
+ * List of optional classes to load together with this class. These aren't neccessarily loaded before
+ * this class is created, but are guaranteed to be available before Ext.onReady listeners are
+ * invoked. For example:
+ *
+ * Ext.define('Mother', {
+ * uses: ['Child'],
+ * giveBirth: function() {
+ * // This code might, or might not work:
+ * // return new Child();
+ *
+ * // Instead use Ext.create() to load the class at the spot if not loaded already:
+ * return Ext.create('Child');
+ * }
+ * });
+ */
+ Manager.registerPostprocessor('uses', function(name, cls, data) {
+ var uses = data.uses;
+ if (uses) {
+ Loader.addUsedClasses(uses);
+ }
+ });
+
+ Manager.onCreated(Loader.historyPush);
+};
+
+// simple mechanism for automated means of injecting large amounts of dependency info
+// at the appropriate time in the load cycle
+if (Ext._classPathMetadata) {
+ Ext.Loader.addClassPathMappings(Ext._classPathMetadata);
+ Ext._classPathMetadata = null;
+}
+
+// initalize the default path of the framework
+(function() {
+ var scripts = document.getElementsByTagName('script'),
+ currentScript = scripts[scripts.length - 1],
+ src = currentScript.src,
+ path = src.substring(0, src.lastIndexOf('/') + 1),
+ Loader = Ext.Loader;
+
+ if(src.indexOf("/platform/core/src/class/") != -1) {
+ path = path + "../../../../extjs/";
+ } else if(src.indexOf("/core/src/class/") != -1) {
+ path = path + "../../../";
+ }
+
+ Loader.setConfig({
+ enabled: true,
+ disableCaching: true,
+ paths: {
+ 'Ext': path + 'src'
+ }
+ });
+})();
+
+// allows a tools like dynatrace to deterministically detect onReady state by invoking
+// a callback (intended for external consumption)
+Ext._endTime = new Date().getTime();
+if (Ext._beforereadyhandler){
+ Ext._beforereadyhandler();
+}
+
+//@tag foundation,core
+//@require ../class/Loader.js
+
+/**
+ * @author Brian Moeskau
+ * @docauthor Brian Moeskau
+ *
+ * A wrapper class for the native JavaScript Error object that adds a few useful capabilities for handling
+ * errors in an Ext application. When you use Ext.Error to {@link #raise} an error from within any class that
+ * uses the Ext 4 class system, the Error class can automatically add the source class and method from which
+ * the error was raised. It also includes logic to automatically log the eroor to the console, if available,
+ * with additional metadata about the error. In all cases, the error will always be thrown at the end so that
+ * execution will halt.
+ *
+ * Ext.Error also offers a global error {@link #handle handling} method that can be overridden in order to
+ * handle application-wide errors in a single spot. You can optionally {@link #ignore} errors altogether,
+ * although in a real application it's usually a better idea to override the handling function and perform
+ * logging or some other method of reporting the errors in a way that is meaningful to the application.
+ *
+ * At its simplest you can simply raise an error as a simple string from within any code:
+ *
+ * Example usage:
+ *
+ * Ext.Error.raise('Something bad happened!');
+ *
+ * If raised from plain JavaScript code, the error will be logged to the console (if available) and the message
+ * displayed. In most cases however you'll be raising errors from within a class, and it may often be useful to add
+ * additional metadata about the error being raised. The {@link #raise} method can also take a config object.
+ * In this form the `msg` attribute becomes the error description, and any other data added to the config gets
+ * added to the error object and, if the console is available, logged to the console for inspection.
+ *
+ * Example usage:
+ *
+ * Ext.define('Ext.Foo', {
+ * doSomething: function(option){
+ * if (someCondition === false) {
+ * Ext.Error.raise({
+ * msg: 'You cannot do that!',
+ * option: option, // whatever was passed into the method
+ * 'error code': 100 // other arbitrary info
+ * });
+ * }
+ * }
+ * });
+ *
+ * If a console is available (that supports the `console.dir` function) you'll see console output like:
+ *
+ * An error was raised with the following data:
+ * option: Object { foo: "bar"}
+ * foo: "bar"
+ * error code: 100
+ * msg: "You cannot do that!"
+ * sourceClass: "Ext.Foo"
+ * sourceMethod: "doSomething"
+ *
+ * uncaught exception: You cannot do that!
+ *
+ * As you can see, the error will report exactly where it was raised and will include as much information as the
+ * raising code can usefully provide.
+ *
+ * If you want to handle all application errors globally you can simply override the static {@link #handle} method
+ * and provide whatever handling logic you need. If the method returns true then the error is considered handled
+ * and will not be thrown to the browser. If anything but true is returned then the error will be thrown normally.
+ *
+ * Example usage:
+ *
+ * Ext.Error.handle = function(err) {
+ * if (err.someProperty == 'NotReallyAnError') {
+ * // maybe log something to the application here if applicable
+ * return true;
+ * }
+ * // any non-true return value (including none) will cause the error to be thrown
+ * }
+ *
+ */
+Ext.Error = Ext.extend(Error, {
+ statics: {
+ /**
+ * @property {Boolean} ignore
+ * Static flag that can be used to globally disable error reporting to the browser if set to true
+ * (defaults to false). Note that if you ignore Ext errors it's likely that some other code may fail
+ * and throw a native JavaScript error thereafter, so use with caution. In most cases it will probably
+ * be preferable to supply a custom error {@link #handle handling} function instead.
+ *
+ * Example usage:
+ *
+ * Ext.Error.ignore = true;
+ *
+ * @static
+ */
+ ignore: false,
+
+ /**
+ * @property {Boolean} notify
+ * Static flag that can be used to globally control error notification to the user. Unlike
+ * Ex.Error.ignore, this does not effect exceptions. They are still thrown. This value can be
+ * set to false to disable the alert notification (default is true for IE6 and IE7).
+ *
+ * Only the first error will generate an alert. Internally this flag is set to false when the
+ * first error occurs prior to displaying the alert.
+ *
+ * This flag is not used in a release build.
+ *
+ * Example usage:
+ *
+ * Ext.Error.notify = false;
+ *
+ * @static
+ */
+ //notify: Ext.isIE6 || Ext.isIE7,
+
+ /**
+ * Raise an error that can include additional data and supports automatic console logging if available.
+ * You can pass a string error message or an object with the `msg` attribute which will be used as the
+ * error message. The object can contain any other name-value attributes (or objects) to be logged
+ * along with the error.
+ *
+ * Note that after displaying the error message a JavaScript error will ultimately be thrown so that
+ * execution will halt.
+ *
+ * Example usage:
+ *
+ * Ext.Error.raise('A simple string error message');
+ *
+ * // or...
+ *
+ * Ext.define('Ext.Foo', {
+ * doSomething: function(option){
+ * if (someCondition === false) {
+ * Ext.Error.raise({
+ * msg: 'You cannot do that!',
+ * option: option, // whatever was passed into the method
+ * 'error code': 100 // other arbitrary info
+ * });
+ * }
+ * }
+ * });
+ *
+ * @param {String/Object} err The error message string, or an object containing the attribute "msg" that will be
+ * used as the error message. Any other data included in the object will also be logged to the browser console,
+ * if available.
+ * @static
+ */
+ raise: function(err){
+ err = err || {};
+ if (Ext.isString(err)) {
+ err = { msg: err };
+ }
+
+ var method = this.raise.caller,
+ msg;
+
+ if (method) {
+ if (method.$name) {
+ err.sourceMethod = method.$name;
+ }
+ if (method.$owner) {
+ err.sourceClass = method.$owner.$className;
+ }
+ }
+
+ if (Ext.Error.handle(err) !== true) {
+ msg = Ext.Error.prototype.toString.call(err);
+
+ Ext.log({
+ msg: msg,
+ level: 'error',
+ dump: err,
+ stack: true
+ });
+
+ throw new Ext.Error(err);
+ }
+ },
+
+ /**
+ * Globally handle any Ext errors that may be raised, optionally providing custom logic to
+ * handle different errors individually. Return true from the function to bypass throwing the
+ * error to the browser, otherwise the error will be thrown and execution will halt.
+ *
+ * Example usage:
+ *
+ * Ext.Error.handle = function(err) {
+ * if (err.someProperty == 'NotReallyAnError') {
+ * // maybe log something to the application here if applicable
+ * return true;
+ * }
+ * // any non-true return value (including none) will cause the error to be thrown
+ * }
+ *
+ * @param {Ext.Error} err The Ext.Error object being raised. It will contain any attributes that were originally
+ * raised with it, plus properties about the method and class from which the error originated (if raised from a
+ * class that uses the Ext 4 class system).
+ * @static
+ */
+ handle: function(){
+ return Ext.Error.ignore;
+ }
+ },
+
+ // This is the standard property that is the name of the constructor.
+ name: 'Ext.Error',
+
+ /**
+ * Creates new Error object.
+ * @param {String/Object} config The error message string, or an object containing the
+ * attribute "msg" that will be used as the error message. Any other data included in
+ * the object will be applied to the error instance and logged to the browser console, if available.
+ */
+ constructor: function(config){
+ if (Ext.isString(config)) {
+ config = { msg: config };
+ }
+
+ var me = this;
+
+ Ext.apply(me, config);
+
+ me.message = me.message || me.msg; // 'message' is standard ('msg' is non-standard)
+ // note: the above does not work in old WebKit (me.message is readonly) (Safari 4)
+ },
+
+ /**
+ * Provides a custom string representation of the error object. This is an override of the base JavaScript
+ * `Object.toString` method, which is useful so that when logged to the browser console, an error object will
+ * be displayed with a useful message instead of `[object Object]`, the default `toString` result.
+ *
+ * The default implementation will include the error message along with the raising class and method, if available,
+ * but this can be overridden with a custom implementation either at the prototype level (for all errors) or on
+ * a particular error instance, if you want to provide a custom description that will show up in the console.
+ * @return {String} The error message. If raised from within the Ext 4 class system, the error message will also
+ * include the raising class and method names, if available.
+ */
+ toString: function(){
+ var me = this,
+ className = me.sourceClass ? me.sourceClass : '',
+ methodName = me.sourceMethod ? '.' + me.sourceMethod + '(): ' : '',
+ msg = me.msg || '(No description provided)';
+
+ return className + methodName + msg;
+ }
+});
+
+/*
+ * Create a function that will throw an error if called (in debug mode) with a message that
+ * indicates the method has been removed.
+ * @param {String} suggestion Optional text to include in the message (a workaround perhaps).
+ * @return {Function} The generated function.
+ * @private
+ */
+Ext.deprecated = function (suggestion) {
+ if (!suggestion) {
+ suggestion = '';
+ }
+
+ function fail () {
+ Ext.Error.raise('The method "' + fail.$owner.$className + '.' + fail.$name +
+ '" has been removed. ' + suggestion);
+ }
+
+ return fail;
+ return Ext.emptyFn;
+};
+
+/*
+ * This mechanism is used to notify the user of the first error encountered on the page. This
+ * was previously internal to Ext.Error.raise and is a desirable feature since errors often
+ * slip silently under the radar. It cannot live in Ext.Error.raise since there are times
+ * where exceptions are handled in a try/catch.
+ */
+(function () {
+ var timer, errors = 0,
+ win = Ext.global,
+ msg;
+
+ if (typeof window === 'undefined') {
+ return; // build system or some such environment...
+ }
+
+ // This method is called to notify the user of the current error status.
+ function notify () {
+ var counters = Ext.log.counters,
+ supports = Ext.supports,
+ hasOnError = supports && supports.WindowOnError; // TODO - timing
+
+ // Put log counters to the status bar (for most browsers):
+ if (counters && (counters.error + counters.warn + counters.info + counters.log)) {
+ msg = [ 'Logged Errors:',counters.error, 'Warnings:',counters.warn,
+ 'Info:',counters.info, 'Log:',counters.log].join(' ');
+ if (errors) {
+ msg = '*** Errors: ' + errors + ' - ' + msg;
+ } else if (counters.error) {
+ msg = '*** ' + msg;
+ }
+ win.status = msg;
+ }
+
+ // Display an alert on the first error:
+ if (!Ext.isDefined(Ext.Error.notify)) {
+ Ext.Error.notify = Ext.isIE6 || Ext.isIE7; // TODO - timing
+ }
+ if (Ext.Error.notify && (hasOnError ? errors : (counters && counters.error))) {
+ Ext.Error.notify = false;
+
+ if (timer) {
+ win.clearInterval(timer); // ticks can queue up so stop...
+ timer = null;
+ }
+
+ alert('Unhandled error on page: See console or log');
+ poll();
+ }
+ }
+
+ // Sets up polling loop. This is the only way to know about errors in some browsers
+ // (Opera/Safari) and is the only way to update the status bar for warnings and other
+ // non-errors.
+ function poll () {
+ timer = win.setInterval(notify, 1000);
+ }
+
+ // window.onerror sounds ideal but it prevents the built-in error dialog from doing
+ // its (better) thing.
+ poll();
+}());
+
+//@tag extras,core
+//@require ../lang/Error.js
+
+/**
+ * Modified version of [Douglas Crockford's JSON.js][dc] that doesn't
+ * mess with the Object prototype.
+ *
+ * [dc]: http://www.json.org/js.html
+ *
+ * @singleton
+ */
+Ext.JSON = (new(function() {
+ var me = this,
+ encodingFunction,
+ decodingFunction,
+ useNative = null,
+ useHasOwn = !! {}.hasOwnProperty,
+ isNative = function() {
+ if (useNative === null) {
+ useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]';
+ }
+ return useNative;
+ },
+ pad = function(n) {
+ return n < 10 ? "0" + n : n;
+ },
+ doDecode = function(json) {
+ return eval("(" + json + ')');
+ },
+ doEncode = function(o, newline) {
+ // http://jsperf.com/is-undefined
+ if (o === null || o === undefined) {
+ return "null";
+ } else if (Ext.isDate(o)) {
+ return Ext.JSON.encodeDate(o);
+ } else if (Ext.isString(o)) {
+ return Ext.JSON.encodeString(o);
+ } else if (typeof o == "number") {
+ //don't use isNumber here, since finite checks happen inside isNumber
+ return isFinite(o) ? String(o) : "null";
+ } else if (Ext.isBoolean(o)) {
+ return String(o);
+ }
+ // Allow custom zerialization by adding a toJSON method to any object type.
+ // Date/String have a toJSON in some environments, so check these first.
+ else if (o.toJSON) {
+ return o.toJSON();
+ } else if (Ext.isArray(o)) {
+ return encodeArray(o, newline);
+ } else if (Ext.isObject(o)) {
+ return encodeObject(o, newline);
+ } else if (typeof o === "function") {
+ return "null";
+ }
+ return 'undefined';
+ },
+ m = {
+ "\b": '\\b',
+ "\t": '\\t',
+ "\n": '\\n',
+ "\f": '\\f',
+ "\r": '\\r',
+ '"': '\\"',
+ "\\": '\\\\',
+ '\x0b': '\\u000b' //ie doesn't handle \v
+ },
+ charToReplace = /[\\\"\x00-\x1f\x7f-\uffff]/g,
+ encodeString = function(s) {
+ return '"' + s.replace(charToReplace, function(a) {
+ var c = m[a];
+ return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"';
+ },
+
+ encodeArrayPretty = function(o, newline) {
+ var len = o.length,
+ cnewline = newline + ' ',
+ sep = ',' + cnewline,
+ a = ["[", cnewline], // Note newline in case there are no members
+ i;
+
+ for (i = 0; i < len; i += 1) {
+ a.push(Ext.JSON.encodeValue(o[i], cnewline), sep);
+ }
+
+ // Overwrite trailing comma (or empty string)
+ a[a.length - 1] = newline + ']';
+
+ return a.join('');
+ },
+
+ encodeObjectPretty = function(o, newline) {
+ var cnewline = newline + ' ',
+ sep = ',' + cnewline,
+ a = ["{", cnewline], // Note newline in case there are no members
+ i;
+
+ for (i in o) {
+ if (!useHasOwn || o.hasOwnProperty(i)) {
+ a.push(Ext.JSON.encodeValue(i) + ': ' + Ext.JSON.encodeValue(o[i], cnewline), sep);
+ }
+ }
+
+ // Overwrite trailing comma (or empty string)
+ a[a.length - 1] = newline + '}';
+
+ return a.join('');
+ },
+
+ encodeArray = function(o, newline) {
+ if (newline) {
+ return encodeArrayPretty(o, newline);
+ }
+
+ var a = ["[", ""], // Note empty string in case there are no serializable members.
+ len = o.length,
+ i;
+ for (i = 0; i < len; i += 1) {
+ a.push(Ext.JSON.encodeValue(o[i]), ',');
+ }
+ // Overwrite trailing comma (or empty string)
+ a[a.length - 1] = ']';
+ return a.join("");
+ },
+
+ encodeObject = function(o, newline) {
+ if (newline) {
+ return encodeObjectPretty(o, newline);
+ }
+
+ var a = ["{", ""], // Note empty string in case there are no serializable members.
+ i;
+ for (i in o) {
+ if (!useHasOwn || o.hasOwnProperty(i)) {
+ a.push(Ext.JSON.encodeValue(i), ":", Ext.JSON.encodeValue(o[i]), ',');
+ }
+ }
+ // Overwrite trailing comma (or empty string)
+ a[a.length - 1] = '}';
+ return a.join("");
+ };
+
+ /**
+ * Encodes a String. This returns the actual string which is inserted into the JSON string as the literal
+ * expression. **The returned value includes enclosing double quotation marks.**
+ *
+ * To override this:
+ *
+ * Ext.JSON.encodeString = function(s) {
+ * return 'Foo' + s;
+ * };
+ *
+ * @param {String} s The String to encode
+ * @return {String} The string literal to use in a JSON string.
+ * @method
+ */
+ me.encodeString = encodeString;
+
+ /**
+ * The function which {@link #encode} uses to encode all javascript values to their JSON representations
+ * when {@link Ext#USE_NATIVE_JSON} is `false`.
+ *
+ * This is made public so that it can be replaced with a custom implementation.
+ *
+ * @param {Object} o Any javascript value to be converted to its JSON representation
+ * @return {String} The JSON representation of the passed value.
+ * @method
+ */
+ me.encodeValue = doEncode;
+
+ /**
+ * Encodes a Date. This returns the actual string which is inserted into the JSON string as the literal
+ * expression. **The returned value includes enclosing double quotation marks.**
+ *
+ * The default return format is `"yyyy-mm-ddThh:mm:ss"`.
+ *
+ * To override this:
+ *
+ * Ext.JSON.encodeDate = function(d) {
+ * return Ext.Date.format(d, '"Y-m-d"');
+ * };
+ *
+ * @param {Date} d The Date to encode
+ * @return {String} The string literal to use in a JSON string.
+ */
+ me.encodeDate = function(o) {
+ return '"' + o.getFullYear() + "-"
+ + pad(o.getMonth() + 1) + "-"
+ + pad(o.getDate()) + "T"
+ + pad(o.getHours()) + ":"
+ + pad(o.getMinutes()) + ":"
+ + pad(o.getSeconds()) + '"';
+ };
+
+ /**
+ * Encodes an Object, Array or other value.
+ *
+ * If the environment's native JSON encoding is not being used ({@link Ext#USE_NATIVE_JSON} is not set,
+ * or the environment does not support it), then ExtJS's encoding will be used. This allows the developer
+ * to add a `toJSON` method to their classes which need serializing to return a valid JSON representation
+ * of the object.
+ *
+ * @param {Object} o The variable to encode
+ * @return {String} The JSON string
+ */
+ me.encode = function(o) {
+ if (!encodingFunction) {
+ // setup encoding function on first access
+ encodingFunction = isNative() ? JSON.stringify : me.encodeValue;
+ }
+ return encodingFunction(o);
+ };
+
+ /**
+ * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws
+ * a SyntaxError unless the safe option is set.
+ *
+ * @param {String} json The JSON string
+ * @param {Boolean} [safe=false] True to return null, false to throw an exception if the JSON is invalid.
+ * @return {Object} The resulting object
+ */
+ me.decode = function(json, safe) {
+ if (!decodingFunction) {
+ // setup decoding function on first access
+ decodingFunction = isNative() ? JSON.parse : doDecode;
+ }
+ try {
+ return decodingFunction(json);
+ } catch (e) {
+ if (safe === true) {
+ return null;
+ }
+ Ext.Error.raise({
+ sourceClass: "Ext.JSON",
+ sourceMethod: "decode",
+ msg: "You're trying to decode an invalid JSON String: " + json
+ });
+ }
+ };
+})());
+/**
+ * Shorthand for {@link Ext.JSON#encode}
+ * @member Ext
+ * @method encode
+ * @inheritdoc Ext.JSON#encode
+ */
+Ext.encode = Ext.JSON.encode;
+/**
+ * Shorthand for {@link Ext.JSON#decode}
+ * @member Ext
+ * @method decode
+ * @inheritdoc Ext.JSON#decode
+ */
+Ext.decode = Ext.JSON.decode;
+
+//@tag extras,core
+//@require misc/JSON.js
+
+/**
+ * @class Ext
+ *
+ * The Ext namespace (global object) encapsulates all classes, singletons, and
+ * utility methods provided by Sencha's libraries.
+ *
+ * Most user interface Components are at a lower level of nesting in the namespace,
+ * but many common utility functions are provided as direct properties of the Ext namespace.
+ *
+ * Also many frequently used methods from other classes are provided as shortcuts
+ * within the Ext namespace. For example {@link Ext#getCmp Ext.getCmp} aliases
+ * {@link Ext.ComponentManager#get Ext.ComponentManager.get}.
+ *
+ * Many applications are initiated with {@link Ext#onReady Ext.onReady} which is
+ * called once the DOM is ready. This ensures all scripts have been loaded,
+ * preventing dependency issues. For example:
+ *
+ * Ext.onReady(function(){
+ * new Ext.Component({
+ * renderTo: document.body,
+ * html: 'DOM ready!'
+ * });
+ * });
+ *
+ * For more information about how to use the Ext classes, see:
+ *
+ * - The Learning Center
+ * - The FAQ
+ * - The forums
+ *
+ * @singleton
+ */
+Ext.apply(Ext, {
+ userAgent: navigator.userAgent.toLowerCase(),
+ cache: {},
+ idSeed: 1000,
+ windowId: 'ext-window',
+ documentId: 'ext-document',
+
+ /**
+ * True when the document is fully initialized and ready for action
+ */
+ isReady: false,
+
+ /**
+ * True to automatically uncache orphaned Ext.Elements periodically
+ */
+ enableGarbageCollector: true,
+
+ /**
+ * True to automatically purge event listeners during garbageCollection.
+ */
+ enableListenerCollection: true,
+
+ addCacheEntry: function(id, el, dom) {
+ dom = dom || el.dom;
+
+ if (!dom) {
+ // Without the DOM node we can't GC the entry
+ Ext.Error.raise('Cannot add an entry to the element cache without the DOM node');
+ }
+
+ var key = id || (el && el.id) || dom.id,
+ entry = Ext.cache[key] || (Ext.cache[key] = {
+ data: {},
+ events: {},
+
+ dom: dom,
+
+ // Skip garbage collection for special elements (window, document, iframes)
+ skipGarbageCollection: !!(dom.getElementById || dom.navigator)
+ });
+
+ if (el) {
+ el.$cache = entry;
+ // Inject the back link from the cache in case the cache entry
+ // had already been created by Ext.fly. Ext.fly creates a cache entry with no el link.
+ entry.el = el;
+ }
+
+ return entry;
+ },
+
+ updateCacheEntry: function(cacheItem, dom){
+ cacheItem.dom = dom;
+ if (cacheItem.el) {
+ cacheItem.el.dom = dom;
+ }
+ return cacheItem;
+ },
+
+ /**
+ * Generates unique ids. If the element already has an id, it is unchanged
+ * @param {HTMLElement/Ext.Element} [el] The element to generate an id for
+ * @param {String} prefix (optional) Id prefix (defaults "ext-gen")
+ * @return {String} The generated Id.
+ */
+ id: function(el, prefix) {
+ var me = this,
+ sandboxPrefix = '';
+ el = Ext.getDom(el, true) || {};
+ if (el === document) {
+ el.id = me.documentId;
+ }
+ else if (el === window) {
+ el.id = me.windowId;
+ }
+ if (!el.id) {
+ if (me.isSandboxed) {
+ sandboxPrefix = Ext.sandboxName.toLowerCase() + '-';
+ }
+ el.id = sandboxPrefix + (prefix || "ext-gen") + (++Ext.idSeed);
+ }
+ return el.id;
+ },
+
+ escapeId: (function(){
+ var validIdRe = /^[a-zA-Z_][a-zA-Z0-9_\-]*$/i,
+ escapeRx = /([\W]{1})/g,
+ leadingNumRx = /^(\d)/g,
+ escapeFn = function(match, capture){
+ return "\\" + capture;
+ },
+ numEscapeFn = function(match, capture){
+ return '\\00' + capture.charCodeAt(0).toString(16) + ' ';
+ };
+
+ return function(id) {
+ return validIdRe.test(id)
+ ? id
+ // replace the number portion last to keep the trailing ' '
+ // from being escaped
+ : id.replace(escapeRx, escapeFn)
+ .replace(leadingNumRx, numEscapeFn);
+ };
+ }()),
+
+ /**
+ * Returns the current document body as an {@link Ext.Element}.
+ * @return Ext.Element The document body
+ */
+ getBody: (function() {
+ var body;
+ return function() {
+ return body || (body = Ext.get(document.body));
+ };
+ }()),
+
+ /**
+ * Returns the current document head as an {@link Ext.Element}.
+ * @return Ext.Element The document head
+ * @method
+ */
+ getHead: (function() {
+ var head;
+ return function() {
+ return head || (head = Ext.get(document.getElementsByTagName("head")[0]));
+ };
+ }()),
+
+ /**
+ * Returns the current HTML document object as an {@link Ext.Element}.
+ * @return Ext.Element The document
+ */
+ getDoc: (function() {
+ var doc;
+ return function() {
+ return doc || (doc = Ext.get(document));
+ };
+ }()),
+
+ /**
+ * This is shorthand reference to {@link Ext.ComponentManager#get}.
+ * Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#id id}
+ *
+ * @param {String} id The component {@link Ext.Component#id id}
+ * @return Ext.Component The Component, `undefined` if not found, or `null` if a
+ * Class was found.
+ */
+ getCmp: function(id) {
+ return Ext.ComponentManager.get(id);
+ },
+
+ /**
+ * Returns the current orientation of the mobile device
+ * @return {String} Either 'portrait' or 'landscape'
+ */
+ getOrientation: function() {
+ return window.innerHeight > window.innerWidth ? 'portrait' : 'landscape';
+ },
+
+ /**
+ * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the
+ * DOM (if applicable) and calling their destroy functions (if available). This method is primarily
+ * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of
+ * {@link Ext.util.Observable} can be passed in. Any number of elements and/or components can be
+ * passed into this function in a single call as separate arguments.
+ *
+ * @param {Ext.Element/Ext.Component/Ext.Element[]/Ext.Component[]...} args
+ * An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy
+ */
+ destroy: function() {
+ var ln = arguments.length,
+ i, arg;
+
+ for (i = 0; i < ln; i++) {
+ arg = arguments[i];
+ if (arg) {
+ if (Ext.isArray(arg)) {
+ this.destroy.apply(this, arg);
+ }
+ else if (Ext.isFunction(arg.destroy)) {
+ arg.destroy();
+ }
+ else if (arg.dom) {
+ arg.remove();
+ }
+ }
+ }
+ },
+
+ /**
+ * Execute a callback function in a particular scope. If no function is passed the call is ignored.
+ *
+ * For example, these lines are equivalent:
+ *
+ * Ext.callback(myFunc, this, [arg1, arg2]);
+ * Ext.isFunction(myFunc) && myFunc.apply(this, [arg1, arg2]);
+ *
+ * @param {Function} callback The callback to execute
+ * @param {Object} [scope] The scope to execute in
+ * @param {Array} [args] The arguments to pass to the function
+ * @param {Number} [delay] Pass a number to delay the call by a number of milliseconds.
+ */
+ callback: function(callback, scope, args, delay){
+ if(Ext.isFunction(callback)){
+ args = args || [];
+ scope = scope || window;
+ if (delay) {
+ Ext.defer(callback, delay, scope, args);
+ } else {
+ callback.apply(scope, args);
+ }
+ }
+ },
+
+ /**
+ * Alias for {@link Ext.String#htmlEncode}.
+ * @inheritdoc Ext.String#htmlEncode
+ * @ignore
+ */
+ htmlEncode : function(value) {
+ return Ext.String.htmlEncode(value);
+ },
+
+ /**
+ * Alias for {@link Ext.String#htmlDecode}.
+ * @inheritdoc Ext.String#htmlDecode
+ * @ignore
+ */
+ htmlDecode : function(value) {
+ return Ext.String.htmlDecode(value);
+ },
+
+ /**
+ * Alias for {@link Ext.String#urlAppend}.
+ * @inheritdoc Ext.String#urlAppend
+ * @ignore
+ */
+ urlAppend : function(url, s) {
+ return Ext.String.urlAppend(url, s);
+ }
+});
+
+
+Ext.ns = Ext.namespace;
+
+// for old browsers
+window.undefined = window.undefined;
+
+/**
+ * @class Ext
+ */
+(function(){
+/*
+FF 3.6 - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/20110420 Firefox/3.6.17
+FF 4.0.1 - Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
+FF 5.0 - Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0
+
+IE6 - Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;)
+IE7 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1;)
+IE8 - Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
+IE9 - Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
+
+Chrome 11 - Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.60 Safari/534.24
+
+Safari 5 - Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1
+
+Opera 11.11 - Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11
+*/
+ var check = function(regex){
+ return regex.test(Ext.userAgent);
+ },
+ isStrict = document.compatMode == "CSS1Compat",
+ version = function (is, regex) {
+ var m;
+ return (is && (m = regex.exec(Ext.userAgent))) ? parseFloat(m[1]) : 0;
+ },
+ docMode = document.documentMode,
+ isOpera = check(/opera/),
+ isOpera10_5 = isOpera && check(/version\/10\.5/),
+ isChrome = check(/\bchrome\b/),
+ isWebKit = check(/webkit/),
+ isSafari = !isChrome && check(/safari/),
+ isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2
+ isSafari3 = isSafari && check(/version\/3/),
+ isSafari4 = isSafari && check(/version\/4/),
+ isSafari5_0 = isSafari && check(/version\/5\.0/),
+ isSafari5 = isSafari && check(/version\/5/),
+ isIE = !isOpera && check(/msie/),
+ isIE7 = isIE && ((check(/msie 7/) && docMode != 8 && docMode != 9) || docMode == 7),
+ isIE8 = isIE && ((check(/msie 8/) && docMode != 7 && docMode != 9) || docMode == 8),
+ isIE9 = isIE && ((check(/msie 9/) && docMode != 7 && docMode != 8) || docMode == 9),
+ isIE6 = isIE && check(/msie 6/),
+ isGecko = !isWebKit && check(/gecko/),
+ isGecko3 = isGecko && check(/rv:1\.9/),
+ isGecko4 = isGecko && check(/rv:2\.0/),
+ isGecko5 = isGecko && check(/rv:5\./),
+ isGecko10 = isGecko && check(/rv:10\./),
+ isFF3_0 = isGecko3 && check(/rv:1\.9\.0/),
+ isFF3_5 = isGecko3 && check(/rv:1\.9\.1/),
+ isFF3_6 = isGecko3 && check(/rv:1\.9\.2/),
+ isWindows = check(/windows|win32/),
+ isMac = check(/macintosh|mac os x/),
+ isLinux = check(/linux/),
+ scrollbarSize = null,
+ chromeVersion = version(true, /\bchrome\/(\d+\.\d+)/),
+ firefoxVersion = version(true, /\bfirefox\/(\d+\.\d+)/),
+ ieVersion = version(isIE, /msie (\d+\.\d+)/),
+ operaVersion = version(isOpera, /version\/(\d+\.\d+)/),
+ safariVersion = version(isSafari, /version\/(\d+\.\d+)/),
+ webKitVersion = version(isWebKit, /webkit\/(\d+\.\d+)/),
+ isSecure = /^https/i.test(window.location.protocol),
+ nullLog;
+
+ // remove css image flicker
+ try {
+ document.execCommand("BackgroundImageCache", false, true);
+ } catch(e) {}
+
+
+ var primitiveRe = /string|number|boolean/;
+ function dumpObject (object) {
+ var member, type, value, name,
+ members = [];
+
+ // Cannot use Ext.encode since it can recurse endlessly (if we're lucky)
+ // ...and the data could be prettier!
+ for (name in object) {
+ if (object.hasOwnProperty(name)) {
+ value = object[name];
+
+ type = typeof value;
+ if (type == "function") {
+ continue;
+ }
+
+ if (type == 'undefined') {
+ member = type;
+ } else if (value === null || primitiveRe.test(type) || Ext.isDate(value)) {
+ member = Ext.encode(value);
+ } else if (Ext.isArray(value)) {
+ member = '[ ]';
+ } else if (Ext.isObject(value)) {
+ member = '{ }';
+ } else {
+ member = type;
+ }
+ members.push(Ext.encode(name) + ': ' + member);
+ }
+ }
+
+ if (members.length) {
+ return ' \nData: {\n ' + members.join(',\n ') + '\n}';
+ }
+ return '';
+ }
+
+ function log (message) {
+ var options, dump,
+ con = Ext.global.console,
+ level = 'log',
+ indent = log.indent || 0,
+ stack,
+ out,
+ max;
+
+ log.indent = indent;
+
+ if (typeof message != 'string') {
+ options = message;
+ message = options.msg || '';
+ level = options.level || level;
+ dump = options.dump;
+ stack = options.stack;
+
+ if (options.indent) {
+ ++log.indent;
+ } else if (options.outdent) {
+ log.indent = indent = Math.max(indent - 1, 0);
+ }
+
+ if (dump && !(con && con.dir)) {
+ message += dumpObject(dump);
+ dump = null;
+ }
+ }
+
+ if (arguments.length > 1) {
+ message += Array.prototype.slice.call(arguments, 1).join('');
+ }
+
+ message = indent ? Ext.String.repeat(' ', log.indentSize * indent) + message : message;
+ // w/o console, all messages are equal, so munge the level into the message:
+ if (level != 'log') {
+ message = '[' + level.charAt(0).toUpperCase() + '] ' + message;
+ }
+
+ // Not obvious, but 'console' comes and goes when Firebug is turned on/off, so
+ // an early test may fail either direction if Firebug is toggled.
+ //
+ if (con) { // if (Firebug-like console)
+ if (con[level]) {
+ con[level](message);
+ } else {
+ con.log(message);
+ }
+
+ if (dump) {
+ con.dir(dump);
+ }
+
+ if (stack && con.trace) {
+ // Firebug's console.error() includes a trace already...
+ if (!con.firebug || level != 'error') {
+ con.trace();
+ }
+ }
+ } else {
+ if (Ext.isOpera) {
+ opera.postError(message);
+ } else {
+ out = log.out;
+ max = log.max;
+
+ if (out.length >= max) {
+ // this formula allows out.max to change (via debugger), where the
+ // more obvious "max/4" would not quite be the same
+ Ext.Array.erase(out, 0, out.length - 3 * Math.floor(max / 4)); // keep newest 75%
+ }
+
+ out.push(message);
+ }
+ }
+
+ // Mostly informational, but the Ext.Error notifier uses them:
+ ++log.count;
+ ++log.counters[level];
+ }
+
+ function logx (level, args) {
+ if (typeof args[0] == 'string') {
+ args.unshift({});
+ }
+ args[0].level = level;
+ log.apply(this, args);
+ }
+
+ log.error = function () {
+ logx('error', Array.prototype.slice.call(arguments));
+ };
+ log.info = function () {
+ logx('info', Array.prototype.slice.call(arguments));
+ };
+ log.warn = function () {
+ logx('warn', Array.prototype.slice.call(arguments));
+ };
+
+ log.count = 0;
+ log.counters = { error: 0, warn: 0, info: 0, log: 0 };
+ log.indentSize = 2;
+ log.out = [];
+ log.max = 750;
+ log.show = function () {
+ window.open('','extlog').document.write([
+ ''].join(''));
+ };
+
+ nullLog = function () {};
+ nullLog.info = nullLog.warn = nullLog.error = Ext.emptyFn;
+
+ Ext.setVersion('extjs', '4.1.1.1');
+ Ext.apply(Ext, {
+ /**
+ * @property {String} SSL_SECURE_URL
+ * URL to a blank file used by Ext when in secure mode for iframe src and onReady src
+ * to prevent the IE insecure content warning (`'about:blank'`, except for IE
+ * in secure mode, which is `'javascript:""'`).
+ */
+ SSL_SECURE_URL : isSecure && isIE ? 'javascript:\'\'' : 'about:blank',
+
+ /**
+ * @property {Boolean} enableFx
+ * True if the {@link Ext.fx.Anim} Class is available.
+ */
+
+ /**
+ * @property {Boolean} scopeResetCSS
+ * True to scope the reset CSS to be just applied to Ext components. Note that this
+ * wraps root containers with an additional element. Also remember that when you turn
+ * on this option, you have to use ext-all-scoped (unless you use the bootstrap.js to
+ * load your javascript, in which case it will be handled for you).
+ */
+ scopeResetCSS : Ext.buildSettings.scopeResetCSS,
+
+ /**
+ * @property {String} resetCls
+ * The css class used to wrap Ext components when the {@link #scopeResetCSS} option
+ * is used.
+ */
+ resetCls: Ext.buildSettings.baseCSSPrefix + 'reset',
+
+ /**
+ * @property {Boolean} enableNestedListenerRemoval
+ * **Experimental.** True to cascade listener removal to child elements when an element
+ * is removed. Currently not optimized for performance.
+ */
+ enableNestedListenerRemoval : false,
+
+ /**
+ * @property {Boolean} USE_NATIVE_JSON
+ * Indicates whether to use native browser parsing for JSON methods.
+ * This option is ignored if the browser does not support native JSON methods.
+ *
+ * **Note:** Native JSON methods will not work with objects that have functions.
+ * Also, property names must be quoted, otherwise the data will not parse.
+ */
+ USE_NATIVE_JSON : false,
+
+ /**
+ * Returns the dom node for the passed String (id), dom node, or Ext.Element.
+ * Optional 'strict' flag is needed for IE since it can return 'name' and
+ * 'id' elements by using getElementById.
+ *
+ * Here are some examples:
+ *
+ * // gets dom node based on id
+ * var elDom = Ext.getDom('elId');
+ * // gets dom node based on the dom node
+ * var elDom1 = Ext.getDom(elDom);
+ *
+ * // If we don't know if we are working with an
+ * // Ext.Element or a dom node use Ext.getDom
+ * function(el){
+ * var dom = Ext.getDom(el);
+ * // do something with the dom node
+ * }
+ *
+ * **Note:** the dom node to be found actually needs to exist (be rendered, etc)
+ * when this method is called to be successful.
+ *
+ * @param {String/HTMLElement/Ext.Element} el
+ * @return HTMLElement
+ */
+ getDom : function(el, strict) {
+ if (!el || !document) {
+ return null;
+ }
+ if (el.dom) {
+ return el.dom;
+ } else {
+ if (typeof el == 'string') {
+ var e = Ext.getElementById(el);
+ // IE returns elements with the 'name' and 'id' attribute.
+ // we do a strict check to return the element with only the id attribute
+ if (e && isIE && strict) {
+ if (el == e.getAttribute('id')) {
+ return e;
+ } else {
+ return null;
+ }
+ }
+ return e;
+ } else {
+ return el;
+ }
+ }
+ },
+
+ /**
+ * Removes a DOM node from the document.
+ *
+ * Removes this element from the document, removes all DOM event listeners, and
+ * deletes the cache reference. All DOM event listeners are removed from this element.
+ * If {@link Ext#enableNestedListenerRemoval Ext.enableNestedListenerRemoval} is
+ * `true`, then DOM event listeners are also removed from all child nodes.
+ * The body node will be ignored if passed in.
+ *
+ * @param {HTMLElement} node The node to remove
+ * @method
+ */
+ removeNode : isIE6 || isIE7 || isIE8
+ ? (function() {
+ var d;
+ return function(n){
+ if(n && n.tagName.toUpperCase() != 'BODY'){
+ (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
+
+ var cache = Ext.cache,
+ id = n.id;
+
+ if (cache[id]) {
+ delete cache[id].dom;
+ delete cache[id];
+ }
+
+ if (isIE8 && n.parentNode) {
+ n.parentNode.removeChild(n);
+ }
+ d = d || document.createElement('div');
+ d.appendChild(n);
+ d.innerHTML = '';
+ }
+ };
+ }())
+ : function(n) {
+ if (n && n.parentNode && n.tagName.toUpperCase() != 'BODY') {
+ (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
+
+ var cache = Ext.cache,
+ id = n.id;
+
+ if (cache[id]) {
+ delete cache[id].dom;
+ delete cache[id];
+ }
+
+ n.parentNode.removeChild(n);
+ }
+ },
+
+ isStrict: isStrict,
+
+ isIEQuirks: isIE && !isStrict,
+
+ /**
+ * True if the detected browser is Opera.
+ * @type Boolean
+ */
+ isOpera : isOpera,
+
+ /**
+ * True if the detected browser is Opera 10.5x.
+ * @type Boolean
+ */
+ isOpera10_5 : isOpera10_5,
+
+ /**
+ * True if the detected browser uses WebKit.
+ * @type Boolean
+ */
+ isWebKit : isWebKit,
+
+ /**
+ * True if the detected browser is Chrome.
+ * @type Boolean
+ */
+ isChrome : isChrome,
+
+ /**
+ * True if the detected browser is Safari.
+ * @type Boolean
+ */
+ isSafari : isSafari,
+
+ /**
+ * True if the detected browser is Safari 3.x.
+ * @type Boolean
+ */
+ isSafari3 : isSafari3,
+
+ /**
+ * True if the detected browser is Safari 4.x.
+ * @type Boolean
+ */
+ isSafari4 : isSafari4,
+
+ /**
+ * True if the detected browser is Safari 5.x.
+ * @type Boolean
+ */
+ isSafari5 : isSafari5,
+
+ /**
+ * True if the detected browser is Safari 5.0.x.
+ * @type Boolean
+ */
+ isSafari5_0 : isSafari5_0,
+
+
+ /**
+ * True if the detected browser is Safari 2.x.
+ * @type Boolean
+ */
+ isSafari2 : isSafari2,
+
+ /**
+ * True if the detected browser is Internet Explorer.
+ * @type Boolean
+ */
+ isIE : isIE,
+
+ /**
+ * True if the detected browser is Internet Explorer 6.x.
+ * @type Boolean
+ */
+ isIE6 : isIE6,
+
+ /**
+ * True if the detected browser is Internet Explorer 7.x.
+ * @type Boolean
+ */
+ isIE7 : isIE7,
+
+ /**
+ * True if the detected browser is Internet Explorer 8.x.
+ * @type Boolean
+ */
+ isIE8 : isIE8,
+
+ /**
+ * True if the detected browser is Internet Explorer 9.x.
+ * @type Boolean
+ */
+ isIE9 : isIE9,
+
+ /**
+ * True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox).
+ * @type Boolean
+ */
+ isGecko : isGecko,
+
+ /**
+ * True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x).
+ * @type Boolean
+ */
+ isGecko3 : isGecko3,
+
+ /**
+ * True if the detected browser uses a Gecko 2.0+ layout engine (e.g. Firefox 4.x).
+ * @type Boolean
+ */
+ isGecko4 : isGecko4,
+
+ /**
+ * True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x).
+ * @type Boolean
+ */
+ isGecko5 : isGecko5,
+
+ /**
+ * True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x).
+ * @type Boolean
+ */
+ isGecko10 : isGecko10,
+
+ /**
+ * True if the detected browser uses FireFox 3.0
+ * @type Boolean
+ */
+ isFF3_0 : isFF3_0,
+
+ /**
+ * True if the detected browser uses FireFox 3.5
+ * @type Boolean
+ */
+ isFF3_5 : isFF3_5,
+
+ /**
+ * True if the detected browser uses FireFox 3.6
+ * @type Boolean
+ */
+ isFF3_6 : isFF3_6,
+
+ /**
+ * True if the detected browser uses FireFox 4
+ * @type Boolean
+ */
+ isFF4 : 4 <= firefoxVersion && firefoxVersion < 5,
+
+ /**
+ * True if the detected browser uses FireFox 5
+ * @type Boolean
+ */
+ isFF5 : 5 <= firefoxVersion && firefoxVersion < 6,
+
+ /**
+ * True if the detected browser uses FireFox 10
+ * @type Boolean
+ */
+ isFF10 : 10 <= firefoxVersion && firefoxVersion < 11,
+
+ /**
+ * True if the detected platform is Linux.
+ * @type Boolean
+ */
+ isLinux : isLinux,
+
+ /**
+ * True if the detected platform is Windows.
+ * @type Boolean
+ */
+ isWindows : isWindows,
+
+ /**
+ * True if the detected platform is Mac OS.
+ * @type Boolean
+ */
+ isMac : isMac,
+
+ /**
+ * The current version of Chrome (0 if the browser is not Chrome).
+ * @type Number
+ */
+ chromeVersion: chromeVersion,
+
+ /**
+ * The current version of Firefox (0 if the browser is not Firefox).
+ * @type Number
+ */
+ firefoxVersion: firefoxVersion,
+
+ /**
+ * The current version of IE (0 if the browser is not IE). This does not account
+ * for the documentMode of the current page, which is factored into {@link #isIE7},
+ * {@link #isIE8} and {@link #isIE9}. Thus this is not always true:
+ *
+ * Ext.isIE8 == (Ext.ieVersion == 8)
+ *
+ * @type Number
+ */
+ ieVersion: ieVersion,
+
+ /**
+ * The current version of Opera (0 if the browser is not Opera).
+ * @type Number
+ */
+ operaVersion: operaVersion,
+
+ /**
+ * The current version of Safari (0 if the browser is not Safari).
+ * @type Number
+ */
+ safariVersion: safariVersion,
+
+ /**
+ * The current version of WebKit (0 if the browser does not use WebKit).
+ * @type Number
+ */
+ webKitVersion: webKitVersion,
+
+ /**
+ * True if the page is running over SSL
+ * @type Boolean
+ */
+ isSecure: isSecure,
+
+ /**
+ * URL to a 1x1 transparent gif image used by Ext to create inline icons with
+ * CSS background images. In older versions of IE, this defaults to
+ * "http://sencha.com/s.gif" and you should change this to a URL on your server.
+ * For other browsers it uses an inline data URL.
+ * @type String
+ */
+ BLANK_IMAGE_URL : (isIE6 || isIE7) ? '/' + '/www.sencha.com/s.gif' : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',
+
+ /**
+ * Utility method for returning a default value if the passed value is empty.
+ *
+ * The value is deemed to be empty if it is:
+ *
+ * - null
+ * - undefined
+ * - an empty array
+ * - a zero length string (Unless the `allowBlank` parameter is `true`)
+ *
+ * @param {Object} value The value to test
+ * @param {Object} defaultValue The value to return if the original value is empty
+ * @param {Boolean} [allowBlank=false] true to allow zero length strings to qualify as non-empty.
+ * @return {Object} value, if non-empty, else defaultValue
+ * @deprecated 4.0.0 Use {@link Ext#valueFrom} instead
+ */
+ value : function(v, defaultValue, allowBlank){
+ return Ext.isEmpty(v, allowBlank) ? defaultValue : v;
+ },
+
+ /**
+ * Escapes the passed string for use in a regular expression.
+ * @param {String} str
+ * @return {String}
+ * @deprecated 4.0.0 Use {@link Ext.String#escapeRegex} instead
+ */
+ escapeRe : function(s) {
+ return s.replace(/([-.*+?\^${}()|\[\]\/\\])/g, "\\$1");
+ },
+
+ /**
+ * Applies event listeners to elements by selectors when the document is ready.
+ * The event name is specified with an `@` suffix.
+ *
+ * Ext.addBehaviors({
+ * // add a listener for click on all anchors in element with id foo
+ * '#foo a@click' : function(e, t){
+ * // do something
+ * },
+ *
+ * // add the same listener to multiple selectors (separated by comma BEFORE the @)
+ * '#foo a, #bar span.some-class@mouseover' : function(){
+ * // do something
+ * }
+ * });
+ *
+ * @param {Object} obj The list of behaviors to apply
+ */
+ addBehaviors : function(o){
+ if(!Ext.isReady){
+ Ext.onReady(function(){
+ Ext.addBehaviors(o);
+ });
+ } else {
+ var cache = {}, // simple cache for applying multiple behaviors to same selector does query multiple times
+ parts,
+ b,
+ s;
+ for (b in o) {
+ if ((parts = b.split('@'))[1]) { // for Object prototype breakers
+ s = parts[0];
+ if(!cache[s]){
+ cache[s] = Ext.select(s);
+ }
+ cache[s].on(parts[1], o[b]);
+ }
+ }
+ cache = null;
+ }
+ },
+
+ /**
+ * Returns the size of the browser scrollbars. This can differ depending on
+ * operating system settings, such as the theme or font size.
+ * @param {Boolean} [force] true to force a recalculation of the value.
+ * @return {Object} An object containing scrollbar sizes.
+ * @return.width {Number} The width of the vertical scrollbar.
+ * @return.height {Number} The height of the horizontal scrollbar.
+ */
+ getScrollbarSize: function (force) {
+ if (!Ext.isReady) {
+ return {};
+ }
+
+ if (force || !scrollbarSize) {
+ var db = document.body,
+ div = document.createElement('div');
+
+ div.style.width = div.style.height = '100px';
+ div.style.overflow = 'scroll';
+ div.style.position = 'absolute';
+
+ db.appendChild(div); // now we can measure the div...
+
+ // at least in iE9 the div is not 100px - the scrollbar size is removed!
+ scrollbarSize = {
+ width: div.offsetWidth - div.clientWidth,
+ height: div.offsetHeight - div.clientHeight
+ };
+
+ db.removeChild(div);
+ }
+
+ return scrollbarSize;
+ },
+
+ /**
+ * Utility method for getting the width of the browser's vertical scrollbar. This
+ * can differ depending on operating system settings, such as the theme or font size.
+ *
+ * This method is deprected in favor of {@link #getScrollbarSize}.
+ *
+ * @param {Boolean} [force] true to force a recalculation of the value.
+ * @return {Number} The width of a vertical scrollbar.
+ * @deprecated
+ */
+ getScrollBarWidth: function(force){
+ var size = Ext.getScrollbarSize(force);
+ return size.width + 2; // legacy fudge factor
+ },
+
+ /**
+ * Copies a set of named properties fom the source object to the destination object.
+ *
+ * Example:
+ *
+ * ImageComponent = Ext.extend(Ext.Component, {
+ * initComponent: function() {
+ * this.autoEl = { tag: 'img' };
+ * MyComponent.superclass.initComponent.apply(this, arguments);
+ * this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height');
+ * }
+ * });
+ *
+ * Important note: To borrow class prototype methods, use {@link Ext.Base#borrow} instead.
+ *
+ * @param {Object} dest The destination object.
+ * @param {Object} source The source object.
+ * @param {String/String[]} names Either an Array of property names, or a comma-delimited list
+ * of property names to copy.
+ * @param {Boolean} [usePrototypeKeys] Defaults to false. Pass true to copy keys off of the
+ * prototype as well as the instance.
+ * @return {Object} The modified object.
+ */
+ copyTo : function(dest, source, names, usePrototypeKeys){
+ if(typeof names == 'string'){
+ names = names.split(/[,;\s]/);
+ }
+
+ var n,
+ nLen = names.length,
+ name;
+
+ for(n = 0; n < nLen; n++) {
+ name = names[n];
+
+ if(usePrototypeKeys || source.hasOwnProperty(name)){
+ dest[name] = source[name];
+ }
+ }
+
+ return dest;
+ },
+
+ /**
+ * Attempts to destroy and then remove a set of named properties of the passed object.
+ * @param {Object} o The object (most likely a Component) who's properties you wish to destroy.
+ * @param {String...} args One or more names of the properties to destroy and remove from the object.
+ */
+ destroyMembers : function(o){
+ for (var i = 1, a = arguments, len = a.length; i < len; i++) {
+ Ext.destroy(o[a[i]]);
+ delete o[a[i]];
+ }
+ },
+
+ /**
+ * Logs a message. If a console is present it will be used. On Opera, the method
+ * "opera.postError" is called. In other cases, the message is logged to an array
+ * "Ext.log.out". An attached debugger can watch this array and view the log. The
+ * log buffer is limited to a maximum of "Ext.log.max" entries (defaults to 250).
+ * The `Ext.log.out` array can also be written to a popup window by entering the
+ * following in the URL bar (a "bookmarklet"):
+ *
+ * javascript:void(Ext.log.show());
+ *
+ * If additional parameters are passed, they are joined and appended to the message.
+ * A technique for tracing entry and exit of a function is this:
+ *
+ * function foo () {
+ * Ext.log({ indent: 1 }, '>> foo');
+ *
+ * // log statements in here or methods called from here will be indented
+ * // by one step
+ *
+ * Ext.log({ outdent: 1 }, '<< foo');
+ * }
+ *
+ * This method does nothing in a release build.
+ *
+ * @param {String/Object} [options] The message to log or an options object with any
+ * of the following properties:
+ *
+ * - `msg`: The message to log (required).
+ * - `level`: One of: "error", "warn", "info" or "log" (the default is "log").
+ * - `dump`: An object to dump to the log as part of the message.
+ * - `stack`: True to include a stack trace in the log.
+ * - `indent`: Cause subsequent log statements to be indented one step.
+ * - `outdent`: Cause this and following statements to be one step less indented.
+ *
+ * @param {String...} [message] The message to log (required unless specified in
+ * options object).
+ *
+ * @method
+ */
+ log :
+ log ||
+ nullLog,
+
+ /**
+ * Partitions the set into two sets: a true set and a false set.
+ *
+ * Example 1:
+ *
+ * Ext.partition([true, false, true, true, false]);
+ * // returns [[true, true, true], [false, false]]
+ *
+ * Example 2:
+ *
+ * Ext.partition(
+ * Ext.query("p"),
+ * function(val){
+ * return val.className == "class1"
+ * }
+ * );
+ * // true are those paragraph elements with a className of "class1",
+ * // false set are those that do not have that className.
+ *
+ * @param {Array/NodeList} arr The array to partition
+ * @param {Function} truth (optional) a function to determine truth.
+ * If this is omitted the element itself must be able to be evaluated for its truthfulness.
+ * @return {Array} [array of truish values, array of falsy values]
+ * @deprecated 4.0.0 Will be removed in the next major version
+ */
+ partition : function(arr, truth){
+ var ret = [[],[]],
+ a, v,
+ aLen = arr.length;
+
+ for (a = 0; a < aLen; a++) {
+ v = arr[a];
+ ret[ (truth && truth(v, a, arr)) || (!truth && v) ? 0 : 1].push(v);
+ }
+
+ return ret;
+ },
+
+ /**
+ * Invokes a method on each item in an Array.
+ *
+ * Example:
+ *
+ * Ext.invoke(Ext.query("p"), "getAttribute", "id");
+ * // [el1.getAttribute("id"), el2.getAttribute("id"), ..., elN.getAttribute("id")]
+ *
+ * @param {Array/NodeList} arr The Array of items to invoke the method on.
+ * @param {String} methodName The method name to invoke.
+ * @param {Object...} args Arguments to send into the method invocation.
+ * @return {Array} The results of invoking the method on each item in the array.
+ * @deprecated 4.0.0 Will be removed in the next major version
+ */
+ invoke : function(arr, methodName){
+ var ret = [],
+ args = Array.prototype.slice.call(arguments, 2),
+ a, v,
+ aLen = arr.length;
+
+ for (a = 0; a < aLen; a++) {
+ v = arr[a];
+
+ if (v && typeof v[methodName] == 'function') {
+ ret.push(v[methodName].apply(v, args));
+ } else {
+ ret.push(undefined);
+ }
+ }
+
+ return ret;
+ },
+
+ /**
+ * Zips N sets together.
+ *
+ * Example 1:
+ *
+ * Ext.zip([1,2,3],[4,5,6]); // [[1,4],[2,5],[3,6]]
+ *
+ * Example 2:
+ *
+ * Ext.zip(
+ * [ "+", "-", "+"],
+ * [ 12, 10, 22],
+ * [ 43, 15, 96],
+ * function(a, b, c){
+ * return "$" + a + "" + b + "." + c
+ * }
+ * ); // ["$+12.43", "$-10.15", "$+22.96"]
+ *
+ * @param {Array/NodeList...} arr This argument may be repeated. Array(s)
+ * to contribute values.
+ * @param {Function} zipper (optional) The last item in the argument list.
+ * This will drive how the items are zipped together.
+ * @return {Array} The zipped set.
+ * @deprecated 4.0.0 Will be removed in the next major version
+ */
+ zip : function(){
+ var parts = Ext.partition(arguments, function( val ){ return typeof val != 'function'; }),
+ arrs = parts[0],
+ fn = parts[1][0],
+ len = Ext.max(Ext.pluck(arrs, "length")),
+ ret = [],
+ i,
+ j,
+ aLen;
+
+ for (i = 0; i < len; i++) {
+ ret[i] = [];
+ if(fn){
+ ret[i] = fn.apply(fn, Ext.pluck(arrs, i));
+ }else{
+ for (j = 0, aLen = arrs.length; j < aLen; j++){
+ ret[i].push( arrs[j][i] );
+ }
+ }
+ }
+ return ret;
+ },
+
+ /**
+ * Turns an array into a sentence, joined by a specified connector - e.g.:
+ *
+ * Ext.toSentence(['Adama', 'Tigh', 'Roslin']); //'Adama, Tigh and Roslin'
+ * Ext.toSentence(['Adama', 'Tigh', 'Roslin'], 'or'); //'Adama, Tigh or Roslin'
+ *
+ * @param {String[]} items The array to create a sentence from
+ * @param {String} connector The string to use to connect the last two words.
+ * Usually 'and' or 'or' - defaults to 'and'.
+ * @return {String} The sentence string
+ * @deprecated 4.0.0 Will be removed in the next major version
+ */
+ toSentence: function(items, connector) {
+ var length = items.length,
+ head,
+ tail;
+
+ if (length <= 1) {
+ return items[0];
+ } else {
+ head = items.slice(0, length - 1);
+ tail = items[length - 1];
+
+ return Ext.util.Format.format("{0} {1} {2}", head.join(", "), connector || 'and', tail);
+ }
+ },
+
+ /**
+ * @property {Boolean} useShims
+ * By default, Ext intelligently decides whether floating elements should be shimmed.
+ * If you are using flash, you may want to set this to true.
+ */
+ useShims: isIE6
+ });
+}());
+
+/**
+ * Loads Ext.app.Application class and starts it up with given configuration after the page is ready.
+ *
+ * See Ext.app.Application for details.
+ *
+ * @param {Object} config
+ */
+Ext.application = function(config) {
+ Ext.require('Ext.app.Application');
+
+ Ext.onReady(function() {
+ new Ext.app.Application(config);
+ });
+};
+
+//@tag extras,core
+//@require ../Ext-more.js
+//@define Ext.util.Format
+
+/**
+ * @class Ext.util.Format
+ *
+ * This class is a centralized place for formatting functions. It includes
+ * functions to format various different types of data, such as text, dates and numeric values.
+ *
+ * ## Localization
+ *
+ * This class contains several options for localization. These can be set once the library has loaded,
+ * all calls to the functions from that point will use the locale settings that were specified.
+ *
+ * Options include:
+ *
+ * - thousandSeparator
+ * - decimalSeparator
+ * - currenyPrecision
+ * - currencySign
+ * - currencyAtEnd
+ *
+ * This class also uses the default date format defined here: {@link Ext.Date#defaultFormat}.
+ *
+ * ## Using with renderers
+ *
+ * There are two helper functions that return a new function that can be used in conjunction with
+ * grid renderers:
+ *
+ * columns: [{
+ * dataIndex: 'date',
+ * renderer: Ext.util.Format.dateRenderer('Y-m-d')
+ * }, {
+ * dataIndex: 'time',
+ * renderer: Ext.util.Format.numberRenderer('0.000')
+ * }]
+ *
+ * Functions that only take a single argument can also be passed directly:
+ *
+ * columns: [{
+ * dataIndex: 'cost',
+ * renderer: Ext.util.Format.usMoney
+ * }, {
+ * dataIndex: 'productCode',
+ * renderer: Ext.util.Format.uppercase
+ * }]
+ *
+ * ## Using with XTemplates
+ *
+ * XTemplates can also directly use Ext.util.Format functions:
+ *
+ * new Ext.XTemplate([
+ * 'Date: {startDate:date("Y-m-d")}',
+ * 'Cost: {cost:usMoney}'
+ * ]);
+ *
+ * @singleton
+ */
+(function() {
+ Ext.ns('Ext.util');
+
+ Ext.util.Format = {};
+ var UtilFormat = Ext.util.Format,
+ stripTagsRE = /<\/?[^>]+>/gi,
+ stripScriptsRe = /(?:)((\n|\r|.)*?)(?:<\/script>)/ig,
+ nl2brRe = /\r?\n/g,
+
+ // A RegExp to remove from a number format string, all characters except digits and '.'
+ formatCleanRe = /[^\d\.]/g,
+
+ // A RegExp to remove from a number format string, all characters except digits and the local decimal separator.
+ // Created on first use. The local decimal separator character must be initialized for this to be created.
+ I18NFormatCleanRe;
+
+ Ext.apply(UtilFormat, {
+ //
+ /**
+ * @property {String} thousandSeparator
+ * The character that the {@link #number} function uses as a thousand separator.
+ *
+ * This may be overridden in a locale file.
+ */
+ thousandSeparator: ',',
+ //
+
+ //
+ /**
+ * @property {String} decimalSeparator
+ * The character that the {@link #number} function uses as a decimal point.
+ *
+ * This may be overridden in a locale file.
+ */
+ decimalSeparator: '.',
+ //
+
+ //
+ /**
+ * @property {Number} currencyPrecision
+ * The number of decimal places that the {@link #currency} function displays.
+ *
+ * This may be overridden in a locale file.
+ */
+ currencyPrecision: 2,
+ //
+
+ //
+ /**
+ * @property {String} currencySign
+ * The currency sign that the {@link #currency} function displays.
+ *
+ * This may be overridden in a locale file.
+ */
+ currencySign: '$',
+ //
+
+ //
+ /**
+ * @property {Boolean} currencyAtEnd
+ * This may be set to true to make the {@link #currency} function
+ * append the currency sign to the formatted value.
+ *
+ * This may be overridden in a locale file.
+ */
+ currencyAtEnd: false,
+ //
+
+ /**
+ * Checks a reference and converts it to empty string if it is undefined.
+ * @param {Object} value Reference to check
+ * @return {Object} Empty string if converted, otherwise the original value
+ */
+ undef : function(value) {
+ return value !== undefined ? value : "";
+ },
+
+ /**
+ * Checks a reference and converts it to the default value if it's empty.
+ * @param {Object} value Reference to check
+ * @param {String} [defaultValue=""] The value to insert of it's undefined.
+ * @return {String}
+ */
+ defaultValue : function(value, defaultValue) {
+ return value !== undefined && value !== '' ? value : defaultValue;
+ },
+
+ /**
+ * Returns a substring from within an original string.
+ * @param {String} value The original text
+ * @param {Number} start The start index of the substring
+ * @param {Number} length The length of the substring
+ * @return {String} The substring
+ * @method
+ */
+ substr : 'ab'.substr(-1) != 'b'
+ ? function (value, start, length) {
+ var str = String(value);
+ return (start < 0)
+ ? str.substr(Math.max(str.length + start, 0), length)
+ : str.substr(start, length);
+ }
+ : function(value, start, length) {
+ return String(value).substr(start, length);
+ },
+
+ /**
+ * Converts a string to all lower case letters.
+ * @param {String} value The text to convert
+ * @return {String} The converted text
+ */
+ lowercase : function(value) {
+ return String(value).toLowerCase();
+ },
+
+ /**
+ * Converts a string to all upper case letters.
+ * @param {String} value The text to convert
+ * @return {String} The converted text
+ */
+ uppercase : function(value) {
+ return String(value).toUpperCase();
+ },
+
+ /**
+ * Format a number as US currency.
+ * @param {Number/String} value The numeric value to format
+ * @return {String} The formatted currency string
+ */
+ usMoney : function(v) {
+ return UtilFormat.currency(v, '$', 2);
+ },
+
+ /**
+ * Format a number as a currency.
+ * @param {Number/String} value The numeric value to format
+ * @param {String} [sign] The currency sign to use (defaults to {@link #currencySign})
+ * @param {Number} [decimals] The number of decimals to use for the currency
+ * (defaults to {@link #currencyPrecision})
+ * @param {Boolean} [end] True if the currency sign should be at the end of the string
+ * (defaults to {@link #currencyAtEnd})
+ * @return {String} The formatted currency string
+ */
+ currency: function(v, currencySign, decimals, end) {
+ var negativeSign = '',
+ format = ",0",
+ i = 0;
+ v = v - 0;
+ if (v < 0) {
+ v = -v;
+ negativeSign = '-';
+ }
+ decimals = Ext.isDefined(decimals) ? decimals : UtilFormat.currencyPrecision;
+ format += format + (decimals > 0 ? '.' : '');
+ for (; i < decimals; i++) {
+ format += '0';
+ }
+ v = UtilFormat.number(v, format);
+ if ((end || UtilFormat.currencyAtEnd) === true) {
+ return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign);
+ } else {
+ return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v);
+ }
+ },
+
+ /**
+ * Formats the passed date using the specified format pattern.
+ * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date
+ * by the Javascript's built-in Date#parse method.
+ * @param {String} [format] Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
+ * @return {String} The formatted date string.
+ */
+ date: function(v, format) {
+ if (!v) {
+ return "";
+ }
+ if (!Ext.isDate(v)) {
+ v = new Date(Date.parse(v));
+ }
+ return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
+ },
+
+ /**
+ * Returns a date rendering function that can be reused to apply a date format multiple times efficiently.
+ * @param {String} format Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
+ * @return {Function} The date formatting function
+ */
+ dateRenderer : function(format) {
+ return function(v) {
+ return UtilFormat.date(v, format);
+ };
+ },
+
+ /**
+ * Strips all HTML tags.
+ * @param {Object} value The text from which to strip tags
+ * @return {String} The stripped text
+ */
+ stripTags : function(v) {
+ return !v ? v : String(v).replace(stripTagsRE, "");
+ },
+
+ /**
+ * Strips all script tags.
+ * @param {Object} value The text from which to strip script tags
+ * @return {String} The stripped text
+ */
+ stripScripts : function(v) {
+ return !v ? v : String(v).replace(stripScriptsRe, "");
+ },
+
+ /**
+ * Simple format for a file size (xxx bytes, xxx KB, xxx MB).
+ * @param {Number/String} size The numeric value to format
+ * @return {String} The formatted file size
+ */
+ fileSize : function(size) {
+ if (size < 1024) {
+ return size + " bytes";
+ } else if (size < 1048576) {
+ return (Math.round(((size*10) / 1024))/10) + " KB";
+ } else {
+ return (Math.round(((size*10) / 1048576))/10) + " MB";
+ }
+ },
+
+ /**
+ * It does simple math for use in a template, for example:
+ *
+ * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
+ *
+ * @return {Function} A function that operates on the passed value.
+ * @method
+ */
+ math : (function(){
+ var fns = {};
+
+ return function(v, a){
+ if (!fns[a]) {
+ fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
+ }
+ return fns[a](v);
+ };
+ }()),
+
+ /**
+ * Rounds the passed number to the required decimal precision.
+ * @param {Number/String} value The numeric value to round.
+ * @param {Number} precision The number of decimal places to which to round the first parameter's value.
+ * @return {Number} The rounded value.
+ */
+ round : function(value, precision) {
+ var result = Number(value);
+ if (typeof precision == 'number') {
+ precision = Math.pow(10, precision);
+ result = Math.round(value * precision) / precision;
+ }
+ return result;
+ },
+
+ /**
+ * Formats the passed number according to the passed format string.
+ *
+ * The number of digits after the decimal separator character specifies the number of
+ * decimal places in the resulting string. The *local-specific* decimal character is
+ * used in the result.
+ *
+ * The *presence* of a thousand separator character in the format string specifies that
+ * the *locale-specific* thousand separator (if any) is inserted separating thousand groups.
+ *
+ * By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.
+ *
+ * ## New to Ext JS 4
+ *
+ * Locale-specific characters are always used in the formatted output when inserting
+ * thousand and decimal separators.
+ *
+ * The format string must specify separator characters according to US/UK conventions ("," as the
+ * thousand separator, and "." as the decimal separator)
+ *
+ * To allow specification of format strings according to local conventions for separator characters, add
+ * the string `/i` to the end of the format string.
+ *
+ * examples (123456.789):
+ *
+ * - `0` - (123456) show only digits, no precision
+ * - `0.00` - (123456.78) show only digits, 2 precision
+ * - `0.0000` - (123456.7890) show only digits, 4 precision
+ * - `0,000` - (123,456) show comma and digits, no precision
+ * - `0,000.00` - (123,456.78) show comma and digits, 2 precision
+ * - `0,0.00` - (123,456.78) shortcut method, show comma and digits, 2 precision
+ *
+ * To allow specification of the formatting string using UK/US grouping characters (,) and
+ * decimal (.) for international numbers, add /i to the end. For example: 0.000,00/i
+ *
+ * @param {Number} v The number to format.
+ * @param {String} format The way you would like to format this text.
+ * @return {String} The formatted number.
+ */
+ number : function(v, formatString) {
+ if (!formatString) {
+ return v;
+ }
+ v = Ext.Number.from(v, NaN);
+ if (isNaN(v)) {
+ return '';
+ }
+ var comma = UtilFormat.thousandSeparator,
+ dec = UtilFormat.decimalSeparator,
+ i18n = false,
+ neg = v < 0,
+ hasComma,
+ psplit,
+ fnum,
+ cnum,
+ parr,
+ j,
+ m,
+ n,
+ i;
+
+ v = Math.abs(v);
+
+ // The "/i" suffix allows caller to use a locale-specific formatting string.
+ // Clean the format string by removing all but numerals and the decimal separator.
+ // Then split the format string into pre and post decimal segments according to *what* the
+ // decimal separator is. If they are specifying "/i", they are using the local convention in the format string.
+ if (formatString.substr(formatString.length - 2) == '/i') {
+ if (!I18NFormatCleanRe) {
+ I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g');
+ }
+ formatString = formatString.substr(0, formatString.length - 2);
+ i18n = true;
+ hasComma = formatString.indexOf(comma) != -1;
+ psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
+ } else {
+ hasComma = formatString.indexOf(',') != -1;
+ psplit = formatString.replace(formatCleanRe, '').split('.');
+ }
+
+ if (psplit.length > 2) {
+ Ext.Error.raise({
+ sourceClass: "Ext.util.Format",
+ sourceMethod: "number",
+ value: v,
+ formatString: formatString,
+ msg: "Invalid number format, should have no more than 1 decimal"
+ });
+ } else if (psplit.length > 1) {
+ v = Ext.Number.toFixed(v, psplit[1].length);
+ } else {
+ v = Ext.Number.toFixed(v, 0);
+ }
+
+ fnum = v.toString();
+
+ psplit = fnum.split('.');
+
+ if (hasComma) {
+ cnum = psplit[0];
+ parr = [];
+ j = cnum.length;
+ m = Math.floor(j / 3);
+ n = cnum.length % 3 || 3;
+
+ for (i = 0; i < j; i += n) {
+ if (i !== 0) {
+ n = 3;
+ }
+
+ parr[parr.length] = cnum.substr(i, n);
+ m -= 1;
+ }
+ fnum = parr.join(comma);
+ if (psplit[1]) {
+ fnum += dec + psplit[1];
+ }
+ } else {
+ if (psplit[1]) {
+ fnum = psplit[0] + dec + psplit[1];
+ }
+ }
+
+ if (neg) {
+ /*
+ * Edge case. If we have a very small negative number it will get rounded to 0,
+ * however the initial check at the top will still report as negative. Replace
+ * everything but 1-9 and check if the string is empty to determine a 0 value.
+ */
+ neg = fnum.replace(/[^1-9]/g, '') !== '';
+ }
+
+ return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
+ },
+
+ /**
+ * Returns a number rendering function that can be reused to apply a number format multiple
+ * times efficiently.
+ *
+ * @param {String} format Any valid number format string for {@link #number}
+ * @return {Function} The number formatting function
+ */
+ numberRenderer : function(format) {
+ return function(v) {
+ return UtilFormat.number(v, format);
+ };
+ },
+
+ /**
+ * Selectively do a plural form of a word based on a numeric value. For example, in a template,
+ * `{commentCount:plural("Comment")}` would result in `"1 Comment"` if commentCount was 1 or
+ * would be `"x Comments"` if the value is 0 or greater than 1.
+ *
+ * @param {Number} value The value to compare against
+ * @param {String} singular The singular form of the word
+ * @param {String} [plural] The plural form of the word (defaults to the singular with an "s")
+ */
+ plural : function(v, s, p) {
+ return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
+ },
+
+ /**
+ * Converts newline characters to the HTML tag ` `
+ *
+ * @param {String} The string value to format.
+ * @return {String} The string with embedded ` ` tags in place of newlines.
+ */
+ nl2br : function(v) {
+ return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, ' ');
+ },
+
+ /**
+ * Alias for {@link Ext.String#capitalize}.
+ * @method
+ * @inheritdoc Ext.String#capitalize
+ */
+ capitalize: Ext.String.capitalize,
+
+ /**
+ * Alias for {@link Ext.String#ellipsis}.
+ * @method
+ * @inheritdoc Ext.String#ellipsis
+ */
+ ellipsis: Ext.String.ellipsis,
+
+ /**
+ * Alias for {@link Ext.String#format}.
+ * @method
+ * @inheritdoc Ext.String#format
+ */
+ format: Ext.String.format,
+
+ /**
+ * Alias for {@link Ext.String#htmlDecode}.
+ * @method
+ * @inheritdoc Ext.String#htmlDecode
+ */
+ htmlDecode: Ext.String.htmlDecode,
+
+ /**
+ * Alias for {@link Ext.String#htmlEncode}.
+ * @method
+ * @inheritdoc Ext.String#htmlEncode
+ */
+ htmlEncode: Ext.String.htmlEncode,
+
+ /**
+ * Alias for {@link Ext.String#leftPad}.
+ * @method
+ * @inheritdoc Ext.String#leftPad
+ */
+ leftPad: Ext.String.leftPad,
+
+ /**
+ * Alias for {@link Ext.String#trim}.
+ * @method
+ * @inheritdoc Ext.String#trim
+ */
+ trim : Ext.String.trim,
+
+ /**
+ * Parses a number or string representing margin sizes into an object.
+ * Supports CSS-style margin declarations (e.g. 10, "10", "10 10", "10 10 10" and
+ * "10 10 10 10" are all valid options and would return the same result).
+ *
+ * @param {Number/String} v The encoded margins
+ * @return {Object} An object with margin sizes for top, right, bottom and left
+ */
+ parseBox : function(box) {
+ box = Ext.isEmpty(box) ? '' : box;
+ if (Ext.isNumber(box)) {
+ box = box.toString();
+ }
+ var parts = box.split(' '),
+ ln = parts.length;
+
+ if (ln == 1) {
+ parts[1] = parts[2] = parts[3] = parts[0];
+ }
+ else if (ln == 2) {
+ parts[2] = parts[0];
+ parts[3] = parts[1];
+ }
+ else if (ln == 3) {
+ parts[3] = parts[1];
+ }
+
+ return {
+ top :parseInt(parts[0], 10) || 0,
+ right :parseInt(parts[1], 10) || 0,
+ bottom:parseInt(parts[2], 10) || 0,
+ left :parseInt(parts[3], 10) || 0
+ };
+ },
+
+ /**
+ * Escapes the passed string for use in a regular expression.
+ * @param {String} str
+ * @return {String}
+ */
+ escapeRegex : function(s) {
+ return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1");
+ }
+ });
+}());
+
+//@tag extras,core
+//@require Format.js
+//@define Ext.util.TaskManager
+//@define Ext.TaskManager
+
+/**
+ * Provides the ability to execute one or more arbitrary tasks in a asynchronous manner.
+ * Generally, you can use the singleton {@link Ext.TaskManager} instead, but if needed,
+ * you can create separate instances of TaskRunner. Any number of separate tasks can be
+ * started at any time and will run independently of each other.
+ *
+ * Example usage:
+ *
+ * // Start a simple clock task that updates a div once per second
+ * var updateClock = function () {
+ * Ext.fly('clock').update(new Date().format('g:i:s A'));
+ * }
+ *
+ * var runner = new Ext.util.TaskRunner();
+ * var task = runner.start({
+ * run: updateClock,
+ * interval: 1000
+ * }
+ *
+ * The equivalent using TaskManager:
+ *
+ * var task = Ext.TaskManager.start({
+ * run: updateClock,
+ * interval: 1000
+ * });
+ *
+ * To end a running task:
+ *
+ * Ext.TaskManager.stop(task);
+ *
+ * If a task needs to be started and stopped repeated over time, you can create a
+ * {@link Ext.util.TaskRunner.Task Task} instance.
+ *
+ * var task = runner.newTask({
+ * run: function () {
+ * // useful code
+ * },
+ * interval: 1000
+ * });
+ *
+ * task.start();
+ *
+ * // ...
+ *
+ * task.stop();
+ *
+ * // ...
+ *
+ * task.start();
+ *
+ * A re-usable, one-shot task can be managed similar to the above:
+ *
+ * var task = runner.newTask({
+ * run: function () {
+ * // useful code to run once
+ * },
+ * repeat: 1
+ * });
+ *
+ * task.start();
+ *
+ * // ...
+ *
+ * task.start();
+ *
+ * See the {@link #start} method for details about how to configure a task object.
+ *
+ * Also see {@link Ext.util.DelayedTask}.
+ *
+ * @constructor
+ * @param {Number/Object} [interval=10] The minimum precision in milliseconds supported by this
+ * TaskRunner instance. Alternatively, a config object to apply to the new instance.
+ */
+Ext.define('Ext.util.TaskRunner', {
+ /**
+ * @cfg interval
+ * The timer resolution.
+ */
+ interval: 10,
+
+ /**
+ * @property timerId
+ * The id of the current timer.
+ * @private
+ */
+ timerId: null,
+
+ constructor: function (interval) {
+ var me = this;
+
+ if (typeof interval == 'number') {
+ me.interval = interval;
+ } else if (interval) {
+ Ext.apply(me, interval);
+ }
+
+ me.tasks = [];
+ me.timerFn = Ext.Function.bind(me.onTick, me);
+ },
+
+ /**
+ * Creates a new {@link Ext.util.TaskRunner.Task Task} instance. These instances can
+ * be easily started and stopped.
+ * @param {Object} config The config object. For details on the supported properties,
+ * see {@link #start}.
+ */
+ newTask: function (config) {
+ var task = new Ext.util.TaskRunner.Task(config);
+ task.manager = this;
+ return task;
+ },
+
+ /**
+ * Starts a new task.
+ *
+ * Before each invocation, Ext injects the property `taskRunCount` into the task object
+ * so that calculations based on the repeat count can be performed.
+ *
+ * The returned task will contain a `destroy` method that can be used to destroy the
+ * task and cancel further calls. This is equivalent to the {@link #stop} method.
+ *
+ * @param {Object} task A config object that supports the following properties:
+ * @param {Function} task.run The function to execute each time the task is invoked. The
+ * function will be called at each interval and passed the `args` argument if specified,
+ * and the current invocation count if not.
+ *
+ * If a particular scope (`this` reference) is required, be sure to specify it using
+ * the `scope` argument.
+ *
+ * @param {Function} task.onError The function to execute in case of unhandled
+ * error on task.run.
+ *
+ * @param {Boolean} task.run.return `false` from this function to terminate the task.
+ *
+ * @param {Number} task.interval The frequency in milliseconds with which the task
+ * should be invoked.
+ *
+ * @param {Object[]} task.args An array of arguments to be passed to the function
+ * specified by `run`. If not specified, the current invocation count is passed.
+ *
+ * @param {Object} task.scope The scope (`this` reference) in which to execute the
+ * `run` function. Defaults to the task config object.
+ *
+ * @param {Number} task.duration The length of time in milliseconds to invoke the task
+ * before stopping automatically (defaults to indefinite).
+ *
+ * @param {Number} task.repeat The number of times to invoke the task before stopping
+ * automatically (defaults to indefinite).
+ * @return {Object} The task
+ */
+ start: function(task) {
+ var me = this,
+ now = new Date().getTime();
+
+ if (!task.pending) {
+ me.tasks.push(task);
+ task.pending = true; // don't allow the task to be added to me.tasks again
+ }
+
+ task.stopped = false; // might have been previously stopped...
+ task.taskStartTime = now;
+ task.taskRunTime = task.fireOnStart !== false ? 0 : task.taskStartTime;
+ task.taskRunCount = 0;
+
+ if (!me.firing) {
+ if (task.fireOnStart !== false) {
+ me.startTimer(0, now);
+ } else {
+ me.startTimer(task.interval, now);
+ }
+ }
+
+ return task;
+ },
+
+ /**
+ * Stops an existing running task.
+ * @param {Object} task The task to stop
+ * @return {Object} The task
+ */
+ stop: function(task) {
+ // NOTE: we don't attempt to remove the task from me.tasks at this point because
+ // this could be called from inside a task which would then corrupt the state of
+ // the loop in onTick
+ if (!task.stopped) {
+ task.stopped = true;
+
+ if (task.onStop) {
+ task.onStop.call(task.scope || task, task);
+ }
+ }
+
+ return task;
+ },
+
+ /**
+ * Stops all tasks that are currently running.
+ */
+ stopAll: function() {
+ // onTick will take care of cleaning up the mess after this point...
+ Ext.each(this.tasks, this.stop, this);
+ },
+
+ //-------------------------------------------------------------------------
+
+ firing: false,
+
+ nextExpires: 1e99,
+
+ // private
+ onTick: function () {
+ var me = this,
+ tasks = me.tasks,
+ now = new Date().getTime(),
+ nextExpires = 1e99,
+ len = tasks.length,
+ expires, newTasks, i, task, rt, remove;
+
+ me.timerId = null;
+ me.firing = true; // ensure we don't startTimer during this loop...
+
+ // tasks.length can be > len if start is called during a task.run call... so we
+ // first check len to avoid tasks.length reference but eventually we need to also
+ // check tasks.length. we avoid repeating use of tasks.length by setting len at
+ // that time (to help the next loop)
+ for (i = 0; i < len || i < (len = tasks.length); ++i) {
+ task = tasks[i];
+
+ if (!(remove = task.stopped)) {
+ expires = task.taskRunTime + task.interval;
+
+ if (expires <= now) {
+ rt = 1; // otherwise we have a stale "rt"
+ try {
+ rt = task.run.apply(task.scope || task, task.args || [++task.taskRunCount]);
+ } catch (taskError) {
+ try {
+ if (task.onError) {
+ rt = task.onError.call(task.scope || task, task, taskError);
+ }
+ } catch (ignore) { }
+ }
+ task.taskRunTime = now;
+ if (rt === false || task.taskRunCount === task.repeat) {
+ me.stop(task);
+ remove = true;
+ } else {
+ remove = task.stopped; // in case stop was called by run
+ expires = now + task.interval;
+ }
+ }
+
+ if (!remove && task.duration && task.duration <= (now - task.taskStartTime)) {
+ me.stop(task);
+ remove = true;
+ }
+ }
+
+ if (remove) {
+ task.pending = false; // allow the task to be added to me.tasks again
+
+ // once we detect that a task needs to be removed, we copy the tasks that
+ // will carry forward into newTasks... this way we avoid O(N*N) to remove
+ // each task from the tasks array (and ripple the array down) and also the
+ // potentially wasted effort of making a new tasks[] even if all tasks are
+ // going into the next wave.
+ if (!newTasks) {
+ newTasks = tasks.slice(0, i);
+ // we don't set me.tasks here because callbacks can also start tasks,
+ // which get added to me.tasks... so we will visit them in this loop
+ // and account for their expirations in nextExpires...
+ }
+ } else {
+ if (newTasks) {
+ newTasks.push(task); // we've cloned the tasks[], so keep this one...
+ }
+
+ if (nextExpires > expires) {
+ nextExpires = expires; // track the nearest expiration time
+ }
+ }
+ }
+
+ if (newTasks) {
+ // only now can we copy the newTasks to me.tasks since no user callbacks can
+ // take place
+ me.tasks = newTasks;
+ }
+
+ me.firing = false; // we're done, so allow startTimer afterwards
+
+ if (me.tasks.length) {
+ // we create a new Date here because all the callbacks could have taken a long
+ // time... we want to base the next timeout on the current time (after the
+ // callback storm):
+ me.startTimer(nextExpires - now, new Date().getTime());
+ }
+ },
+
+ // private
+ startTimer: function (timeout, now) {
+ var me = this,
+ expires = now + timeout,
+ timerId = me.timerId;
+
+ // Check to see if this request is enough in advance of the current timer. If so,
+ // we reschedule the timer based on this new expiration.
+ if (timerId && me.nextExpires - expires > me.interval) {
+ clearTimeout(timerId);
+ timerId = null;
+ }
+
+ if (!timerId) {
+ if (timeout < me.interval) {
+ timeout = me.interval;
+ }
+
+ me.timerId = setTimeout(me.timerFn, timeout);
+ me.nextExpires = expires;
+ }
+ }
+},
+function () {
+ var me = this,
+ proto = me.prototype;
+
+ /**
+ * Destroys this instance, stopping all tasks that are currently running.
+ * @method destroy
+ */
+ proto.destroy = proto.stopAll;
+
+ /**
+ * @class Ext.TaskManager
+ * @extends Ext.util.TaskRunner
+ * @singleton
+ *
+ * A static {@link Ext.util.TaskRunner} instance that can be used to start and stop
+ * arbitrary tasks. See {@link Ext.util.TaskRunner} for supported methods and task
+ * config properties.
+ *
+ * // Start a simple clock task that updates a div once per second
+ * var task = {
+ * run: function(){
+ * Ext.fly('clock').update(new Date().format('g:i:s A'));
+ * },
+ * interval: 1000 //1 second
+ * }
+ *
+ * Ext.TaskManager.start(task);
+ *
+ * See the {@link #start} method for details about how to configure a task object.
+ */
+ Ext.util.TaskManager = Ext.TaskManager = new me();
+
+ /**
+ * Instances of this class are created by {@link Ext.util.TaskRunner#newTask} method.
+ *
+ * For details on config properties, see {@link Ext.util.TaskRunner#start}.
+ * @class Ext.util.TaskRunner.Task
+ */
+ me.Task = new Ext.Class({
+ isTask: true,
+
+ /**
+ * This flag is set to `true` by {@link #stop}.
+ * @private
+ */
+ stopped: true, // this avoids the odd combination of !stopped && !pending
+
+ /**
+ * Override default behavior
+ */
+ fireOnStart: false,
+
+ constructor: function (config) {
+ Ext.apply(this, config);
+ },
+
+ /**
+ * Restarts this task, clearing it duration, expiration and run count.
+ * @param {Number} [interval] Optionally reset this task's interval.
+ */
+ restart: function (interval) {
+ if (interval !== undefined) {
+ this.interval = interval;
+ }
+
+ this.manager.start(this);
+ },
+
+ /**
+ * Starts this task if it is not already started.
+ * @param {Number} [interval] Optionally reset this task's interval.
+ */
+ start: function (interval) {
+ if (this.stopped) {
+ this.restart(interval);
+ }
+ },
+
+ /**
+ * Stops this task.
+ */
+ stop: function () {
+ this.manager.stop(this);
+ }
+ });
+
+ proto = me.Task.prototype;
+
+ /**
+ * Destroys this instance, stopping this task's execution.
+ * @method destroy
+ */
+ proto.destroy = proto.stop;
+});
+
+//@tag extras,core
+//@require ../util/TaskManager.js
+
+/**
+ * @class Ext.perf.Accumulator
+ * @private
+ */
+Ext.define('Ext.perf.Accumulator', (function () {
+ var currentFrame = null,
+ khrome = Ext.global['chrome'],
+ formatTpl,
+ // lazy init on first request for timestamp (avoids infobar in IE until needed)
+ // Also avoids kicking off Chrome's microsecond timer until first needed
+ getTimestamp = function () {
+
+ getTimestamp = function () {
+ return new Date().getTime();
+ };
+
+ var interval, toolbox;
+
+ // If Chrome is started with the --enable-benchmarking switch
+ if (Ext.isChrome && khrome && khrome.Interval) {
+ interval = new khrome.Interval();
+ interval.start();
+ getTimestamp = function () {
+ return interval.microseconds() / 1000;
+ };
+ } else if (window.ActiveXObject) {
+ try {
+ // the above technique is not very accurate for small intervals...
+ toolbox = new ActiveXObject('SenchaToolbox.Toolbox');
+ Ext.senchaToolbox = toolbox; // export for other uses
+ getTimestamp = function () {
+ return toolbox.milliseconds;
+ };
+ } catch (e) {
+ // ignore
+ }
+ } else if (Date.now) {
+ getTimestamp = Date.now;
+ }
+
+ Ext.perf.getTimestamp = Ext.perf.Accumulator.getTimestamp = getTimestamp;
+ return getTimestamp();
+ };
+
+ function adjustSet (set, time) {
+ set.sum += time;
+ set.min = Math.min(set.min, time);
+ set.max = Math.max(set.max, time);
+ }
+
+ function leaveFrame (time) {
+ var totalTime = time ? time : (getTimestamp() - this.time), // do this first
+ me = this, // me = frame
+ accum = me.accum;
+
+ ++accum.count;
+ if (! --accum.depth) {
+ adjustSet(accum.total, totalTime);
+ }
+ adjustSet(accum.pure, totalTime - me.childTime);
+
+ currentFrame = me.parent;
+ if (currentFrame) {
+ ++currentFrame.accum.childCount;
+ currentFrame.childTime += totalTime;
+ }
+ }
+
+ function makeSet () {
+ return {
+ min: Number.MAX_VALUE,
+ max: 0,
+ sum: 0
+ };
+ }
+
+ function makeTap (me, fn) {
+ return function () {
+ var frame = me.enter(),
+ ret = fn.apply(this, arguments);
+
+ frame.leave();
+ return ret;
+ };
+ }
+
+ function round (x) {
+ return Math.round(x * 100) / 100;
+ }
+
+ function setToJSON (count, childCount, calibration, set) {
+ var data = {
+ avg: 0,
+ min: set.min,
+ max: set.max,
+ sum: 0
+ };
+
+ if (count) {
+ calibration = calibration || 0;
+ data.sum = set.sum - childCount * calibration;
+ data.avg = data.sum / count;
+ // min and max cannot be easily corrected since we don't know the number of
+ // child calls for them.
+ }
+
+ return data;
+ }
+
+ return {
+ constructor: function (name) {
+ var me = this;
+
+ me.count = me.childCount = me.depth = me.maxDepth = 0;
+ me.pure = makeSet();
+ me.total = makeSet();
+ me.name = name;
+ },
+
+ statics: {
+ getTimestamp: getTimestamp
+ },
+
+ format: function (calibration) {
+ if (!formatTpl) {
+ formatTpl = new Ext.XTemplate([
+ '{name} - {count} call(s)',
+ '',
+ '',
+ ' ({childCount} children)',
+ ' ',
+ '',
+ ' ({depth} deep)',
+ ' ',
+ '',
+ ', {type}: {[this.time(values.sum)]} msec (',
+ //'min={[this.time(values.min)]}, ',
+ 'avg={[this.time(values.sum / parent.count)]}',
+ //', max={[this.time(values.max)]}',
+ ')',
+ ' ',
+ ' '
+ ].join(''), {
+ time: function (t) {
+ return Math.round(t * 100) / 100;
+ }
+ });
+ }
+
+ var data = this.getData(calibration);
+ data.name = this.name;
+ data.pure.type = 'Pure';
+ data.total.type = 'Total';
+ data.times = [data.pure, data.total];
+ return formatTpl.apply(data);
+ },
+
+ getData: function (calibration) {
+ var me = this;
+
+ return {
+ count: me.count,
+ childCount: me.childCount,
+ depth: me.maxDepth,
+ pure: setToJSON(me.count, me.childCount, calibration, me.pure),
+ total: setToJSON(me.count, me.childCount, calibration, me.total)
+ };
+ },
+
+ enter: function () {
+ var me = this,
+ frame = {
+ accum: me,
+ leave: leaveFrame,
+ childTime: 0,
+ parent: currentFrame
+ };
+
+ ++me.depth;
+ if (me.maxDepth < me.depth) {
+ me.maxDepth = me.depth;
+ }
+
+ currentFrame = frame;
+ frame.time = getTimestamp(); // do this last
+ return frame;
+ },
+
+ monitor: function (fn, scope, args) {
+ var frame = this.enter();
+ if (args) {
+ fn.apply(scope, args);
+ } else {
+ fn.call(scope);
+ }
+ frame.leave();
+ },
+
+ report: function () {
+ Ext.log(this.format());
+ },
+
+ tap: function (className, methodName) {
+ var me = this,
+ methods = typeof methodName == 'string' ? [methodName] : methodName,
+ klass, statik, i, parts, length, name, src,
+ tapFunc;
+
+ tapFunc = function(){
+ if (typeof className == 'string') {
+ klass = Ext.global;
+ parts = className.split('.');
+ for (i = 0, length = parts.length; i < length; ++i) {
+ klass = klass[parts[i]];
+ }
+ } else {
+ klass = className;
+ }
+
+ for (i = 0, length = methods.length; i < length; ++i) {
+ name = methods[i];
+ statik = name.charAt(0) == '!';
+
+ if (statik) {
+ name = name.substring(1);
+ } else {
+ statik = !(name in klass.prototype);
+ }
+
+ src = statik ? klass : klass.prototype;
+ src[name] = makeTap(me, src[name]);
+ }
+ };
+
+ Ext.ClassManager.onCreated(tapFunc, me, className);
+
+ return me;
+ }
+ };
+}()),
+
+function () {
+ Ext.perf.getTimestamp = this.getTimestamp;
+});
+
+//@tag extras,core
+//@require Accumulator.js
+
+/**
+ * @class Ext.perf.Monitor
+ * @singleton
+ * @private
+ */
+Ext.define('Ext.perf.Monitor', {
+ singleton: true,
+ alternateClassName: 'Ext.Perf',
+
+ requires: [
+ 'Ext.perf.Accumulator'
+ ],
+
+ constructor: function () {
+ this.accumulators = [];
+ this.accumulatorsByName = {};
+ },
+
+ calibrate: function () {
+ var accum = new Ext.perf.Accumulator('$'),
+ total = accum.total,
+ getTimestamp = Ext.perf.Accumulator.getTimestamp,
+ count = 0,
+ frame,
+ endTime,
+ startTime;
+
+ startTime = getTimestamp();
+
+ do {
+ frame = accum.enter();
+ frame.leave();
+ ++count;
+ } while (total.sum < 100);
+
+ endTime = getTimestamp();
+
+ return (endTime - startTime) / count;
+ },
+
+ get: function (name) {
+ var me = this,
+ accum = me.accumulatorsByName[name];
+
+ if (!accum) {
+ me.accumulatorsByName[name] = accum = new Ext.perf.Accumulator(name);
+ me.accumulators.push(accum);
+ }
+
+ return accum;
+ },
+
+ enter: function (name) {
+ return this.get(name).enter();
+ },
+
+ monitor: function (name, fn, scope) {
+ this.get(name).monitor(fn, scope);
+ },
+
+ report: function () {
+ var me = this,
+ accumulators = me.accumulators,
+ calibration = me.calibrate();
+
+ accumulators.sort(function (a, b) {
+ return (a.name < b.name) ? -1 : ((b.name < a.name) ? 1 : 0);
+ });
+
+ me.updateGC();
+
+ Ext.log('Calibration: ' + Math.round(calibration * 100) / 100 + ' msec/sample');
+ Ext.each(accumulators, function (accum) {
+ Ext.log(accum.format(calibration));
+ });
+ },
+
+ getData: function (all) {
+ var ret = {},
+ accumulators = this.accumulators;
+
+ Ext.each(accumulators, function (accum) {
+ if (all || accum.count) {
+ ret[accum.name] = accum.getData();
+ }
+ });
+
+ return ret;
+ },
+
+ reset: function(){
+ Ext.each(this.accumulators, function(accum){
+ var me = accum;
+ me.count = me.childCount = me.depth = me.maxDepth = 0;
+ me.pure = {
+ min: Number.MAX_VALUE,
+ max: 0,
+ sum: 0
+ };
+ me.total = {
+ min: Number.MAX_VALUE,
+ max: 0,
+ sum: 0
+ };
+ });
+ },
+
+ updateGC: function () {
+ var accumGC = this.accumulatorsByName.GC,
+ toolbox = Ext.senchaToolbox,
+ bucket;
+
+ if (accumGC) {
+ accumGC.count = toolbox.garbageCollectionCounter || 0;
+
+ if (accumGC.count) {
+ bucket = accumGC.pure;
+ accumGC.total.sum = bucket.sum = toolbox.garbageCollectionMilliseconds;
+ bucket.min = bucket.max = bucket.sum / accumGC.count;
+ bucket = accumGC.total;
+ bucket.min = bucket.max = bucket.sum / accumGC.count;
+ }
+ }
+ },
+
+ watchGC: function () {
+ Ext.perf.getTimestamp(); // initializes SenchaToolbox (if available)
+
+ var toolbox = Ext.senchaToolbox;
+
+ if (toolbox) {
+ this.get("GC");
+ toolbox.watchGarbageCollector(false); // no logging, just totals
+ }
+ },
+
+ setup: function (config) {
+ if (!config) {
+ config = {
+ /*insertHtml: {
+ 'Ext.dom.Helper': 'insertHtml'
+ },*/
+ /*xtplCompile: {
+ 'Ext.XTemplateCompiler': 'compile'
+ },*/
+// doInsert: {
+// 'Ext.Template': 'doInsert'
+// },
+// applyOut: {
+// 'Ext.XTemplate': 'applyOut'
+// },
+ render: {
+ 'Ext.AbstractComponent': 'render'
+ },
+// fnishRender: {
+// 'Ext.AbstractComponent': 'finishRender'
+// },
+// renderSelectors: {
+// 'Ext.AbstractComponent': 'applyRenderSelectors'
+// },
+// compAddCls: {
+// 'Ext.AbstractComponent': 'addCls'
+// },
+// compRemoveCls: {
+// 'Ext.AbstractComponent': 'removeCls'
+// },
+// getStyle: {
+// 'Ext.core.Element': 'getStyle'
+// },
+// setStyle: {
+// 'Ext.core.Element': 'setStyle'
+// },
+// addCls: {
+// 'Ext.core.Element': 'addCls'
+// },
+// removeCls: {
+// 'Ext.core.Element': 'removeCls'
+// },
+// measure: {
+// 'Ext.layout.component.Component': 'measureAutoDimensions'
+// },
+// moveItem: {
+// 'Ext.layout.Layout': 'moveItem'
+// },
+// layoutFlush: {
+// 'Ext.layout.Context': 'flush'
+// },
+ layout: {
+ 'Ext.layout.Context': 'run'
+ }
+ };
+ }
+
+ this.currentConfig = config;
+
+ var key, prop,
+ accum, className, methods;
+ for (key in config) {
+ if (config.hasOwnProperty(key)) {
+ prop = config[key];
+ accum = Ext.Perf.get(key);
+
+ for (className in prop) {
+ if (prop.hasOwnProperty(className)) {
+ methods = prop[className];
+ accum.tap(className, methods);
+ }
+ }
+ }
+ }
+
+ this.watchGC();
+ }
+});
+
+//@tag extras,core
+//@require perf/Monitor.js
+//@define Ext.Supports
+
+/**
+ * @class Ext.is
+ *
+ * Determines information about the current platform the application is running on.
+ *
+ * @singleton
+ */
+Ext.is = {
+ init : function(navigator) {
+ var platforms = this.platforms,
+ ln = platforms.length,
+ i, platform;
+
+ navigator = navigator || window.navigator;
+
+ for (i = 0; i < ln; i++) {
+ platform = platforms[i];
+ this[platform.identity] = platform.regex.test(navigator[platform.property]);
+ }
+
+ /**
+ * @property Desktop True if the browser is running on a desktop machine
+ * @type {Boolean}
+ */
+ this.Desktop = this.Mac || this.Windows || (this.Linux && !this.Android);
+ /**
+ * @property Tablet True if the browser is running on a tablet (iPad)
+ */
+ this.Tablet = this.iPad;
+ /**
+ * @property Phone True if the browser is running on a phone.
+ * @type {Boolean}
+ */
+ this.Phone = !this.Desktop && !this.Tablet;
+ /**
+ * @property iOS True if the browser is running on iOS
+ * @type {Boolean}
+ */
+ this.iOS = this.iPhone || this.iPad || this.iPod;
+
+ /**
+ * @property Standalone Detects when application has been saved to homescreen.
+ * @type {Boolean}
+ */
+ this.Standalone = !!window.navigator.standalone;
+ },
+
+ /**
+ * @property iPhone True when the browser is running on a iPhone
+ * @type {Boolean}
+ */
+ platforms: [{
+ property: 'platform',
+ regex: /iPhone/i,
+ identity: 'iPhone'
+ },
+
+ /**
+ * @property iPod True when the browser is running on a iPod
+ * @type {Boolean}
+ */
+ {
+ property: 'platform',
+ regex: /iPod/i,
+ identity: 'iPod'
+ },
+
+ /**
+ * @property iPad True when the browser is running on a iPad
+ * @type {Boolean}
+ */
+ {
+ property: 'userAgent',
+ regex: /iPad/i,
+ identity: 'iPad'
+ },
+
+ /**
+ * @property Blackberry True when the browser is running on a Blackberry
+ * @type {Boolean}
+ */
+ {
+ property: 'userAgent',
+ regex: /Blackberry/i,
+ identity: 'Blackberry'
+ },
+
+ /**
+ * @property Android True when the browser is running on an Android device
+ * @type {Boolean}
+ */
+ {
+ property: 'userAgent',
+ regex: /Android/i,
+ identity: 'Android'
+ },
+
+ /**
+ * @property Mac True when the browser is running on a Mac
+ * @type {Boolean}
+ */
+ {
+ property: 'platform',
+ regex: /Mac/i,
+ identity: 'Mac'
+ },
+
+ /**
+ * @property Windows True when the browser is running on Windows
+ * @type {Boolean}
+ */
+ {
+ property: 'platform',
+ regex: /Win/i,
+ identity: 'Windows'
+ },
+
+ /**
+ * @property Linux True when the browser is running on Linux
+ * @type {Boolean}
+ */
+ {
+ property: 'platform',
+ regex: /Linux/i,
+ identity: 'Linux'
+ }]
+};
+
+Ext.is.init();
+
+/**
+ * @class Ext.supports
+ *
+ * Determines information about features are supported in the current environment
+ *
+ * @singleton
+ */
+(function(){
+
+ // this is a local copy of certain logic from (Abstract)Element.getStyle
+ // to break a dependancy between the supports mechanism and Element
+ // use this instead of element references to check for styling info
+ var getStyle = function(element, styleName){
+ var view = element.ownerDocument.defaultView,
+ style = (view ? view.getComputedStyle(element, null) : element.currentStyle) || element.style;
+ return style[styleName];
+ };
+
+Ext.supports = {
+ /**
+ * Runs feature detection routines and sets the various flags. This is called when
+ * the scripts loads (very early) and again at {@link Ext#onReady}. Some detections
+ * are flagged as `early` and run immediately. Others that require the document body
+ * will not run until ready.
+ *
+ * Each test is run only once, so calling this method from an onReady function is safe
+ * and ensures that all flags have been set.
+ * @markdown
+ * @private
+ */
+ init : function() {
+ var me = this,
+ doc = document,
+ tests = me.tests,
+ n = tests.length,
+ div = n && Ext.isReady && doc.createElement('div'),
+ test, notRun = [];
+
+ if (div) {
+ div.innerHTML = [
+ '',
+ '',
+ '
',
+ '
'
+ ].join('');
+
+ doc.body.appendChild(div);
+ }
+
+ while (n--) {
+ test = tests[n];
+ if (div || test.early) {
+ me[test.identity] = test.fn.call(me, doc, div);
+ } else {
+ notRun.push(test);
+ }
+ }
+
+ if (div) {
+ doc.body.removeChild(div);
+ }
+
+ me.tests = notRun;
+ },
+
+ /**
+ * @property PointerEvents True if document environment supports the CSS3 pointer-events style.
+ * @type {Boolean}
+ */
+ PointerEvents: 'pointerEvents' in document.documentElement.style,
+
+ /**
+ * @property CSS3BoxShadow True if document environment supports the CSS3 box-shadow style.
+ * @type {Boolean}
+ */
+ CSS3BoxShadow: 'boxShadow' in document.documentElement.style || 'WebkitBoxShadow' in document.documentElement.style || 'MozBoxShadow' in document.documentElement.style,
+
+ /**
+ * @property ClassList True if document environment supports the HTML5 classList API.
+ * @type {Boolean}
+ */
+ ClassList: !!document.documentElement.classList,
+
+ /**
+ * @property OrientationChange True if the device supports orientation change
+ * @type {Boolean}
+ */
+ OrientationChange: ((typeof window.orientation != 'undefined') && ('onorientationchange' in window)),
+
+ /**
+ * @property DeviceMotion True if the device supports device motion (acceleration and rotation rate)
+ * @type {Boolean}
+ */
+ DeviceMotion: ('ondevicemotion' in window),
+
+ /**
+ * @property Touch True if the device supports touch
+ * @type {Boolean}
+ */
+ // is.Desktop is needed due to the bug in Chrome 5.0.375, Safari 3.1.2
+ // and Safari 4.0 (they all have 'ontouchstart' in the window object).
+ Touch: ('ontouchstart' in window) && (!Ext.is.Desktop),
+
+ /**
+ * @property TimeoutActualLateness True if the browser passes the "actualLateness" parameter to
+ * setTimeout. See: https://developer.mozilla.org/en/DOM/window.setTimeout
+ * @type {Boolean}
+ */
+ TimeoutActualLateness: (function(){
+ setTimeout(function(){
+ Ext.supports.TimeoutActualLateness = arguments.length !== 0;
+ }, 0);
+ }()),
+
+ tests: [
+ /**
+ * @property Transitions True if the device supports CSS3 Transitions
+ * @type {Boolean}
+ */
+ {
+ identity: 'Transitions',
+ fn: function(doc, div) {
+ var prefix = [
+ 'webkit',
+ 'Moz',
+ 'o',
+ 'ms',
+ 'khtml'
+ ],
+ TE = 'TransitionEnd',
+ transitionEndName = [
+ prefix[0] + TE,
+ 'transitionend', //Moz bucks the prefixing convention
+ prefix[2] + TE,
+ prefix[3] + TE,
+ prefix[4] + TE
+ ],
+ ln = prefix.length,
+ i = 0,
+ out = false;
+
+ for (; i < ln; i++) {
+ if (getStyle(div, prefix[i] + "TransitionProperty")) {
+ Ext.supports.CSS3Prefix = prefix[i];
+ Ext.supports.CSS3TransitionEnd = transitionEndName[i];
+ out = true;
+ break;
+ }
+ }
+ return out;
+ }
+ },
+
+ /**
+ * @property RightMargin True if the device supports right margin.
+ * See https://bugs.webkit.org/show_bug.cgi?id=13343 for why this is needed.
+ * @type {Boolean}
+ */
+ {
+ identity: 'RightMargin',
+ fn: function(doc, div) {
+ var view = doc.defaultView;
+ return !(view && view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px');
+ }
+ },
+
+ /**
+ * @property DisplayChangeInputSelectionBug True if INPUT elements lose their
+ * selection when their display style is changed. Essentially, if a text input
+ * has focus and its display style is changed, the I-beam disappears.
+ *
+ * This bug is encountered due to the work around in place for the {@link #RightMargin}
+ * bug. This has been observed in Safari 4.0.4 and older, and appears to be fixed
+ * in Safari 5. It's not clear if Safari 4.1 has the bug, but it has the same WebKit
+ * version number as Safari 5 (according to http://unixpapa.com/js/gecko.html).
+ */
+ {
+ identity: 'DisplayChangeInputSelectionBug',
+ early: true,
+ fn: function() {
+ var webKitVersion = Ext.webKitVersion;
+ // WebKit but older than Safari 5 or Chrome 6:
+ return 0 < webKitVersion && webKitVersion < 533;
+ }
+ },
+
+ /**
+ * @property DisplayChangeTextAreaSelectionBug True if TEXTAREA elements lose their
+ * selection when their display style is changed. Essentially, if a text area has
+ * focus and its display style is changed, the I-beam disappears.
+ *
+ * This bug is encountered due to the work around in place for the {@link #RightMargin}
+ * bug. This has been observed in Chrome 10 and Safari 5 and older, and appears to
+ * be fixed in Chrome 11.
+ */
+ {
+ identity: 'DisplayChangeTextAreaSelectionBug',
+ early: true,
+ fn: function() {
+ var webKitVersion = Ext.webKitVersion;
+
+ /*
+ Has bug w/textarea:
+
+ (Chrome) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US)
+ AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.127
+ Safari/534.16
+ (Safari) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-us)
+ AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5
+ Safari/533.21.1
+
+ No bug:
+
+ (Chrome) Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7)
+ AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.57
+ Safari/534.24
+ */
+ return 0 < webKitVersion && webKitVersion < 534.24;
+ }
+ },
+
+ /**
+ * @property TransparentColor True if the device supports transparent color
+ * @type {Boolean}
+ */
+ {
+ identity: 'TransparentColor',
+ fn: function(doc, div, view) {
+ view = doc.defaultView;
+ return !(view && view.getComputedStyle(div.lastChild, null).backgroundColor != 'transparent');
+ }
+ },
+
+ /**
+ * @property ComputedStyle True if the browser supports document.defaultView.getComputedStyle()
+ * @type {Boolean}
+ */
+ {
+ identity: 'ComputedStyle',
+ fn: function(doc, div, view) {
+ view = doc.defaultView;
+ return view && view.getComputedStyle;
+ }
+ },
+
+ /**
+ * @property Svg True if the device supports SVG
+ * @type {Boolean}
+ */
+ {
+ identity: 'Svg',
+ fn: function(doc) {
+ return !!doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect;
+ }
+ },
+
+ /**
+ * @property Canvas True if the device supports Canvas
+ * @type {Boolean}
+ */
+ {
+ identity: 'Canvas',
+ fn: function(doc) {
+ return !!doc.createElement('canvas').getContext;
+ }
+ },
+
+ /**
+ * @property Vml True if the device supports VML
+ * @type {Boolean}
+ */
+ {
+ identity: 'Vml',
+ fn: function(doc) {
+ var d = doc.createElement("div");
+ d.innerHTML = "";
+ return (d.childNodes.length == 2);
+ }
+ },
+
+ /**
+ * @property Float True if the device supports CSS float
+ * @type {Boolean}
+ */
+ {
+ identity: 'Float',
+ fn: function(doc, div) {
+ return !!div.lastChild.style.cssFloat;
+ }
+ },
+
+ /**
+ * @property AudioTag True if the device supports the HTML5 audio tag
+ * @type {Boolean}
+ */
+ {
+ identity: 'AudioTag',
+ fn: function(doc) {
+ return !!doc.createElement('audio').canPlayType;
+ }
+ },
+
+ /**
+ * @property History True if the device supports HTML5 history
+ * @type {Boolean}
+ */
+ {
+ identity: 'History',
+ fn: function() {
+ var history = window.history;
+ return !!(history && history.pushState);
+ }
+ },
+
+ /**
+ * @property CSS3DTransform True if the device supports CSS3DTransform
+ * @type {Boolean}
+ */
+ {
+ identity: 'CSS3DTransform',
+ fn: function() {
+ return (typeof WebKitCSSMatrix != 'undefined' && new WebKitCSSMatrix().hasOwnProperty('m41'));
+ }
+ },
+
+ /**
+ * @property CSS3LinearGradient True if the device supports CSS3 linear gradients
+ * @type {Boolean}
+ */
+ {
+ identity: 'CSS3LinearGradient',
+ fn: function(doc, div) {
+ var property = 'background-image:',
+ webkit = '-webkit-gradient(linear, left top, right bottom, from(black), to(white))',
+ w3c = 'linear-gradient(left top, black, white)',
+ moz = '-moz-' + w3c,
+ opera = '-o-' + w3c,
+ options = [property + webkit, property + w3c, property + moz, property + opera];
+
+ div.style.cssText = options.join(';');
+
+ return ("" + div.style.backgroundImage).indexOf('gradient') !== -1;
+ }
+ },
+
+ /**
+ * @property CSS3BorderRadius True if the device supports CSS3 border radius
+ * @type {Boolean}
+ */
+ {
+ identity: 'CSS3BorderRadius',
+ fn: function(doc, div) {
+ var domPrefixes = ['borderRadius', 'BorderRadius', 'MozBorderRadius', 'WebkitBorderRadius', 'OBorderRadius', 'KhtmlBorderRadius'],
+ pass = false,
+ i;
+ for (i = 0; i < domPrefixes.length; i++) {
+ if (document.body.style[domPrefixes[i]] !== undefined) {
+ return true;
+ }
+ }
+ return pass;
+ }
+ },
+
+ /**
+ * @property GeoLocation True if the device supports GeoLocation
+ * @type {Boolean}
+ */
+ {
+ identity: 'GeoLocation',
+ fn: function() {
+ return (typeof navigator != 'undefined' && typeof navigator.geolocation != 'undefined') || (typeof google != 'undefined' && typeof google.gears != 'undefined');
+ }
+ },
+ /**
+ * @property MouseEnterLeave True if the browser supports mouseenter and mouseleave events
+ * @type {Boolean}
+ */
+ {
+ identity: 'MouseEnterLeave',
+ fn: function(doc, div){
+ return ('onmouseenter' in div && 'onmouseleave' in div);
+ }
+ },
+ /**
+ * @property MouseWheel True if the browser supports the mousewheel event
+ * @type {Boolean}
+ */
+ {
+ identity: 'MouseWheel',
+ fn: function(doc, div) {
+ return ('onmousewheel' in div);
+ }
+ },
+ /**
+ * @property Opacity True if the browser supports normal css opacity
+ * @type {Boolean}
+ */
+ {
+ identity: 'Opacity',
+ fn: function(doc, div){
+ // Not a strict equal comparison in case opacity can be converted to a number.
+ if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
+ return false;
+ }
+ div.firstChild.style.cssText = 'opacity:0.73';
+ return div.firstChild.style.opacity == '0.73';
+ }
+ },
+ /**
+ * @property Placeholder True if the browser supports the HTML5 placeholder attribute on inputs
+ * @type {Boolean}
+ */
+ {
+ identity: 'Placeholder',
+ fn: function(doc) {
+ return 'placeholder' in doc.createElement('input');
+ }
+ },
+
+ /**
+ * @property Direct2DBug True if when asking for an element's dimension via offsetWidth or offsetHeight,
+ * getBoundingClientRect, etc. the browser returns the subpixel width rounded to the nearest pixel.
+ * @type {Boolean}
+ */
+ {
+ identity: 'Direct2DBug',
+ fn: function() {
+ return Ext.isString(document.body.style.msTransformOrigin);
+ }
+ },
+ /**
+ * @property BoundingClientRect True if the browser supports the getBoundingClientRect method on elements
+ * @type {Boolean}
+ */
+ {
+ identity: 'BoundingClientRect',
+ fn: function(doc, div) {
+ return Ext.isFunction(div.getBoundingClientRect);
+ }
+ },
+ {
+ identity: 'IncludePaddingInWidthCalculation',
+ fn: function(doc, div){
+ return div.childNodes[1].firstChild.offsetWidth == 210;
+ }
+ },
+ {
+ identity: 'IncludePaddingInHeightCalculation',
+ fn: function(doc, div){
+ return div.childNodes[1].firstChild.offsetHeight == 210;
+ }
+ },
+
+ /**
+ * @property ArraySort True if the Array sort native method isn't bugged.
+ * @type {Boolean}
+ */
+ {
+ identity: 'ArraySort',
+ fn: function() {
+ var a = [1,2,3,4,5].sort(function(){ return 0; });
+ return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
+ }
+ },
+ /**
+ * @property Range True if browser support document.createRange native method.
+ * @type {Boolean}
+ */
+ {
+ identity: 'Range',
+ fn: function() {
+ return !!document.createRange;
+ }
+ },
+ /**
+ * @property CreateContextualFragment True if browser support CreateContextualFragment range native methods.
+ * @type {Boolean}
+ */
+ {
+ identity: 'CreateContextualFragment',
+ fn: function() {
+ var range = Ext.supports.Range ? document.createRange() : false;
+
+ return range && !!range.createContextualFragment;
+ }
+ },
+
+ /**
+ * @property WindowOnError True if browser supports window.onerror.
+ * @type {Boolean}
+ */
+ {
+ identity: 'WindowOnError',
+ fn: function () {
+ // sadly, we cannot feature detect this...
+ return Ext.isIE || Ext.isGecko || Ext.webKitVersion >= 534.16; // Chrome 10+
+ }
+ },
+
+ /**
+ * @property TextAreaMaxLength True if the browser supports maxlength on textareas.
+ * @type {Boolean}
+ */
+ {
+ identity: 'TextAreaMaxLength',
+ fn: function(){
+ var el = document.createElement('textarea');
+ return ('maxlength' in el);
+ }
+ },
+ /**
+ * @property GetPositionPercentage True if the browser will return the left/top/right/bottom
+ * position as a percentage when explicitly set as a percentage value.
+ * @type {Boolean}
+ */
+ // Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=707691#c7
+ {
+ identity: 'GetPositionPercentage',
+ fn: function(doc, div){
+ return getStyle(div.childNodes[2], 'left') == '10%';
+ }
+ }
+ ]
+};
+}());
+
+Ext.supports.init(); // run the "early" detections now
+
+//@tag dom,core
+//@require ../Support.js
+//@define Ext.util.DelayedTask
+
+/**
+ * @class Ext.util.DelayedTask
+ *
+ * The DelayedTask class provides a convenient way to "buffer" the execution of a method,
+ * performing setTimeout where a new timeout cancels the old timeout. When called, the
+ * task will wait the specified time period before executing. If durng that time period,
+ * the task is called again, the original call will be cancelled. This continues so that
+ * the function is only called a single time for each iteration.
+ *
+ * This method is especially useful for things like detecting whether a user has finished
+ * typing in a text field. An example would be performing validation on a keypress. You can
+ * use this class to buffer the keypress events for a certain number of milliseconds, and
+ * perform only if they stop for that amount of time.
+ *
+ * ## Usage
+ *
+ * var task = new Ext.util.DelayedTask(function(){
+ * alert(Ext.getDom('myInputField').value.length);
+ * });
+ *
+ * // Wait 500ms before calling our function. If the user presses another key
+ * // during that 500ms, it will be cancelled and we'll wait another 500ms.
+ * Ext.get('myInputField').on('keypress', function(){
+ * task.{@link #delay}(500);
+ * });
+ *
+ * Note that we are using a DelayedTask here to illustrate a point. The configuration
+ * option `buffer` for {@link Ext.util.Observable#addListener addListener/on} will
+ * also setup a delayed task for you to buffer events.
+ *
+ * @constructor The parameters to this constructor serve as defaults and are not required.
+ * @param {Function} fn (optional) The default function to call. If not specified here, it must be specified during the {@link #delay} call.
+ * @param {Object} scope (optional) The default scope (The this reference) in which the
+ * function is called. If not specified, this will refer to the browser window.
+ * @param {Array} args (optional) The default Array of arguments.
+ */
+Ext.util.DelayedTask = function(fn, scope, args) {
+ var me = this,
+ id,
+ call = function() {
+ clearInterval(id);
+ id = null;
+ fn.apply(scope, args || []);
+ };
+
+ /**
+ * Cancels any pending timeout and queues a new one
+ * @param {Number} delay The milliseconds to delay
+ * @param {Function} newFn (optional) Overrides function passed to constructor
+ * @param {Object} newScope (optional) Overrides scope passed to constructor. Remember that if no scope
+ * is specified, this will refer to the browser window.
+ * @param {Array} newArgs (optional) Overrides args passed to constructor
+ */
+ this.delay = function(delay, newFn, newScope, newArgs) {
+ me.cancel();
+ fn = newFn || fn;
+ scope = newScope || scope;
+ args = newArgs || args;
+ id = setInterval(call, delay);
+ };
+
+ /**
+ * Cancel the last queued timeout
+ */
+ this.cancel = function(){
+ if (id) {
+ clearInterval(id);
+ id = null;
+ }
+ };
+};
+
+//@tag dom,core
+//@define Ext.util.Event
+//@require Ext.util.DelayedTask
+
+Ext.require('Ext.util.DelayedTask', function() {
+
+ /**
+ * Represents single event type that an Observable object listens to.
+ * All actual listeners are tracked inside here. When the event fires,
+ * it calls all the registered listener functions.
+ *
+ * @private
+ */
+ Ext.util.Event = Ext.extend(Object, (function() {
+ var noOptions = {};
+
+ function createTargeted(handler, listener, o, scope){
+ return function(){
+ if (o.target === arguments[0]){
+ handler.apply(scope, arguments);
+ }
+ };
+ }
+
+ function createBuffered(handler, listener, o, scope) {
+ listener.task = new Ext.util.DelayedTask();
+ return function() {
+ listener.task.delay(o.buffer, handler, scope, Ext.Array.toArray(arguments));
+ };
+ }
+
+ function createDelayed(handler, listener, o, scope) {
+ return function() {
+ var task = new Ext.util.DelayedTask();
+ if (!listener.tasks) {
+ listener.tasks = [];
+ }
+ listener.tasks.push(task);
+ task.delay(o.delay || 10, handler, scope, Ext.Array.toArray(arguments));
+ };
+ }
+
+ function createSingle(handler, listener, o, scope) {
+ return function() {
+ var event = listener.ev;
+
+ if (event.removeListener(listener.fn, scope) && event.observable) {
+ // Removing from a regular Observable-owned, named event (not an anonymous
+ // event such as Ext's readyEvent): Decrement the listeners count
+ event.observable.hasListeners[event.name]--;
+ }
+
+ return handler.apply(scope, arguments);
+ };
+ }
+
+ return {
+ /**
+ * @property {Boolean} isEvent
+ * `true` in this class to identify an object as an instantiated Event, or subclass thereof.
+ */
+ isEvent: true,
+
+ constructor: function(observable, name) {
+ this.name = name;
+ this.observable = observable;
+ this.listeners = [];
+ },
+
+ addListener: function(fn, scope, options) {
+ var me = this,
+ listener;
+ scope = scope || me.observable;
+
+ if (!fn) {
+ Ext.Error.raise({
+ sourceClass: Ext.getClassName(this.observable),
+ sourceMethod: "addListener",
+ msg: "The specified callback function is undefined"
+ });
+ }
+
+ if (!me.isListening(fn, scope)) {
+ listener = me.createListener(fn, scope, options);
+ if (me.firing) {
+ // if we are currently firing this event, don't disturb the listener loop
+ me.listeners = me.listeners.slice(0);
+ }
+ me.listeners.push(listener);
+ }
+ },
+
+ createListener: function(fn, scope, options) {
+ options = options || noOptions;
+ scope = scope || this.observable;
+
+ var listener = {
+ fn: fn,
+ scope: scope,
+ o: options,
+ ev: this
+ },
+ handler = fn;
+
+ // The order is important. The 'single' wrapper must be wrapped by the 'buffer' and 'delayed' wrapper
+ // because the event removal that the single listener does destroys the listener's DelayedTask(s)
+ if (options.single) {
+ handler = createSingle(handler, listener, options, scope);
+ }
+ if (options.target) {
+ handler = createTargeted(handler, listener, options, scope);
+ }
+ if (options.delay) {
+ handler = createDelayed(handler, listener, options, scope);
+ }
+ if (options.buffer) {
+ handler = createBuffered(handler, listener, options, scope);
+ }
+
+ listener.fireFn = handler;
+ return listener;
+ },
+
+ findListener: function(fn, scope) {
+ var listeners = this.listeners,
+ i = listeners.length,
+ listener,
+ s;
+
+ while (i--) {
+ listener = listeners[i];
+ if (listener) {
+ s = listener.scope;
+
+ // Compare the listener's scope with *JUST THE PASSED SCOPE* if one is passed, and only fall back to the owning Observable if none is passed.
+ // We cannot use the test (s == scope || s == this.observable)
+ // Otherwise, if the Observable itself adds Ext.emptyFn as a listener, and then Ext.emptyFn is added under another scope, there will be a false match.
+ if (listener.fn == fn && (s == (scope || this.observable))) {
+ return i;
+ }
+ }
+ }
+
+ return - 1;
+ },
+
+ isListening: function(fn, scope) {
+ return this.findListener(fn, scope) !== -1;
+ },
+
+ removeListener: function(fn, scope) {
+ var me = this,
+ index,
+ listener,
+ k;
+ index = me.findListener(fn, scope);
+ if (index != -1) {
+ listener = me.listeners[index];
+
+ if (me.firing) {
+ me.listeners = me.listeners.slice(0);
+ }
+
+ // cancel and remove a buffered handler that hasn't fired yet
+ if (listener.task) {
+ listener.task.cancel();
+ delete listener.task;
+ }
+
+ // cancel and remove all delayed handlers that haven't fired yet
+ k = listener.tasks && listener.tasks.length;
+ if (k) {
+ while (k--) {
+ listener.tasks[k].cancel();
+ }
+ delete listener.tasks;
+ }
+
+ // remove this listener from the listeners array
+ Ext.Array.erase(me.listeners, index, 1);
+ return true;
+ }
+
+ return false;
+ },
+
+ // Iterate to stop any buffered/delayed events
+ clearListeners: function() {
+ var listeners = this.listeners,
+ i = listeners.length;
+
+ while (i--) {
+ this.removeListener(listeners[i].fn, listeners[i].scope);
+ }
+ },
+
+ fire: function() {
+ var me = this,
+ listeners = me.listeners,
+ count = listeners.length,
+ i,
+ args,
+ listener;
+
+ if (count > 0) {
+ me.firing = true;
+ for (i = 0; i < count; i++) {
+ listener = listeners[i];
+ args = arguments.length ? Array.prototype.slice.call(arguments, 0) : [];
+ if (listener.o) {
+ args.push(listener.o);
+ }
+ if (listener && listener.fireFn.apply(listener.scope || me.observable, args) === false) {
+ return (me.firing = false);
+ }
+ }
+ }
+ me.firing = false;
+ return true;
+ }
+ };
+ }()));
+});
+
+/**
+ * Base class that provides a common interface for publishing events. Subclasses are expected to to have a property
+ * "events" with all the events defined, and, optionally, a property "listeners" with configured listeners defined.
+ *
+ * For example:
+ *
+ * Ext.define('Employee', {
+ * mixins: {
+ * observable: 'Ext.util.Observable'
+ * },
+ *
+ * constructor: function (config) {
+ * // The Observable constructor copies all of the properties of `config` on
+ * // to `this` using {@link Ext#apply}. Further, the `listeners` property is
+ * // processed to add listeners.
+ * //
+ * this.mixins.observable.constructor.call(this, config);
+ *
+ * this.addEvents(
+ * 'fired',
+ * 'quit'
+ * );
+ * }
+ * });
+ *
+ * This could then be used like this:
+ *
+ * var newEmployee = new Employee({
+ * name: employeeName,
+ * listeners: {
+ * quit: function() {
+ * // By default, "this" will be the object that fired the event.
+ * alert(this.name + " has quit!");
+ * }
+ * }
+ * });
+ */
+Ext.define('Ext.util.Observable', {
+
+ /* Begin Definitions */
+
+ requires: ['Ext.util.Event'],
+
+ statics: {
+ /**
+ * Removes **all** added captures from the Observable.
+ *
+ * @param {Ext.util.Observable} o The Observable to release
+ * @static
+ */
+ releaseCapture: function(o) {
+ o.fireEvent = this.prototype.fireEvent;
+ },
+
+ /**
+ * Starts capture on the specified Observable. All events will be passed to the supplied function with the event
+ * name + standard signature of the event **before** the event is fired. If the supplied function returns false,
+ * the event will not fire.
+ *
+ * @param {Ext.util.Observable} o The Observable to capture events from.
+ * @param {Function} fn The function to call when an event is fired.
+ * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. Defaults to
+ * the Observable firing the event.
+ * @static
+ */
+ capture: function(o, fn, scope) {
+ o.fireEvent = Ext.Function.createInterceptor(o.fireEvent, fn, scope);
+ },
+
+ /**
+ * Sets observability on the passed class constructor.
+ *
+ * This makes any event fired on any instance of the passed class also fire a single event through
+ * the **class** allowing for central handling of events on many instances at once.
+ *
+ * Usage:
+ *
+ * Ext.util.Observable.observe(Ext.data.Connection);
+ * Ext.data.Connection.on('beforerequest', function(con, options) {
+ * console.log('Ajax request made to ' + options.url);
+ * });
+ *
+ * @param {Function} c The class constructor to make observable.
+ * @param {Object} listeners An object containing a series of listeners to add. See {@link #addListener}.
+ * @static
+ */
+ observe: function(cls, listeners) {
+ if (cls) {
+ if (!cls.isObservable) {
+ Ext.applyIf(cls, new this());
+ this.capture(cls.prototype, cls.fireEvent, cls);
+ }
+ if (Ext.isObject(listeners)) {
+ cls.on(listeners);
+ }
+ }
+ return cls;
+ },
+
+ /**
+ * Prepares a given class for observable instances. This method is called when a
+ * class derives from this class or uses this class as a mixin.
+ * @param {Function} T The class constructor to prepare.
+ * @private
+ */
+ prepareClass: function (T, mixin) {
+ // T.hasListeners is the object to track listeners on class T. This object's
+ // prototype (__proto__) is the "hasListeners" of T.superclass.
+
+ // Instances of T will create "hasListeners" that have T.hasListeners as their
+ // immediate prototype (__proto__).
+
+ if (!T.HasListeners) {
+ // We create a HasListeners "class" for this class. The "prototype" of the
+ // HasListeners class is an instance of the HasListeners class associated
+ // with this class's super class (or with Observable).
+ var Observable = Ext.util.Observable,
+ HasListeners = function () {},
+ SuperHL = T.superclass.HasListeners || (mixin && mixin.HasListeners) ||
+ Observable.HasListeners;
+
+ // Make the HasListener class available on the class and its prototype:
+ T.prototype.HasListeners = T.HasListeners = HasListeners;
+
+ // And connect its "prototype" to the new HasListeners of our super class
+ // (which is also the class-level "hasListeners" instance).
+ HasListeners.prototype = T.hasListeners = new SuperHL();
+ }
+ }
+ },
+
+ /* End Definitions */
+
+ /**
+ * @cfg {Object} listeners
+ *
+ * A config object containing one or more event handlers to be added to this object during initialization. This
+ * should be a valid listeners config object as specified in the {@link #addListener} example for attaching multiple
+ * handlers at once.
+ *
+ * **DOM events from Ext JS {@link Ext.Component Components}**
+ *
+ * While _some_ Ext JS Component classes export selected DOM events (e.g. "click", "mouseover" etc), this is usually
+ * only done when extra value can be added. For example the {@link Ext.view.View DataView}'s **`{@link
+ * Ext.view.View#itemclick itemclick}`** event passing the node clicked on. To access DOM events directly from a
+ * child element of a Component, we need to specify the `element` option to identify the Component property to add a
+ * DOM listener to:
+ *
+ * new Ext.panel.Panel({
+ * width: 400,
+ * height: 200,
+ * dockedItems: [{
+ * xtype: 'toolbar'
+ * }],
+ * listeners: {
+ * click: {
+ * element: 'el', //bind to the underlying el property on the panel
+ * fn: function(){ console.log('click el'); }
+ * },
+ * dblclick: {
+ * element: 'body', //bind to the underlying body property on the panel
+ * fn: function(){ console.log('dblclick body'); }
+ * }
+ * }
+ * });
+ */
+
+ /**
+ * @property {Boolean} isObservable
+ * `true` in this class to identify an object as an instantiated Observable, or subclass thereof.
+ */
+ isObservable: true,
+
+ /**
+ * @private
+ * Initial suspended call count. Incremented when {@link #suspendEvents} is called, decremented when {@link #resumeEvents} is called.
+ */
+ eventsSuspended: 0,
+
+ /**
+ * @property {Object} hasListeners
+ * @readonly
+ * This object holds a key for any event that has a listener. The listener may be set
+ * directly on the instance, or on its class or a super class (via {@link #observe}) or
+ * on the {@link Ext.app.EventBus MVC EventBus}. The values of this object are truthy
+ * (a non-zero number) and falsy (0 or undefined). They do not represent an exact count
+ * of listeners. The value for an event is truthy if the event must be fired and is
+ * falsy if there is no need to fire the event.
+ *
+ * The intended use of this property is to avoid the expense of fireEvent calls when
+ * there are no listeners. This can be particularly helpful when one would otherwise
+ * have to call fireEvent hundreds or thousands of times. It is used like this:
+ *
+ * if (this.hasListeners.foo) {
+ * this.fireEvent('foo', this, arg1);
+ * }
+ */
+
+ constructor: function(config) {
+ var me = this;
+
+ Ext.apply(me, config);
+
+ // The subclass may have already initialized it.
+ if (!me.hasListeners) {
+ me.hasListeners = new me.HasListeners();
+ }
+
+ me.events = me.events || {};
+ if (me.listeners) {
+ me.on(me.listeners);
+ me.listeners = null; //Set as an instance property to pre-empt the prototype in case any are set there.
+ }
+
+ if (me.bubbleEvents) {
+ me.enableBubble(me.bubbleEvents);
+ }
+ },
+
+ onClassExtended: function (T) {
+ if (!T.HasListeners) {
+ // Some classes derive from us and some others derive from those classes. All
+ // of these are passed to this method.
+ Ext.util.Observable.prepareClass(T);
+ }
+ },
+
+ // @private
+ eventOptionsRe : /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|element|vertical|horizontal|freezeEvent)$/,
+
+ /**
+ * Adds listeners to any Observable object (or Ext.Element) which are automatically removed when this Component is
+ * destroyed.
+ *
+ * @param {Ext.util.Observable/Ext.Element} item The item to which to add a listener/listeners.
+ * @param {Object/String} ename The event name, or an object containing event name properties.
+ * @param {Function} fn (optional) If the `ename` parameter was an event name, this is the handler function.
+ * @param {Object} scope (optional) If the `ename` parameter was an event name, this is the scope (`this` reference)
+ * in which the handler function is executed.
+ * @param {Object} opt (optional) If the `ename` parameter was an event name, this is the
+ * {@link Ext.util.Observable#addListener addListener} options.
+ */
+ addManagedListener : function(item, ename, fn, scope, options) {
+ var me = this,
+ managedListeners = me.managedListeners = me.managedListeners || [],
+ config;
+
+ if (typeof ename !== 'string') {
+ options = ename;
+ for (ename in options) {
+ if (options.hasOwnProperty(ename)) {
+ config = options[ename];
+ if (!me.eventOptionsRe.test(ename)) {
+ me.addManagedListener(item, ename, config.fn || config, config.scope || options.scope, config.fn ? config : options);
+ }
+ }
+ }
+ }
+ else {
+ managedListeners.push({
+ item: item,
+ ename: ename,
+ fn: fn,
+ scope: scope,
+ options: options
+ });
+
+ item.on(ename, fn, scope, options);
+ }
+ },
+
+ /**
+ * Removes listeners that were added by the {@link #mon} method.
+ *
+ * @param {Ext.util.Observable/Ext.Element} item The item from which to remove a listener/listeners.
+ * @param {Object/String} ename The event name, or an object containing event name properties.
+ * @param {Function} fn (optional) If the `ename` parameter was an event name, this is the handler function.
+ * @param {Object} scope (optional) If the `ename` parameter was an event name, this is the scope (`this` reference)
+ * in which the handler function is executed.
+ */
+ removeManagedListener : function(item, ename, fn, scope) {
+ var me = this,
+ options,
+ config,
+ managedListeners,
+ length,
+ i;
+
+ if (typeof ename !== 'string') {
+ options = ename;
+ for (ename in options) {
+ if (options.hasOwnProperty(ename)) {
+ config = options[ename];
+ if (!me.eventOptionsRe.test(ename)) {
+ me.removeManagedListener(item, ename, config.fn || config, config.scope || options.scope);
+ }
+ }
+ }
+ }
+
+ managedListeners = me.managedListeners ? me.managedListeners.slice() : [];
+
+ for (i = 0, length = managedListeners.length; i < length; i++) {
+ me.removeManagedListenerItem(false, managedListeners[i], item, ename, fn, scope);
+ }
+ },
+
+ /**
+ * Fires the specified event with the passed parameters (minus the event name, plus the `options` object passed
+ * to {@link #addListener}).
+ *
+ * An event may be set to bubble up an Observable parent hierarchy (See {@link Ext.Component#getBubbleTarget}) by
+ * calling {@link #enableBubble}.
+ *
+ * @param {String} eventName The name of the event to fire.
+ * @param {Object...} args Variable number of parameters are passed to handlers.
+ * @return {Boolean} returns false if any of the handlers return false otherwise it returns true.
+ */
+ fireEvent: function(eventName) {
+ eventName = eventName.toLowerCase();
+ var me = this,
+ events = me.events,
+ event = events && events[eventName],
+ ret = true;
+
+ // Only continue firing the event if there are listeners to be informed.
+ // Bubbled events will always have a listener count, so will be fired.
+ if (event && me.hasListeners[eventName]) {
+ ret = me.continueFireEvent(eventName, Ext.Array.slice(arguments, 1), event.bubble);
+ }
+ return ret;
+ },
+
+ /**
+ * Continue to fire event.
+ * @private
+ *
+ * @param {String} eventName
+ * @param {Array} args
+ * @param {Boolean} bubbles
+ */
+ continueFireEvent: function(eventName, args, bubbles) {
+ var target = this,
+ queue, event,
+ ret = true;
+
+ do {
+ if (target.eventsSuspended) {
+ if ((queue = target.eventQueue)) {
+ queue.push([eventName, args, bubbles]);
+ }
+ return ret;
+ } else {
+ event = target.events[eventName];
+ // Continue bubbling if event exists and it is `true` or the handler didn't returns false and it
+ // configure to bubble.
+ if (event && event != true) {
+ if ((ret = event.fire.apply(event, args)) === false) {
+ break;
+ }
+ }
+ }
+ } while (bubbles && (target = target.getBubbleParent()));
+ return ret;
+ },
+
+ /**
+ * Gets the bubbling parent for an Observable
+ * @private
+ * @return {Ext.util.Observable} The bubble parent. null is returned if no bubble target exists
+ */
+ getBubbleParent: function(){
+ var me = this, parent = me.getBubbleTarget && me.getBubbleTarget();
+ if (parent && parent.isObservable) {
+ return parent;
+ }
+ return null;
+ },
+
+ /**
+ * Appends an event handler to this object. For example:
+ *
+ * myGridPanel.on("mouseover", this.onMouseOver, this);
+ *
+ * The method also allows for a single argument to be passed which is a config object
+ * containing properties which specify multiple events. For example:
+ *
+ * myGridPanel.on({
+ * cellClick: this.onCellClick,
+ * mouseover: this.onMouseOver,
+ * mouseout: this.onMouseOut,
+ * scope: this // Important. Ensure "this" is correct during handler execution
+ * });
+ *
+ * One can also specify options for each event handler separately:
+ *
+ * myGridPanel.on({
+ * cellClick: {fn: this.onCellClick, scope: this, single: true},
+ * mouseover: {fn: panel.onMouseOver, scope: panel}
+ * });
+ *
+ * *Names* of methods in a specified scope may also be used. Note that
+ * `scope` MUST be specified to use this option:
+ *
+ * myGridPanel.on({
+ * cellClick: {fn: 'onCellClick', scope: this, single: true},
+ * mouseover: {fn: 'onMouseOver', scope: panel}
+ * });
+ *
+ * @param {String/Object} eventName The name of the event to listen for.
+ * May also be an object who's property names are event names.
+ *
+ * @param {Function} [fn] The method the event invokes, or *if `scope` is specified, the *name* of the method within
+ * the specified `scope`. Will be called with arguments
+ * given to {@link #fireEvent} plus the `options` parameter described below.
+ *
+ * @param {Object} [scope] The scope (`this` reference) in which the handler function is
+ * executed. **If omitted, defaults to the object which fired the event.**
+ *
+ * @param {Object} [options] An object containing handler configuration.
+ *
+ * **Note:** Unlike in ExtJS 3.x, the options object will also be passed as the last
+ * argument to every event handler.
+ *
+ * This object may contain any of the following properties:
+ *
+ * @param {Object} options.scope
+ * The scope (`this` reference) in which the handler function is executed. **If omitted,
+ * defaults to the object which fired the event.**
+ *
+ * @param {Number} options.delay
+ * The number of milliseconds to delay the invocation of the handler after the event fires.
+ *
+ * @param {Boolean} options.single
+ * True to add a handler to handle just the next firing of the event, and then remove itself.
+ *
+ * @param {Number} options.buffer
+ * Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
+ * by the specified number of milliseconds. If the event fires again within that time,
+ * the original handler is _not_ invoked, but the new handler is scheduled in its place.
+ *
+ * @param {Ext.util.Observable} options.target
+ * Only call the handler if the event was fired on the target Observable, _not_ if the event
+ * was bubbled up from a child Observable.
+ *
+ * @param {String} options.element
+ * **This option is only valid for listeners bound to {@link Ext.Component Components}.**
+ * The name of a Component property which references an element to add a listener to.
+ *
+ * This option is useful during Component construction to add DOM event listeners to elements of
+ * {@link Ext.Component Components} which will exist only after the Component is rendered.
+ * For example, to add a click listener to a Panel's body:
+ *
+ * new Ext.panel.Panel({
+ * title: 'The title',
+ * listeners: {
+ * click: this.handlePanelClick,
+ * element: 'body'
+ * }
+ * });
+ *
+ * **Combining Options**
+ *
+ * Using the options argument, it is possible to combine different types of listeners:
+ *
+ * A delayed, one-time listener.
+ *
+ * myPanel.on('hide', this.handleClick, this, {
+ * single: true,
+ * delay: 100
+ * });
+ *
+ */
+ addListener: function(ename, fn, scope, options) {
+ var me = this,
+ config, event, hasListeners,
+ prevListenerCount = 0;
+
+ if (typeof ename !== 'string') {
+ options = ename;
+ for (ename in options) {
+ if (options.hasOwnProperty(ename)) {
+ config = options[ename];
+ if (!me.eventOptionsRe.test(ename)) {
+ me.addListener(ename, config.fn || config, config.scope || options.scope, config.fn ? config : options);
+ }
+ }
+ }
+ } else {
+ ename = ename.toLowerCase();
+ event = me.events[ename];
+ if (event && event.isEvent) {
+ prevListenerCount = event.listeners.length;
+ } else {
+ me.events[ename] = event = new Ext.util.Event(me, ename);
+ }
+
+ // Allow listeners: { click: 'onClick', scope: myObject }
+ if (typeof fn === 'string') {
+ if (!(scope[fn] || me[fn])) {
+ Ext.Error.raise('No method named "' + fn + '"');
+ }
+ fn = scope[fn] || me[fn];
+ }
+ event.addListener(fn, scope, options);
+
+ // If a new listener has been added (Event.addListener rejects duplicates of the same fn+scope)
+ // then increment the hasListeners counter
+ if (event.listeners.length !== prevListenerCount) {
+ hasListeners = me.hasListeners;
+ if (hasListeners.hasOwnProperty(ename)) {
+ // if we already have listeners at this level, just increment the count...
+ ++hasListeners[ename];
+ } else {
+ // otherwise, start the count at 1 (which hides whatever is in our prototype
+ // chain)...
+ hasListeners[ename] = 1;
+ }
+ }
+ }
+ },
+
+ /**
+ * Removes an event handler.
+ *
+ * @param {String} eventName The type of event the handler was associated with.
+ * @param {Function} fn The handler to remove. **This must be a reference to the function passed into the
+ * {@link #addListener} call.**
+ * @param {Object} scope (optional) The scope originally specified for the handler. It must be the same as the
+ * scope argument specified in the original call to {@link #addListener} or the listener will not be removed.
+ */
+ removeListener: function(ename, fn, scope) {
+ var me = this,
+ config,
+ event,
+ options;
+
+ if (typeof ename !== 'string') {
+ options = ename;
+ for (ename in options) {
+ if (options.hasOwnProperty(ename)) {
+ config = options[ename];
+ if (!me.eventOptionsRe.test(ename)) {
+ me.removeListener(ename, config.fn || config, config.scope || options.scope);
+ }
+ }
+ }
+ } else {
+ ename = ename.toLowerCase();
+ event = me.events[ename];
+ if (event && event.isEvent) {
+ if (event.removeListener(fn, scope) && !--me.hasListeners[ename]) {
+ // Delete this entry, since 0 does not mean no one is listening, just
+ // that no one is *directly& listening. This allows the eventBus or
+ // class observers to "poke" through and expose their presence.
+ delete me.hasListeners[ename];
+ }
+ }
+ }
+ },
+
+ /**
+ * Removes all listeners for this object including the managed listeners
+ */
+ clearListeners: function() {
+ var events = this.events,
+ event,
+ key;
+
+ for (key in events) {
+ if (events.hasOwnProperty(key)) {
+ event = events[key];
+ if (event.isEvent) {
+ event.clearListeners();
+ }
+ }
+ }
+
+ this.clearManagedListeners();
+ },
+
+ purgeListeners : function() {
+ if (Ext.global.console) {
+ Ext.global.console.warn('Observable: purgeListeners has been deprecated. Please use clearListeners.');
+ }
+ return this.clearListeners.apply(this, arguments);
+ },
+
+ /**
+ * Removes all managed listeners for this object.
+ */
+ clearManagedListeners : function() {
+ var managedListeners = this.managedListeners || [],
+ i = 0,
+ len = managedListeners.length;
+
+ for (; i < len; i++) {
+ this.removeManagedListenerItem(true, managedListeners[i]);
+ }
+
+ this.managedListeners = [];
+ },
+
+ /**
+ * Remove a single managed listener item
+ * @private
+ * @param {Boolean} isClear True if this is being called during a clear
+ * @param {Object} managedListener The managed listener item
+ * See removeManagedListener for other args
+ */
+ removeManagedListenerItem: function(isClear, managedListener, item, ename, fn, scope){
+ if (isClear || (managedListener.item === item && managedListener.ename === ename && (!fn || managedListener.fn === fn) && (!scope || managedListener.scope === scope))) {
+ managedListener.item.un(managedListener.ename, managedListener.fn, managedListener.scope);
+ if (!isClear) {
+ Ext.Array.remove(this.managedListeners, managedListener);
+ }
+ }
+ },
+
+ purgeManagedListeners : function() {
+ if (Ext.global.console) {
+ Ext.global.console.warn('Observable: purgeManagedListeners has been deprecated. Please use clearManagedListeners.');
+ }
+ return this.clearManagedListeners.apply(this, arguments);
+ },
+
+ /**
+ * Adds the specified events to the list of events which this Observable may fire.
+ *
+ * @param {Object/String...} eventNames Either an object with event names as properties with
+ * a value of `true`. For example:
+ *
+ * this.addEvents({
+ * storeloaded: true,
+ * storecleared: true
+ * });
+ *
+ * Or any number of event names as separate parameters. For example:
+ *
+ * this.addEvents('storeloaded', 'storecleared');
+ *
+ */
+ addEvents: function(o) {
+ var me = this,
+ events = me.events || (me.events = {}),
+ arg, args, i;
+
+ if (typeof o == 'string') {
+ for (args = arguments, i = args.length; i--; ) {
+ arg = args[i];
+ if (!events[arg]) {
+ events[arg] = true;
+ }
+ }
+ } else {
+ Ext.applyIf(me.events, o);
+ }
+ },
+
+ /**
+ * Checks to see if this object has any listeners for a specified event, or whether the event bubbles. The answer
+ * indicates whether the event needs firing or not.
+ *
+ * @param {String} eventName The name of the event to check for
+ * @return {Boolean} `true` if the event is being listened for or bubbles, else `false`
+ */
+ hasListener: function(ename) {
+ return !!this.hasListeners[ename.toLowerCase()];
+ },
+
+ /**
+ * Suspends the firing of all events. (see {@link #resumeEvents})
+ *
+ * @param {Boolean} queueSuspended Pass as true to queue up suspended events to be fired
+ * after the {@link #resumeEvents} call instead of discarding all suspended events.
+ */
+ suspendEvents: function(queueSuspended) {
+ this.eventsSuspended += 1;
+ if (queueSuspended && !this.eventQueue) {
+ this.eventQueue = [];
+ }
+ },
+
+ /**
+ * Resumes firing events (see {@link #suspendEvents}).
+ *
+ * If events were suspended using the `queueSuspended` parameter, then all events fired
+ * during event suspension will be sent to any listeners now.
+ */
+ resumeEvents: function() {
+ var me = this,
+ queued = me.eventQueue,
+ qLen, q;
+
+ if (me.eventsSuspended && ! --me.eventsSuspended) {
+ delete me.eventQueue;
+
+ if (queued) {
+ qLen = queued.length;
+ for (q = 0; q < qLen; q++) {
+ me.continueFireEvent.apply(me, queued[q]);
+ }
+ }
+ }
+ },
+
+ /**
+ * Relays selected events from the specified Observable as if the events were fired by `this`.
+ *
+ * For example if you are extending Grid, you might decide to forward some events from store.
+ * So you can do this inside your initComponent:
+ *
+ * this.relayEvents(this.getStore(), ['load']);
+ *
+ * The grid instance will then have an observable 'load' event which will be passed the
+ * parameters of the store's load event and any function fired with the grid's load event
+ * would have access to the grid using the `this` keyword.
+ *
+ * @param {Object} origin The Observable whose events this object is to relay.
+ * @param {String[]} events Array of event names to relay.
+ * @param {String} [prefix] A common prefix to prepend to the event names. For example:
+ *
+ * this.relayEvents(this.getStore(), ['load', 'clear'], 'store');
+ *
+ * Now the grid will forward 'load' and 'clear' events of store as 'storeload' and 'storeclear'.
+ */
+ relayEvents : function(origin, events, prefix) {
+ var me = this,
+ len = events.length,
+ i = 0,
+ oldName,
+ newName;
+
+ for (; i < len; i++) {
+ oldName = events[i];
+ newName = prefix ? prefix + oldName : oldName;
+
+ // Add the relaying function as a ManagedListener so that it is removed when this.clearListeners is called (usually when _this_ is destroyed)
+ me.mon(origin, oldName, me.createRelayer(newName));
+ }
+ },
+
+ /**
+ * @private
+ * Creates an event handling function which refires the event from this object as the passed event name.
+ * @param newName
+ * @param {Array} beginEnd (optional) The caller can specify on which indices to slice
+ * @returns {Function}
+ */
+ createRelayer: function(newName, beginEnd){
+ var me = this;
+ return function() {
+ return me.fireEvent.apply(me, [newName].concat(Array.prototype.slice.apply(arguments, beginEnd || [0, -1])));
+ };
+ },
+
+ /**
+ * Enables events fired by this Observable to bubble up an owner hierarchy by calling `this.getBubbleTarget()` if
+ * present. There is no implementation in the Observable base class.
+ *
+ * This is commonly used by Ext.Components to bubble events to owner Containers.
+ * See {@link Ext.Component#getBubbleTarget}. The default implementation in Ext.Component returns the
+ * Component's immediate owner. But if a known target is required, this can be overridden to access the
+ * required target more quickly.
+ *
+ * Example:
+ *
+ * Ext.override(Ext.form.field.Base, {
+ * // Add functionality to Field's initComponent to enable the change event to bubble
+ * initComponent : Ext.Function.createSequence(Ext.form.field.Base.prototype.initComponent, function() {
+ * this.enableBubble('change');
+ * }),
+ *
+ * // We know that we want Field's events to bubble directly to the FormPanel.
+ * getBubbleTarget : function() {
+ * if (!this.formPanel) {
+ * this.formPanel = this.findParentByType('form');
+ * }
+ * return this.formPanel;
+ * }
+ * });
+ *
+ * var myForm = new Ext.formPanel({
+ * title: 'User Details',
+ * items: [{
+ * ...
+ * }],
+ * listeners: {
+ * change: function() {
+ * // Title goes red if form has been modified.
+ * myForm.header.setStyle('color', 'red');
+ * }
+ * }
+ * });
+ *
+ * @param {String/String[]} eventNames The event name to bubble, or an Array of event names.
+ */
+ enableBubble: function(eventNames) {
+ if (eventNames) {
+ var me = this,
+ names = (typeof eventNames == 'string') ? arguments : eventNames,
+ length = names.length,
+ events = me.events,
+ ename, event, i;
+
+ for (i = 0; i < length; ++i) {
+ ename = names[i].toLowerCase();
+ event = events[ename];
+
+ if (!event || typeof event == 'boolean') {
+ events[ename] = event = new Ext.util.Event(me, ename);
+ }
+
+ // Event must fire if it bubbles (We don't know if anyone up the bubble hierarchy has listeners added)
+ me.hasListeners[ename] = (me.hasListeners[ename]||0) + 1;
+
+ event.bubble = true;
+ }
+ }
+ }
+}, function() {
+ var Observable = this,
+ proto = Observable.prototype,
+ HasListeners = function () {},
+ prepareMixin = function (T) {
+ if (!T.HasListeners) {
+ var proto = T.prototype;
+
+ // Classes that use us as a mixin (best practice) need to be prepared.
+ Observable.prepareClass(T, this);
+
+ // Now that we are mixed in to class T, we need to watch T for derivations
+ // and prepare them also.
+ T.onExtended(function (U) {
+ Observable.prepareClass(U);
+ });
+
+ // Also, if a class uses us as a mixin and that class is then used as
+ // a mixin, we need to be notified of that as well.
+ if (proto.onClassMixedIn) {
+ // play nice with other potential overrides...
+ Ext.override(T, {
+ onClassMixedIn: function (U) {
+ prepareMixin.call(this, U);
+ this.callParent(arguments);
+ }
+ });
+ } else {
+ // just us chickens, so add the method...
+ proto.onClassMixedIn = function (U) {
+ prepareMixin.call(this, U);
+ };
+ }
+ }
+ };
+
+ HasListeners.prototype = {
+ //$$: 42 // to make sure we have a proper prototype
+ };
+
+ proto.HasListeners = Observable.HasListeners = HasListeners;
+
+ Observable.createAlias({
+ /**
+ * @method
+ * Shorthand for {@link #addListener}.
+ * @inheritdoc Ext.util.Observable#addListener
+ */
+ on: 'addListener',
+ /**
+ * @method
+ * Shorthand for {@link #removeListener}.
+ * @inheritdoc Ext.util.Observable#removeListener
+ */
+ un: 'removeListener',
+ /**
+ * @method
+ * Shorthand for {@link #addManagedListener}.
+ * @inheritdoc Ext.util.Observable#addManagedListener
+ */
+ mon: 'addManagedListener',
+ /**
+ * @method
+ * Shorthand for {@link #removeManagedListener}.
+ * @inheritdoc Ext.util.Observable#removeManagedListener
+ */
+ mun: 'removeManagedListener'
+ });
+
+ //deprecated, will be removed in 5.0
+ Observable.observeClass = Observable.observe;
+
+ // this is considered experimental (along with beforeMethod, afterMethod, removeMethodListener?)
+ // allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
+ // private
+ function getMethodEvent(method){
+ var e = (this.methodEvents = this.methodEvents || {})[method],
+ returnValue,
+ v,
+ cancel,
+ obj = this,
+ makeCall;
+
+ if (!e) {
+ this.methodEvents[method] = e = {};
+ e.originalFn = this[method];
+ e.methodName = method;
+ e.before = [];
+ e.after = [];
+
+ makeCall = function(fn, scope, args){
+ if((v = fn.apply(scope || obj, args)) !== undefined){
+ if (typeof v == 'object') {
+ if(v.returnValue !== undefined){
+ returnValue = v.returnValue;
+ }else{
+ returnValue = v;
+ }
+ cancel = !!v.cancel;
+ }
+ else
+ if (v === false) {
+ cancel = true;
+ }
+ else {
+ returnValue = v;
+ }
+ }
+ };
+
+ this[method] = function(){
+ var args = Array.prototype.slice.call(arguments, 0),
+ b, i, len;
+ returnValue = v = undefined;
+ cancel = false;
+
+ for(i = 0, len = e.before.length; i < len; i++){
+ b = e.before[i];
+ makeCall(b.fn, b.scope, args);
+ if (cancel) {
+ return returnValue;
+ }
+ }
+
+ if((v = e.originalFn.apply(obj, args)) !== undefined){
+ returnValue = v;
+ }
+
+ for(i = 0, len = e.after.length; i < len; i++){
+ b = e.after[i];
+ makeCall(b.fn, b.scope, args);
+ if (cancel) {
+ return returnValue;
+ }
+ }
+ return returnValue;
+ };
+ }
+ return e;
+ }
+
+ Ext.apply(proto, {
+ onClassMixedIn: prepareMixin,
+
+ // these are considered experimental
+ // allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
+ // adds an 'interceptor' called before the original method
+ beforeMethod : function(method, fn, scope){
+ getMethodEvent.call(this, method).before.push({
+ fn: fn,
+ scope: scope
+ });
+ },
+
+ // adds a 'sequence' called after the original method
+ afterMethod : function(method, fn, scope){
+ getMethodEvent.call(this, method).after.push({
+ fn: fn,
+ scope: scope
+ });
+ },
+
+ removeMethodListener: function(method, fn, scope){
+ var e = this.getMethodEvent(method),
+ i, len;
+ for(i = 0, len = e.before.length; i < len; i++){
+ if(e.before[i].fn == fn && e.before[i].scope == scope){
+ Ext.Array.erase(e.before, i, 1);
+ return;
+ }
+ }
+ for(i = 0, len = e.after.length; i < len; i++){
+ if(e.after[i].fn == fn && e.after[i].scope == scope){
+ Ext.Array.erase(e.after, i, 1);
+ return;
+ }
+ }
+ },
+
+ toggleEventLogging: function(toggle) {
+ Ext.util.Observable[toggle ? 'capture' : 'releaseCapture'](this, function(en) {
+ if (Ext.isDefined(Ext.global.console)) {
+ Ext.global.console.log(en, arguments);
+ }
+ });
+ }
+ });
+});
+
+/**
+ * @class Ext.util.HashMap
+ *
+ * Represents a collection of a set of key and value pairs. Each key in the HashMap
+ * must be unique, the same key cannot exist twice. Access to items is provided via
+ * the key only. Sample usage:
+ *
+var map = new Ext.util.HashMap();
+map.add('key1', 1);
+map.add('key2', 2);
+map.add('key3', 3);
+
+map.each(function(key, value, length){
+ console.log(key, value, length);
+});
+ *
+ *
+ *
+ * The HashMap is an unordered class,
+ * there is no guarantee when iterating over the items that they will be in any particular
+ * order. If this is required, then use a {@link Ext.util.MixedCollection}.
+ *
+ */
+Ext.define('Ext.util.HashMap', {
+ mixins: {
+ observable: 'Ext.util.Observable'
+ },
+
+ /**
+ * @cfg {Function} keyFn A function that is used to retrieve a default key for a passed object.
+ * A default is provided that returns the id property on the object. This function is only used
+ * if the add method is called with a single argument.
+ */
+
+ /**
+ * Creates new HashMap.
+ * @param {Object} config (optional) Config object.
+ */
+ constructor: function(config) {
+ config = config || {};
+
+ var me = this,
+ keyFn = config.keyFn;
+
+ me.addEvents(
+ /**
+ * @event add
+ * Fires when a new item is added to the hash
+ * @param {Ext.util.HashMap} this.
+ * @param {String} key The key of the added item.
+ * @param {Object} value The value of the added item.
+ */
+ 'add',
+ /**
+ * @event clear
+ * Fires when the hash is cleared.
+ * @param {Ext.util.HashMap} this.
+ */
+ 'clear',
+ /**
+ * @event remove
+ * Fires when an item is removed from the hash.
+ * @param {Ext.util.HashMap} this.
+ * @param {String} key The key of the removed item.
+ * @param {Object} value The value of the removed item.
+ */
+ 'remove',
+ /**
+ * @event replace
+ * Fires when an item is replaced in the hash.
+ * @param {Ext.util.HashMap} this.
+ * @param {String} key The key of the replaced item.
+ * @param {Object} value The new value for the item.
+ * @param {Object} old The old value for the item.
+ */
+ 'replace'
+ );
+
+ me.mixins.observable.constructor.call(me, config);
+ me.clear(true);
+
+ if (keyFn) {
+ me.getKey = keyFn;
+ }
+ },
+
+ /**
+ * Gets the number of items in the hash.
+ * @return {Number} The number of items in the hash.
+ */
+ getCount: function() {
+ return this.length;
+ },
+
+ /**
+ * Implementation for being able to extract the key from an object if only
+ * a single argument is passed.
+ * @private
+ * @param {String} key The key
+ * @param {Object} value The value
+ * @return {Array} [key, value]
+ */
+ getData: function(key, value) {
+ // if we have no value, it means we need to get the key from the object
+ if (value === undefined) {
+ value = key;
+ key = this.getKey(value);
+ }
+
+ return [key, value];
+ },
+
+ /**
+ * Extracts the key from an object. This is a default implementation, it may be overridden
+ * @param {Object} o The object to get the key from
+ * @return {String} The key to use.
+ */
+ getKey: function(o) {
+ return o.id;
+ },
+
+ /**
+ * Adds an item to the collection. Fires the {@link #event-add} event when complete.
+ *
+ * @param {String/Object} key The key to associate with the item, or the new item.
+ *
+ * If a {@link #getKey} implementation was specified for this HashMap,
+ * or if the key of the stored items is in a property called `id`,
+ * the HashMap will be able to *derive* the key for the new item.
+ * In this case just pass the new item in this parameter.
+ *
+ * @param {Object} [o] The item to add.
+ *
+ * @return {Object} The item added.
+ */
+ add: function(key, value) {
+ var me = this;
+
+ if (value === undefined) {
+ value = key;
+ key = me.getKey(value);
+ }
+
+ if (me.containsKey(key)) {
+ return me.replace(key, value);
+ }
+
+ me.map[key] = value;
+ ++me.length;
+ if (me.hasListeners.add) {
+ me.fireEvent('add', me, key, value);
+ }
+ return value;
+ },
+
+ /**
+ * Replaces an item in the hash. If the key doesn't exist, the
+ * {@link #method-add} method will be used.
+ * @param {String} key The key of the item.
+ * @param {Object} value The new value for the item.
+ * @return {Object} The new value of the item.
+ */
+ replace: function(key, value) {
+ var me = this,
+ map = me.map,
+ old;
+
+ if (value === undefined) {
+ value = key;
+ key = me.getKey(value);
+ }
+
+ if (!me.containsKey(key)) {
+ me.add(key, value);
+ }
+ old = map[key];
+ map[key] = value;
+ if (me.hasListeners.replace) {
+ me.fireEvent('replace', me, key, value, old);
+ }
+ return value;
+ },
+
+ /**
+ * Remove an item from the hash.
+ * @param {Object} o The value of the item to remove.
+ * @return {Boolean} True if the item was successfully removed.
+ */
+ remove: function(o) {
+ var key = this.findKey(o);
+ if (key !== undefined) {
+ return this.removeAtKey(key);
+ }
+ return false;
+ },
+
+ /**
+ * Remove an item from the hash.
+ * @param {String} key The key to remove.
+ * @return {Boolean} True if the item was successfully removed.
+ */
+ removeAtKey: function(key) {
+ var me = this,
+ value;
+
+ if (me.containsKey(key)) {
+ value = me.map[key];
+ delete me.map[key];
+ --me.length;
+ if (me.hasListeners.remove) {
+ me.fireEvent('remove', me, key, value);
+ }
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Retrieves an item with a particular key.
+ * @param {String} key The key to lookup.
+ * @return {Object} The value at that key. If it doesn't exist, undefined is returned.
+ */
+ get: function(key) {
+ return this.map[key];
+ },
+
+ /**
+ * Removes all items from the hash.
+ * @return {Ext.util.HashMap} this
+ */
+ clear: function(/* private */ initial) {
+ var me = this;
+ me.map = {};
+ me.length = 0;
+ if (initial !== true && me.hasListeners.clear) {
+ me.fireEvent('clear', me);
+ }
+ return me;
+ },
+
+ /**
+ * Checks whether a key exists in the hash.
+ * @param {String} key The key to check for.
+ * @return {Boolean} True if they key exists in the hash.
+ */
+ containsKey: function(key) {
+ return this.map[key] !== undefined;
+ },
+
+ /**
+ * Checks whether a value exists in the hash.
+ * @param {Object} value The value to check for.
+ * @return {Boolean} True if the value exists in the dictionary.
+ */
+ contains: function(value) {
+ return this.containsKey(this.findKey(value));
+ },
+
+ /**
+ * Return all of the keys in the hash.
+ * @return {Array} An array of keys.
+ */
+ getKeys: function() {
+ return this.getArray(true);
+ },
+
+ /**
+ * Return all of the values in the hash.
+ * @return {Array} An array of values.
+ */
+ getValues: function() {
+ return this.getArray(false);
+ },
+
+ /**
+ * Gets either the keys/values in an array from the hash.
+ * @private
+ * @param {Boolean} isKey True to extract the keys, otherwise, the value
+ * @return {Array} An array of either keys/values from the hash.
+ */
+ getArray: function(isKey) {
+ var arr = [],
+ key,
+ map = this.map;
+ for (key in map) {
+ if (map.hasOwnProperty(key)) {
+ arr.push(isKey ? key: map[key]);
+ }
+ }
+ return arr;
+ },
+
+ /**
+ * Executes the specified function once for each item in the hash.
+ * Returning false from the function will cease iteration.
+ *
+ * The paramaters passed to the function are:
+ *
+ * @param {Function} fn The function to execute.
+ * @param {Object} scope The scope to execute in. Defaults to this .
+ * @return {Ext.util.HashMap} this
+ */
+ each: function(fn, scope) {
+ // copy items so they may be removed during iteration.
+ var items = Ext.apply({}, this.map),
+ key,
+ length = this.length;
+
+ scope = scope || this;
+ for (key in items) {
+ if (items.hasOwnProperty(key)) {
+ if (fn.call(scope, key, items[key], length) === false) {
+ break;
+ }
+ }
+ }
+ return this;
+ },
+
+ /**
+ * Performs a shallow copy on this hash.
+ * @return {Ext.util.HashMap} The new hash object.
+ */
+ clone: function() {
+ var hash = new this.self(),
+ map = this.map,
+ key;
+
+ hash.suspendEvents();
+ for (key in map) {
+ if (map.hasOwnProperty(key)) {
+ hash.add(key, map[key]);
+ }
+ }
+ hash.resumeEvents();
+ return hash;
+ },
+
+ /**
+ * @private
+ * Find the key for a value.
+ * @param {Object} value The value to find.
+ * @return {Object} The value of the item. Returns undefined if not found.
+ */
+ findKey: function(value) {
+ var key,
+ map = this.map;
+
+ for (key in map) {
+ if (map.hasOwnProperty(key) && map[key] === value) {
+ return key;
+ }
+ }
+ return undefined;
+ }
+});
+
+/**
+ * Base Manager class
+ */
+Ext.define('Ext.AbstractManager', {
+
+ /* Begin Definitions */
+
+ requires: ['Ext.util.HashMap'],
+
+ /* End Definitions */
+
+ typeName: 'type',
+
+ constructor: function(config) {
+ Ext.apply(this, config || {});
+
+ /**
+ * @property {Ext.util.HashMap} all
+ * Contains all of the items currently managed
+ */
+ this.all = new Ext.util.HashMap();
+
+ this.types = {};
+ },
+
+ /**
+ * Returns an item by id.
+ * For additional details see {@link Ext.util.HashMap#get}.
+ * @param {String} id The id of the item
+ * @return {Object} The item, undefined if not found.
+ */
+ get : function(id) {
+ return this.all.get(id);
+ },
+
+ /**
+ * Registers an item to be managed
+ * @param {Object} item The item to register
+ */
+ register: function(item) {
+ var all = this.all,
+ key = all.getKey(item);
+
+ if (all.containsKey(key)) {
+ Ext.Error.raise('Registering duplicate id "' + key + '" with this manager');
+ }
+ this.all.add(item);
+ },
+
+ /**
+ * Unregisters an item by removing it from this manager
+ * @param {Object} item The item to unregister
+ */
+ unregister: function(item) {
+ this.all.remove(item);
+ },
+
+ /**
+ * Registers a new item constructor, keyed by a type key.
+ * @param {String} type The mnemonic string by which the class may be looked up.
+ * @param {Function} cls The new instance class.
+ */
+ registerType : function(type, cls) {
+ this.types[type] = cls;
+ cls[this.typeName] = type;
+ },
+
+ /**
+ * Checks if an item type is registered.
+ * @param {String} type The mnemonic string by which the class may be looked up
+ * @return {Boolean} Whether the type is registered.
+ */
+ isRegistered : function(type){
+ return this.types[type] !== undefined;
+ },
+
+ /**
+ * Creates and returns an instance of whatever this manager manages, based on the supplied type and
+ * config object.
+ * @param {Object} config The config object
+ * @param {String} defaultType If no type is discovered in the config object, we fall back to this type
+ * @return {Object} The instance of whatever this manager is managing
+ */
+ create: function(config, defaultType) {
+ var type = config[this.typeName] || config.type || defaultType,
+ Constructor = this.types[type];
+
+ if (Constructor === undefined) {
+ Ext.Error.raise("The '" + type + "' type has not been registered with this manager");
+ }
+
+ return new Constructor(config);
+ },
+
+ /**
+ * Registers a function that will be called when an item with the specified id is added to the manager.
+ * This will happen on instantiation.
+ * @param {String} id The item id
+ * @param {Function} fn The callback function. Called with a single parameter, the item.
+ * @param {Object} scope The scope (this reference) in which the callback is executed.
+ * Defaults to the item.
+ */
+ onAvailable : function(id, fn, scope){
+ var all = this.all,
+ item,
+ callback;
+
+ if (all.containsKey(id)) {
+ item = all.get(id);
+ fn.call(scope || item, item);
+ } else {
+ callback = function(map, key, item){
+ if (key == id) {
+ fn.call(scope || item, item);
+ all.un('add', callback);
+ }
+ };
+ all.on('add', callback);
+ }
+ },
+
+ /**
+ * Executes the specified function once for each item in the collection.
+ * @param {Function} fn The function to execute.
+ * @param {String} fn.key The key of the item
+ * @param {Number} fn.value The value of the item
+ * @param {Number} fn.length The total number of items in the collection
+ * @param {Boolean} fn.return False to cease iteration.
+ * @param {Object} scope The scope to execute in. Defaults to `this`.
+ */
+ each: function(fn, scope){
+ this.all.each(fn, scope || this);
+ },
+
+ /**
+ * Gets the number of items in the collection.
+ * @return {Number} The number of items in the collection.
+ */
+ getCount: function(){
+ return this.all.getCount();
+ }
+});
+
+/**
+ * @class Ext.ComponentManager
+ * Provides a registry of all Components (instances of {@link Ext.Component} or any subclass
+ * thereof) on a page so that they can be easily accessed by {@link Ext.Component component}
+ * {@link Ext.Component#id id} (see {@link #get}, or the convenience method {@link Ext#getCmp Ext.getCmp}).
+ * This object also provides a registry of available Component classes
+ * indexed by a mnemonic code known as the Component's {@link Ext.Component#xtype xtype}.
+ * The xtype provides a way to avoid instantiating child Components
+ * when creating a full, nested config object for a complete Ext page.
+ * A child Component may be specified simply as a config object
+ * as long as the correct {@link Ext.Component#xtype xtype} is specified so that if and when the Component
+ * needs rendering, the correct type can be looked up for lazy instantiation.
+ * For a list of all available {@link Ext.Component#xtype xtypes}, see {@link Ext.Component}.
+ * @singleton
+ */
+Ext.define('Ext.ComponentManager', {
+ extend: 'Ext.AbstractManager',
+ alternateClassName: 'Ext.ComponentMgr',
+
+ singleton: true,
+
+ typeName: 'xtype',
+
+ /**
+ * Creates a new Component from the specified config object using the
+ * config object's xtype to determine the class to instantiate.
+ * @param {Object} config A configuration object for the Component you wish to create.
+ * @param {String} defaultType (optional) The xtype to use if the config object does not
+ * contain a xtype. (Optional if the config contains a xtype).
+ * @return {Ext.Component} The newly instantiated Component.
+ */
+ create: function(component, defaultType){
+ if (typeof component == 'string') {
+ return Ext.widget(component);
+ }
+ if (component.isComponent) {
+ return component;
+ }
+ return Ext.widget(component.xtype || defaultType, component);
+ },
+
+ registerType: function(type, cls) {
+ this.types[type] = cls;
+ cls[this.typeName] = type;
+ cls.prototype[this.typeName] = type;
+ }
+});
+
+/**
+ * Provides searching of Components within Ext.ComponentManager (globally) or a specific
+ * Ext.container.Container on the document with a similar syntax to a CSS selector.
+ *
+ * Components can be retrieved by using their {@link Ext.Component xtype}
+ *
+ * - `component`
+ * - `gridpanel`
+ *
+ * Matching by xtype matches inherited types, so in the following code, the previous field
+ * *of any type which inherits from `TextField`* will be found:
+ *
+ * prevField = myField.previousNode('textfield');
+ *
+ * To match only the exact type, pass the "shallow" flag (See {@link Ext.AbstractComponent#isXType AbstractComponent's isXType method})
+ *
+ * prevTextField = myField.previousNode('textfield(true)');
+ *
+ * An itemId or id must be prefixed with a #
+ *
+ * - `#myContainer`
+ *
+ * Attributes must be wrapped in brackets
+ *
+ * - `component[autoScroll]`
+ * - `panel[title="Test"]`
+ *
+ * Member expressions from candidate Components may be tested. If the expression returns a *truthy* value,
+ * the candidate Component will be included in the query:
+ *
+ * var disabledFields = myFormPanel.query("{isDisabled()}");
+ *
+ * Pseudo classes may be used to filter results in the same way as in {@link Ext.DomQuery DomQuery}:
+ *
+ * // Function receives array and returns a filtered array.
+ * Ext.ComponentQuery.pseudos.invalid = function(items) {
+ * var i = 0, l = items.length, c, result = [];
+ * for (; i < l; i++) {
+ * if (!(c = items[i]).isValid()) {
+ * result.push(c);
+ * }
+ * }
+ * return result;
+ * };
+ *
+ * var invalidFields = myFormPanel.query('field:invalid');
+ * if (invalidFields.length) {
+ * invalidFields[0].getEl().scrollIntoView(myFormPanel.body);
+ * for (var i = 0, l = invalidFields.length; i < l; i++) {
+ * invalidFields[i].getEl().frame("red");
+ * }
+ * }
+ *
+ * Default pseudos include:
+ *
+ * - not
+ * - first
+ * - last
+ *
+ * Queries return an array of components.
+ * Here are some example queries.
+ *
+ * // retrieve all Ext.Panels in the document by xtype
+ * var panelsArray = Ext.ComponentQuery.query('panel');
+ *
+ * // retrieve all Ext.Panels within the container with an id myCt
+ * var panelsWithinmyCt = Ext.ComponentQuery.query('#myCt panel');
+ *
+ * // retrieve all direct children which are Ext.Panels within myCt
+ * var directChildPanel = Ext.ComponentQuery.query('#myCt > panel');
+ *
+ * // retrieve all grids and trees
+ * var gridsAndTrees = Ext.ComponentQuery.query('gridpanel, treepanel');
+ *
+ * For easy access to queries based from a particular Container see the {@link Ext.container.Container#query},
+ * {@link Ext.container.Container#down} and {@link Ext.container.Container#child} methods. Also see
+ * {@link Ext.Component#up}.
+ */
+Ext.define('Ext.ComponentQuery', {
+ singleton: true,
+ requires: ['Ext.ComponentManager']
+}, function() {
+
+ var cq = this,
+
+ // A function source code pattern with a placeholder which accepts an expression which yields a truth value when applied
+ // as a member on each item in the passed array.
+ filterFnPattern = [
+ 'var r = [],',
+ 'i = 0,',
+ 'it = items,',
+ 'l = it.length,',
+ 'c;',
+ 'for (; i < l; i++) {',
+ 'c = it[i];',
+ 'if (c.{0}) {',
+ 'r.push(c);',
+ '}',
+ '}',
+ 'return r;'
+ ].join(''),
+
+ filterItems = function(items, operation) {
+ // Argument list for the operation is [ itemsArray, operationArg1, operationArg2...]
+ // The operation's method loops over each item in the candidate array and
+ // returns an array of items which match its criteria
+ return operation.method.apply(this, [ items ].concat(operation.args));
+ },
+
+ getItems = function(items, mode) {
+ var result = [],
+ i = 0,
+ length = items.length,
+ candidate,
+ deep = mode !== '>';
+
+ for (; i < length; i++) {
+ candidate = items[i];
+ if (candidate.getRefItems) {
+ result = result.concat(candidate.getRefItems(deep));
+ }
+ }
+ return result;
+ },
+
+ getAncestors = function(items) {
+ var result = [],
+ i = 0,
+ length = items.length,
+ candidate;
+ for (; i < length; i++) {
+ candidate = items[i];
+ while (!!(candidate = (candidate.ownerCt || candidate.floatParent))) {
+ result.push(candidate);
+ }
+ }
+ return result;
+ },
+
+ // Filters the passed candidate array and returns only items which match the passed xtype
+ filterByXType = function(items, xtype, shallow) {
+ if (xtype === '*') {
+ return items.slice();
+ }
+ else {
+ var result = [],
+ i = 0,
+ length = items.length,
+ candidate;
+ for (; i < length; i++) {
+ candidate = items[i];
+ if (candidate.isXType(xtype, shallow)) {
+ result.push(candidate);
+ }
+ }
+ return result;
+ }
+ },
+
+ // Filters the passed candidate array and returns only items which have the passed className
+ filterByClassName = function(items, className) {
+ var EA = Ext.Array,
+ result = [],
+ i = 0,
+ length = items.length,
+ candidate;
+ for (; i < length; i++) {
+ candidate = items[i];
+ if (candidate.hasCls(className)) {
+ result.push(candidate);
+ }
+ }
+ return result;
+ },
+
+ // Filters the passed candidate array and returns only items which have the specified property match
+ filterByAttribute = function(items, property, operator, value) {
+ var result = [],
+ i = 0,
+ length = items.length,
+ candidate;
+ for (; i < length; i++) {
+ candidate = items[i];
+ if (!value ? !!candidate[property] : (String(candidate[property]) === value)) {
+ result.push(candidate);
+ }
+ }
+ return result;
+ },
+
+ // Filters the passed candidate array and returns only items which have the specified itemId or id
+ filterById = function(items, id) {
+ var result = [],
+ i = 0,
+ length = items.length,
+ candidate;
+ for (; i < length; i++) {
+ candidate = items[i];
+ if (candidate.getItemId() === id) {
+ result.push(candidate);
+ }
+ }
+ return result;
+ },
+
+ // Filters the passed candidate array and returns only items which the named pseudo class matcher filters in
+ filterByPseudo = function(items, name, value) {
+ return cq.pseudos[name](items, value);
+ },
+
+ // Determines leading mode
+ // > for direct child, and ^ to switch to ownerCt axis
+ modeRe = /^(\s?([>\^])\s?|\s|$)/,
+
+ // Matches a token with possibly (true|false) appended for the "shallow" parameter
+ tokenRe = /^(#)?([\w\-]+|\*)(?:\((true|false)\))?/,
+
+ matchers = [{
+ // Checks for .xtype with possibly (true|false) appended for the "shallow" parameter
+ re: /^\.([\w\-]+)(?:\((true|false)\))?/,
+ method: filterByXType
+ },{
+ // checks for [attribute=value]
+ re: /^(?:[\[](?:@)?([\w\-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]])/,
+ method: filterByAttribute
+ }, {
+ // checks for #cmpItemId
+ re: /^#([\w\-]+)/,
+ method: filterById
+ }, {
+ // checks for :()
+ re: /^\:([\w\-]+)(?:\(((?:\{[^\}]+\})|(?:(?!\{)[^\s>\/]*?(?!\})))\))?/,
+ method: filterByPseudo
+ }, {
+ // checks for {}
+ re: /^(?:\{([^\}]+)\})/,
+ method: filterFnPattern
+ }];
+
+ // Internal class Ext.ComponentQuery.Query
+ cq.Query = Ext.extend(Object, {
+ constructor: function(cfg) {
+ cfg = cfg || {};
+ Ext.apply(this, cfg);
+ },
+
+ // Executes this Query upon the selected root.
+ // The root provides the initial source of candidate Component matches which are progressively
+ // filtered by iterating through this Query's operations cache.
+ // If no root is provided, all registered Components are searched via the ComponentManager.
+ // root may be a Container who's descendant Components are filtered
+ // root may be a Component with an implementation of getRefItems which provides some nested Components such as the
+ // docked items within a Panel.
+ // root may be an array of candidate Components to filter using this Query.
+ execute : function(root) {
+ var operations = this.operations,
+ i = 0,
+ length = operations.length,
+ operation,
+ workingItems;
+
+ // no root, use all Components in the document
+ if (!root) {
+ workingItems = Ext.ComponentManager.all.getArray();
+ }
+ // Root is a candidate Array
+ else if (Ext.isArray(root)) {
+ workingItems = root;
+ }
+ // Root is a MixedCollection
+ else if (root.isMixedCollection) {
+ workingItems = root.items;
+ }
+
+ // We are going to loop over our operations and take care of them
+ // one by one.
+ for (; i < length; i++) {
+ operation = operations[i];
+
+ // The mode operation requires some custom handling.
+ // All other operations essentially filter down our current
+ // working items, while mode replaces our current working
+ // items by getting children from each one of our current
+ // working items. The type of mode determines the type of
+ // children we get. (e.g. > only gets direct children)
+ if (operation.mode === '^') {
+ workingItems = getAncestors(workingItems || [root]);
+ }
+ else if (operation.mode) {
+ workingItems = getItems(workingItems || [root], operation.mode);
+ }
+ else {
+ workingItems = filterItems(workingItems || getItems([root]), operation);
+ }
+
+ // If this is the last operation, it means our current working
+ // items are the final matched items. Thus return them!
+ if (i === length -1) {
+ return workingItems;
+ }
+ }
+ return [];
+ },
+
+ is: function(component) {
+ var operations = this.operations,
+ components = Ext.isArray(component) ? component : [component],
+ originalLength = components.length,
+ lastOperation = operations[operations.length-1],
+ ln, i;
+
+ components = filterItems(components, lastOperation);
+ if (components.length === originalLength) {
+ if (operations.length > 1) {
+ for (i = 0, ln = components.length; i < ln; i++) {
+ if (Ext.Array.indexOf(this.execute(), components[i]) === -1) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ });
+
+ Ext.apply(this, {
+
+ // private cache of selectors and matching ComponentQuery.Query objects
+ cache: {},
+
+ // private cache of pseudo class filter functions
+ pseudos: {
+ not: function(components, selector){
+ var CQ = Ext.ComponentQuery,
+ i = 0,
+ length = components.length,
+ results = [],
+ index = -1,
+ component;
+
+ for(; i < length; ++i) {
+ component = components[i];
+ if (!CQ.is(component, selector)) {
+ results[++index] = component;
+ }
+ }
+ return results;
+ },
+ first: function(components) {
+ var ret = [];
+
+ if (components.length > 0) {
+ ret.push(components[0]);
+ }
+ return ret;
+ },
+ last: function(components) {
+ var len = components.length,
+ ret = [];
+
+ if (len > 0) {
+ ret.push(components[len - 1]);
+ }
+ return ret;
+ }
+ },
+
+ /**
+ * Returns an array of matched Components from within the passed root object.
+ *
+ * This method filters returned Components in a similar way to how CSS selector based DOM
+ * queries work using a textual selector string.
+ *
+ * See class summary for details.
+ *
+ * @param {String} selector The selector string to filter returned Components
+ * @param {Ext.container.Container} root The Container within which to perform the query.
+ * If omitted, all Components within the document are included in the search.
+ *
+ * This parameter may also be an array of Components to filter according to the selector.
+ * @returns {Ext.Component[]} The matched Components.
+ *
+ * @member Ext.ComponentQuery
+ */
+ query: function(selector, root) {
+ var selectors = selector.split(','),
+ length = selectors.length,
+ i = 0,
+ results = [],
+ noDupResults = [],
+ dupMatcher = {},
+ query, resultsLn, cmp;
+
+ for (; i < length; i++) {
+ selector = Ext.String.trim(selectors[i]);
+ query = this.cache[selector] || (this.cache[selector] = this.parse(selector));
+ results = results.concat(query.execute(root));
+ }
+
+ // multiple selectors, potential to find duplicates
+ // lets filter them out.
+ if (length > 1) {
+ resultsLn = results.length;
+ for (i = 0; i < resultsLn; i++) {
+ cmp = results[i];
+ if (!dupMatcher[cmp.id]) {
+ noDupResults.push(cmp);
+ dupMatcher[cmp.id] = true;
+ }
+ }
+ results = noDupResults;
+ }
+ return results;
+ },
+
+ /**
+ * Tests whether the passed Component matches the selector string.
+ * @param {Ext.Component} component The Component to test
+ * @param {String} selector The selector string to test against.
+ * @return {Boolean} True if the Component matches the selector.
+ * @member Ext.ComponentQuery
+ */
+ is: function(component, selector) {
+ if (!selector) {
+ return true;
+ }
+ var selectors = selector.split(','),
+ length = selectors.length,
+ i = 0,
+ query;
+
+ for (; i < length; i++) {
+ selector = Ext.String.trim(selectors[i]);
+ query = this.cache[selector] || (this.cache[selector] = this.parse(selector));
+ if (query.is(component)) {
+ return true;
+ }
+ }
+ return false;
+ },
+
+ parse: function(selector) {
+ var operations = [],
+ length = matchers.length,
+ lastSelector,
+ tokenMatch,
+ matchedChar,
+ modeMatch,
+ selectorMatch,
+ i, matcher, method;
+
+ // We are going to parse the beginning of the selector over and
+ // over again, slicing off the selector any portions we converted into an
+ // operation, until it is an empty string.
+ while (selector && lastSelector !== selector) {
+ lastSelector = selector;
+
+ // First we check if we are dealing with a token like #, * or an xtype
+ tokenMatch = selector.match(tokenRe);
+
+ if (tokenMatch) {
+ matchedChar = tokenMatch[1];
+
+ // If the token is prefixed with a # we push a filterById operation to our stack
+ if (matchedChar === '#') {
+ operations.push({
+ method: filterById,
+ args: [Ext.String.trim(tokenMatch[2])]
+ });
+ }
+ // If the token is prefixed with a . we push a filterByClassName operation to our stack
+ // FIXME: Not enabled yet. just needs \. adding to the tokenRe prefix
+ else if (matchedChar === '.') {
+ operations.push({
+ method: filterByClassName,
+ args: [Ext.String.trim(tokenMatch[2])]
+ });
+ }
+ // If the token is a * or an xtype string, we push a filterByXType
+ // operation to the stack.
+ else {
+ operations.push({
+ method: filterByXType,
+ args: [Ext.String.trim(tokenMatch[2]), Boolean(tokenMatch[3])]
+ });
+ }
+
+ // Now we slice of the part we just converted into an operation
+ selector = selector.replace(tokenMatch[0], '');
+ }
+
+ // If the next part of the query is not a space or > or ^, it means we
+ // are going to check for more things that our current selection
+ // has to comply to.
+ while (!(modeMatch = selector.match(modeRe))) {
+ // Lets loop over each type of matcher and execute it
+ // on our current selector.
+ for (i = 0; selector && i < length; i++) {
+ matcher = matchers[i];
+ selectorMatch = selector.match(matcher.re);
+ method = matcher.method;
+
+ // If we have a match, add an operation with the method
+ // associated with this matcher, and pass the regular
+ // expression matches are arguments to the operation.
+ if (selectorMatch) {
+ operations.push({
+ method: Ext.isString(matcher.method)
+ // Turn a string method into a function by formatting the string with our selector matche expression
+ // A new method is created for different match expressions, eg {id=='textfield-1024'}
+ // Every expression may be different in different selectors.
+ ? Ext.functionFactory('items', Ext.String.format.apply(Ext.String, [method].concat(selectorMatch.slice(1))))
+ : matcher.method,
+ args: selectorMatch.slice(1)
+ });
+ selector = selector.replace(selectorMatch[0], '');
+ break; // Break on match
+ }
+ // Exhausted all matches: It's an error
+ if (i === (length - 1)) {
+ Ext.Error.raise('Invalid ComponentQuery selector: "' + arguments[0] + '"');
+ }
+ }
+ }
+
+ // Now we are going to check for a mode change. This means a space
+ // or a > to determine if we are going to select all the children
+ // of the currently matched items, or a ^ if we are going to use the
+ // ownerCt axis as the candidate source.
+ if (modeMatch[1]) { // Assignment, and test for truthiness!
+ operations.push({
+ mode: modeMatch[2]||modeMatch[1]
+ });
+ selector = selector.replace(modeMatch[0], '');
+ }
+ }
+
+ // Now that we have all our operations in an array, we are going
+ // to create a new Query using these operations.
+ return new cq.Query({
+ operations: operations
+ });
+ }
+ });
+});
+
+/*
+ * The dirty implementation in this class is quite naive. The reasoning for this is that the dirty state
+ * will only be used in very specific circumstances, specifically, after the render process has begun but
+ * the component is not yet rendered to the DOM. As such, we want it to perform as quickly as possible
+ * so it's not as fully featured as you may expect.
+ */
+
+/**
+ * Manages certain element-like data prior to rendering. These values are passed
+ * on to the render process. This is currently used to manage the "class" and "style" attributes
+ * of a component's primary el as well as the bodyEl of panels. This allows things like
+ * addBodyCls in Panel to share logic with addCls in AbstractComponent.
+ * @private
+ */
+Ext.define('Ext.util.ProtoElement', (function () {
+ var splitWords = Ext.String.splitWords,
+ toMap = Ext.Array.toMap;
+
+ return {
+
+ isProtoEl: true,
+
+ /**
+ * The property name for the className on the data object passed to {@link #writeTo}.
+ */
+ clsProp: 'cls',
+
+ /**
+ * The property name for the style on the data object passed to {@link #writeTo}.
+ */
+ styleProp: 'style',
+
+ /**
+ * The property name for the removed classes on the data object passed to {@link #writeTo}.
+ */
+ removedProp: 'removed',
+
+ /**
+ * True if the style must be converted to text during {@link #writeTo}. When used to
+ * populate tpl data, this will be true. When used to populate {@link Ext.DomHelper}
+ * specs, this will be false (the default).
+ */
+ styleIsText: false,
+
+ constructor: function (config) {
+ var me = this;
+
+ Ext.apply(me, config);
+
+ me.classList = splitWords(me.cls);
+ me.classMap = toMap(me.classList);
+ delete me.cls;
+
+ if (Ext.isFunction(me.style)) {
+ me.styleFn = me.style;
+ delete me.style;
+ } else if (typeof me.style == 'string') {
+ me.style = Ext.Element.parseStyles(me.style);
+ } else if (me.style) {
+ me.style = Ext.apply({}, me.style); // don't edit the given object
+ }
+ },
+
+ /**
+ * Indicates that the current state of the object has been flushed to the DOM, so we need
+ * to track any subsequent changes
+ */
+ flush: function(){
+ this.flushClassList = [];
+ this.removedClasses = {};
+ // clear the style, it will be recreated if we add anything new
+ delete this.style;
+ },
+
+ /**
+ * Adds class to the element.
+ * @param {String} cls One or more classnames separated with spaces.
+ * @return {Ext.util.ProtoElement} this
+ */
+ addCls: function (cls) {
+ var me = this,
+ add = splitWords(cls),
+ length = add.length,
+ list = me.classList,
+ map = me.classMap,
+ flushList = me.flushClassList,
+ i = 0,
+ c;
+
+ for (; i < length; ++i) {
+ c = add[i];
+ if (!map[c]) {
+ map[c] = true;
+ list.push(c);
+ if (flushList) {
+ flushList.push(c);
+ delete me.removedClasses[c];
+ }
+ }
+ }
+
+ return me;
+ },
+
+ /**
+ * True if the element has given class.
+ * @param {String} cls
+ * @return {Boolean}
+ */
+ hasCls: function (cls) {
+ return cls in this.classMap;
+ },
+
+ /**
+ * Removes class from the element.
+ * @param {String} cls One or more classnames separated with spaces.
+ * @return {Ext.util.ProtoElement} this
+ */
+ removeCls: function (cls) {
+ var me = this,
+ list = me.classList,
+ newList = (me.classList = []),
+ remove = toMap(splitWords(cls)),
+ length = list.length,
+ map = me.classMap,
+ removedClasses = me.removedClasses,
+ i, c;
+
+ for (i = 0; i < length; ++i) {
+ c = list[i];
+ if (remove[c]) {
+ if (removedClasses) {
+ if (map[c]) {
+ removedClasses[c] = true;
+ Ext.Array.remove(me.flushClassList, c);
+ }
+ }
+ delete map[c];
+ } else {
+ newList.push(c);
+ }
+ }
+
+ return me;
+ },
+
+ /**
+ * Adds styles to the element.
+ * @param {String/Object} prop The style property to be set, or an object of multiple styles.
+ * @param {String} [value] The value to apply to the given property.
+ * @return {Ext.util.ProtoElement} this
+ */
+ setStyle: function (prop, value) {
+ var me = this,
+ style = me.style || (me.style = {});
+
+ if (typeof prop == 'string') {
+ if (arguments.length === 1) {
+ me.setStyle(Ext.Element.parseStyles(prop));
+ } else {
+ style[prop] = value;
+ }
+ } else {
+ Ext.apply(style, prop);
+ }
+
+ return me;
+ },
+
+ /**
+ * Writes style and class properties to given object.
+ * Styles will be written to {@link #styleProp} and class names to {@link #clsProp}.
+ * @param {Object} to
+ * @return {Object} to
+ */
+ writeTo: function (to) {
+ var me = this,
+ classList = me.flushClassList || me.classList,
+ removedClasses = me.removedClasses,
+ style;
+
+ if (me.styleFn) {
+ style = Ext.apply({}, me.styleFn());
+ Ext.apply(style, me.style);
+ } else {
+ style = me.style;
+ }
+
+ to[me.clsProp] = classList.join(' ');
+
+ if (style) {
+ to[me.styleProp] = me.styleIsText ? Ext.DomHelper.generateStyles(style) : style;
+ }
+
+ if (removedClasses) {
+ removedClasses = Ext.Object.getKeys(removedClasses);
+ if (removedClasses.length) {
+ to[me.removedProp] = removedClasses.join(' ');
+ }
+ }
+
+ return to;
+ }
+ };
+}()));
+
+//@tag dom,core
+//@require util/Event.js
+//@define Ext.EventManager
+
+/**
+ * @class Ext.EventManager
+ * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
+ * several useful events directly.
+ * See {@link Ext.EventObject} for more details on normalized event objects.
+ * @singleton
+ */
+Ext.EventManager = new function() {
+ var EventManager = this,
+ doc = document,
+ win = window,
+ initExtCss = function() {
+ // find the body element
+ var bd = doc.body || doc.getElementsByTagName('body')[0],
+ baseCSSPrefix = Ext.baseCSSPrefix,
+ cls = [baseCSSPrefix + 'body'],
+ htmlCls = [],
+ supportsLG = Ext.supports.CSS3LinearGradient,
+ supportsBR = Ext.supports.CSS3BorderRadius,
+ resetCls = [],
+ html,
+ resetElementSpec;
+
+ if (!bd) {
+ return false;
+ }
+
+ html = bd.parentNode;
+
+ function add (c) {
+ cls.push(baseCSSPrefix + c);
+ }
+
+ //Let's keep this human readable!
+ if (Ext.isIE) {
+ add('ie');
+
+ // very often CSS needs to do checks like "IE7+" or "IE6 or 7". To help
+ // reduce the clutter (since CSS/SCSS cannot do these tests), we add some
+ // additional classes:
+ //
+ // x-ie7p : IE7+ : 7 <= ieVer
+ // x-ie7m : IE7- : ieVer <= 7
+ // x-ie8p : IE8+ : 8 <= ieVer
+ // x-ie8m : IE8- : ieVer <= 8
+ // x-ie9p : IE9+ : 9 <= ieVer
+ // x-ie78 : IE7 or 8 : 7 <= ieVer <= 8
+ //
+ if (Ext.isIE6) {
+ add('ie6');
+ } else { // ignore pre-IE6 :)
+ add('ie7p');
+
+ if (Ext.isIE7) {
+ add('ie7');
+ } else {
+ add('ie8p');
+
+ if (Ext.isIE8) {
+ add('ie8');
+ } else {
+ add('ie9p');
+
+ if (Ext.isIE9) {
+ add('ie9');
+ }
+ }
+ }
+ }
+
+ if (Ext.isIE6 || Ext.isIE7) {
+ add('ie7m');
+ }
+ if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
+ add('ie8m');
+ }
+ if (Ext.isIE7 || Ext.isIE8) {
+ add('ie78');
+ }
+ }
+ if (Ext.isGecko) {
+ add('gecko');
+ if (Ext.isGecko3) {
+ add('gecko3');
+ }
+ if (Ext.isGecko4) {
+ add('gecko4');
+ }
+ if (Ext.isGecko5) {
+ add('gecko5');
+ }
+ }
+ if (Ext.isOpera) {
+ add('opera');
+ }
+ if (Ext.isWebKit) {
+ add('webkit');
+ }
+ if (Ext.isSafari) {
+ add('safari');
+ if (Ext.isSafari2) {
+ add('safari2');
+ }
+ if (Ext.isSafari3) {
+ add('safari3');
+ }
+ if (Ext.isSafari4) {
+ add('safari4');
+ }
+ if (Ext.isSafari5) {
+ add('safari5');
+ }
+ if (Ext.isSafari5_0) {
+ add('safari5_0')
+ }
+ }
+ if (Ext.isChrome) {
+ add('chrome');
+ }
+ if (Ext.isMac) {
+ add('mac');
+ }
+ if (Ext.isLinux) {
+ add('linux');
+ }
+ if (!supportsBR) {
+ add('nbr');
+ }
+ if (!supportsLG) {
+ add('nlg');
+ }
+
+ // If we are not globally resetting scope, but just resetting it in a wrapper around
+ // serarately rendered widgets, then create a common reset element for use when creating
+ // measurable elements. Using a common DomHelper spec.
+ if (Ext.scopeResetCSS) {
+
+ // Create Ext.resetElementSpec for use in Renderable when wrapping top level Components.
+ resetElementSpec = Ext.resetElementSpec = {
+ cls: baseCSSPrefix + 'reset'
+ };
+
+ if (!supportsLG) {
+ resetCls.push(baseCSSPrefix + 'nlg');
+ }
+
+ if (!supportsBR) {
+ resetCls.push(baseCSSPrefix + 'nbr');
+ }
+
+ if (resetCls.length) {
+ resetElementSpec.cn = {
+ cls: resetCls.join(' ')
+ };
+ }
+
+ Ext.resetElement = Ext.getBody().createChild(resetElementSpec);
+ if (resetCls.length) {
+ Ext.resetElement = Ext.get(Ext.resetElement.dom.firstChild);
+ }
+ }
+ // Otherwise, the common reset element is the document body
+ else {
+ Ext.resetElement = Ext.getBody();
+ add('reset');
+ }
+
+ // add to the parent to allow for selectors x-strict x-border-box, also set the isBorderBox property correctly
+ if (html) {
+ if (Ext.isStrict && (Ext.isIE6 || Ext.isIE7)) {
+ Ext.isBorderBox = false;
+ }
+ else {
+ Ext.isBorderBox = true;
+ }
+
+ if(Ext.isBorderBox) {
+ htmlCls.push(baseCSSPrefix + 'border-box');
+ }
+ if (Ext.isStrict) {
+ htmlCls.push(baseCSSPrefix + 'strict');
+ } else {
+ htmlCls.push(baseCSSPrefix + 'quirks');
+ }
+ Ext.fly(html, '_internal').addCls(htmlCls);
+ }
+
+ Ext.fly(bd, '_internal').addCls(cls);
+ return true;
+ };
+
+ Ext.apply(EventManager, {
+ /**
+ * Check if we have bound our global onReady listener
+ * @private
+ */
+ hasBoundOnReady: false,
+
+ /**
+ * Check if fireDocReady has been called
+ * @private
+ */
+ hasFiredReady: false,
+
+ /**
+ * Additionally, allow the 'DOM' listener thread to complete (usually desirable with mobWebkit, Gecko)
+ * before firing the entire onReady chain (high stack load on Loader) by specifying a delay value
+ * @default 1ms
+ * @private
+ */
+ deferReadyEvent : 1,
+
+ /*
+ * diags: a list of event names passed to onReadyEvent (in chron order)
+ * @private
+ */
+ onReadyChain : [],
+
+ /**
+ * Holds references to any onReady functions
+ * @private
+ */
+ readyEvent:
+ (function () {
+ var event = new Ext.util.Event();
+ event.fire = function () {
+ Ext._beforeReadyTime = Ext._beforeReadyTime || new Date().getTime();
+ event.self.prototype.fire.apply(event, arguments);
+ Ext._afterReadytime = new Date().getTime();
+ };
+ return event;
+ }()),
+
+ /**
+ * Fires when a DOM event handler finishes its run, just before returning to browser control.
+ * This can be useful for performing cleanup, or upfdate tasks which need to happen only
+ * after all code in an event handler has been run, but which should not be executed in a timer
+ * due to the intervening browser reflow/repaint which would take place.
+ *
+ */
+ idleEvent: new Ext.util.Event(),
+
+ /**
+ * detects whether the EventManager has been placed in a paused state for synchronization
+ * with external debugging / perf tools (PageAnalyzer)
+ * @private
+ */
+ isReadyPaused: function(){
+ return (/[?&]ext-pauseReadyFire\b/i.test(location.search) && !Ext._continueFireReady);
+ },
+
+ /**
+ * Binds the appropriate browser event for checking if the DOM has loaded.
+ * @private
+ */
+ bindReadyEvent: function() {
+ if (EventManager.hasBoundOnReady) {
+ return;
+ }
+
+ // Test scenario where Core is dynamically loaded AFTER window.load
+ if ( doc.readyState == 'complete' ) { // Firefox4+ got support for this state, others already do.
+ EventManager.onReadyEvent({
+ type: doc.readyState || 'body'
+ });
+ } else {
+ document.addEventListener('DOMContentLoaded', EventManager.onReadyEvent, false);
+ window.addEventListener('load', EventManager.onReadyEvent, false);
+ EventManager.hasBoundOnReady = true;
+ }
+ },
+
+ onReadyEvent : function(e) {
+ if (e && e.type) {
+ EventManager.onReadyChain.push(e.type);
+ }
+
+ if (EventManager.hasBoundOnReady) {
+ document.removeEventListener('DOMContentLoaded', EventManager.onReadyEvent, false);
+ window.removeEventListener('load', EventManager.onReadyEvent, false);
+ }
+
+ if (!Ext.isReady) {
+ EventManager.fireDocReady();
+ }
+ },
+
+ /**
+ * We know the document is loaded, so trigger any onReady events.
+ * @private
+ */
+ fireDocReady: function() {
+ if (!Ext.isReady) {
+ Ext._readyTime = new Date().getTime();
+ Ext.isReady = true;
+
+ Ext.supports.init();
+ EventManager.onWindowUnload();
+ EventManager.readyEvent.onReadyChain = EventManager.onReadyChain; //diags report
+
+ if (Ext.isNumber(EventManager.deferReadyEvent)) {
+ Ext.Function.defer(EventManager.fireReadyEvent, EventManager.deferReadyEvent);
+ EventManager.hasDocReadyTimer = true;
+ } else {
+ EventManager.fireReadyEvent();
+ }
+ }
+ },
+
+ /**
+ * Fires the ready event
+ * @private
+ */
+ fireReadyEvent: function(){
+ var readyEvent = EventManager.readyEvent;
+
+ // Unset the timer flag here since other onReady events may be
+ // added during the fire() call and we don't want to block them
+ EventManager.hasDocReadyTimer = false;
+ EventManager.isFiring = true;
+
+ // Ready events are all single: true, if we get to the end
+ // & there are more listeners, it means they were added
+ // inside some other ready event
+ while (readyEvent.listeners.length && !EventManager.isReadyPaused()) {
+ readyEvent.fire();
+ }
+ EventManager.isFiring = false;
+ EventManager.hasFiredReady = true;
+ },
+
+ /**
+ * Adds a listener to be notified when the document is ready (before onload and before images are loaded).
+ *
+ * @param {Function} fn The method the event invokes.
+ * @param {Object} [scope] The scope (`this` reference) in which the handler function executes.
+ * Defaults to the browser window.
+ * @param {Object} [options] Options object as passed to {@link Ext.Element#addListener}.
+ */
+ onDocumentReady: function(fn, scope, options) {
+ options = options || {};
+ // force single, only ever fire it once
+ options.single = true;
+ EventManager.readyEvent.addListener(fn, scope, options);
+
+ // If we're in the middle of firing, or we have a deferred timer
+ // pending, drop out since the event will be fired later
+ if (!(EventManager.isFiring || EventManager.hasDocReadyTimer)) {
+ if (Ext.isReady) {
+ EventManager.fireReadyEvent();
+ } else {
+ EventManager.bindReadyEvent();
+ }
+ }
+ },
+
+ // --------------------- event binding ---------------------
+
+ /**
+ * Contains a list of all document mouse downs, so we can ensure they fire even when stopEvent is called.
+ * @private
+ */
+ stoppedMouseDownEvent: new Ext.util.Event(),
+
+ /**
+ * Options to parse for the 4th argument to addListener.
+ * @private
+ */
+ propRe: /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|freezeEvent)$/,
+
+ /**
+ * Get the id of the element. If one has not been assigned, automatically assign it.
+ * @param {HTMLElement/Ext.Element} element The element to get the id for.
+ * @return {String} id
+ */
+ getId : function(element) {
+ var id;
+
+ element = Ext.getDom(element);
+
+ if (element === doc || element === win) {
+ id = element === doc ? Ext.documentId : Ext.windowId;
+ }
+ else {
+ id = Ext.id(element);
+ }
+
+ if (!Ext.cache[id]) {
+ Ext.addCacheEntry(id, null, element);
+ }
+
+ return id;
+ },
+
+ /**
+ * Convert a "config style" listener into a set of flat arguments so they can be passed to addListener
+ * @private
+ * @param {Object} element The element the event is for
+ * @param {Object} event The event configuration
+ * @param {Object} isRemove True if a removal should be performed, otherwise an add will be done.
+ */
+ prepareListenerConfig: function(element, config, isRemove) {
+ var propRe = EventManager.propRe,
+ key, value, args;
+
+ // loop over all the keys in the object
+ for (key in config) {
+ if (config.hasOwnProperty(key)) {
+ // if the key is something else then an event option
+ if (!propRe.test(key)) {
+ value = config[key];
+ // if the value is a function it must be something like click: function() {}, scope: this
+ // which means that there might be multiple event listeners with shared options
+ if (typeof value == 'function') {
+ // shared options
+ args = [element, key, value, config.scope, config];
+ } else {
+ // if its not a function, it must be an object like click: {fn: function() {}, scope: this}
+ args = [element, key, value.fn, value.scope, value];
+ }
+
+ if (isRemove) {
+ EventManager.removeListener.apply(EventManager, args);
+ } else {
+ EventManager.addListener.apply(EventManager, args);
+ }
+ }
+ }
+ }
+ },
+
+ mouseEnterLeaveRe: /mouseenter|mouseleave/,
+
+ /**
+ * Normalize cross browser event differences
+ * @private
+ * @param {Object} eventName The event name
+ * @param {Object} fn The function to execute
+ * @return {Object} The new event name/function
+ */
+ normalizeEvent: function(eventName, fn) {
+ if (EventManager.mouseEnterLeaveRe.test(eventName) && !Ext.supports.MouseEnterLeave) {
+ if (fn) {
+ fn = Ext.Function.createInterceptor(fn, EventManager.contains);
+ }
+ eventName = eventName == 'mouseenter' ? 'mouseover' : 'mouseout';
+ } else if (eventName == 'mousewheel' && !Ext.supports.MouseWheel && !Ext.isOpera) {
+ eventName = 'DOMMouseScroll';
+ }
+ return {
+ eventName: eventName,
+ fn: fn
+ };
+ },
+
+ /**
+ * Checks whether the event's relatedTarget is contained inside (or is ) the element.
+ * @private
+ * @param {Object} event
+ */
+ contains: function(event) {
+ var parent = event.browserEvent.currentTarget,
+ child = EventManager.getRelatedTarget(event);
+
+ if (parent && parent.firstChild) {
+ while (child) {
+ if (child === parent) {
+ return false;
+ }
+ child = child.parentNode;
+ if (child && (child.nodeType != 1)) {
+ child = null;
+ }
+ }
+ }
+ return true;
+ },
+
+ /**
+ * Appends an event handler to an element. The shorthand version {@link #on} is equivalent. Typically you will
+ * use {@link Ext.Element#addListener} directly on an Element in favor of calling this version.
+ * @param {String/HTMLElement} el The html element or id to assign the event handler to.
+ * @param {String} eventName The name of the event to listen for.
+ * @param {Function} handler The handler function the event invokes. This function is passed
+ * the following parameters:
+ * evt : EventObjectThe {@link Ext.EventObject EventObject} describing the event.
+ * t : ElementThe {@link Ext.Element Element} which was the target of the event.
+ * Note that this may be filtered by using the delegate option.
+ * o : ObjectThe options object from the addListener call.
+ *
+ * @param {Object} scope (optional) The scope (this reference) in which the handler function is executed. Defaults to the Element .
+ * @param {Object} options (optional) An object containing handler configuration properties.
+ * This may contain any of the following properties:
+ * scope : ObjectThe scope (this reference) in which the handler function is executed. Defaults to the Element .
+ * delegate : StringA simple selector to filter the target or look for a descendant of the target
+ * stopEvent : BooleanTrue to stop the event. That is stop propagation, and prevent the default action.
+ * preventDefault : BooleanTrue to prevent the default action
+ * stopPropagation : BooleanTrue to prevent event propagation
+ * normalized : BooleanFalse to pass a browser event to the handler function instead of an Ext.EventObject
+ * delay : NumberThe number of milliseconds to delay the invocation of the handler after te event fires.
+ * single : BooleanTrue to add a handler to handle just the next firing of the event, and then remove itself.
+ * buffer : NumberCauses the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
+ * by the specified number of milliseconds. If the event fires again within that time, the original
+ * handler is not invoked, but the new handler is scheduled in its place.
+ * target : ElementOnly call the handler if the event was fired on the target Element, not if the event was bubbled up from a child node.
+ *
+ * See {@link Ext.Element#addListener} for examples of how to use these options.
+ */
+ addListener: function(element, eventName, fn, scope, options) {
+ // Check if we've been passed a "config style" event.
+ if (typeof eventName !== 'string') {
+ EventManager.prepareListenerConfig(element, eventName);
+ return;
+ }
+
+ var dom = element.dom || Ext.getDom(element),
+ bind, wrap;
+
+ if (!fn) {
+ Ext.Error.raise({
+ sourceClass: 'Ext.EventManager',
+ sourceMethod: 'addListener',
+ targetElement: element,
+ eventName: eventName,
+ msg: 'Error adding "' + eventName + '\" listener. The handler function is undefined.'
+ });
+ }
+
+ // create the wrapper function
+ options = options || {};
+
+ bind = EventManager.normalizeEvent(eventName, fn);
+ wrap = EventManager.createListenerWrap(dom, eventName, bind.fn, scope, options);
+
+ if (dom.attachEvent) {
+ dom.attachEvent('on' + bind.eventName, wrap);
+ } else {
+ dom.addEventListener(bind.eventName, wrap, options.capture || false);
+ }
+
+ if (dom == doc && eventName == 'mousedown') {
+ EventManager.stoppedMouseDownEvent.addListener(wrap);
+ }
+
+ // add all required data into the event cache
+ EventManager.getEventListenerCache(element.dom ? element : dom, eventName).push({
+ fn: fn,
+ wrap: wrap,
+ scope: scope
+ });
+ },
+
+ /**
+ * Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically
+ * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
+ * @param {String/HTMLElement} el The id or html element from which to remove the listener.
+ * @param {String} eventName The name of the event.
+ * @param {Function} fn The handler function to remove. This must be a reference to the function passed into the {@link #addListener} call.
+ * @param {Object} scope If a scope (this reference) was specified when the listener was added,
+ * then this must refer to the same object.
+ */
+ removeListener : function(element, eventName, fn, scope) {
+ // handle our listener config object syntax
+ if (typeof eventName !== 'string') {
+ EventManager.prepareListenerConfig(element, eventName, true);
+ return;
+ }
+
+ var dom = Ext.getDom(element),
+ el = element.dom ? element : Ext.get(dom),
+ cache = EventManager.getEventListenerCache(el, eventName),
+ bindName = EventManager.normalizeEvent(eventName).eventName,
+ i = cache.length, j,
+ listener, wrap, tasks;
+
+
+ while (i--) {
+ listener = cache[i];
+
+ if (listener && (!fn || listener.fn == fn) && (!scope || listener.scope === scope)) {
+ wrap = listener.wrap;
+
+ // clear buffered calls
+ if (wrap.task) {
+ clearTimeout(wrap.task);
+ delete wrap.task;
+ }
+
+ // clear delayed calls
+ j = wrap.tasks && wrap.tasks.length;
+ if (j) {
+ while (j--) {
+ clearTimeout(wrap.tasks[j]);
+ }
+ delete wrap.tasks;
+ }
+
+ if (dom.detachEvent) {
+ dom.detachEvent('on' + bindName, wrap);
+ } else {
+ dom.removeEventListener(bindName, wrap, false);
+ }
+
+ if (wrap && dom == doc && eventName == 'mousedown') {
+ EventManager.stoppedMouseDownEvent.removeListener(wrap);
+ }
+
+ // remove listener from cache
+ Ext.Array.erase(cache, i, 1);
+ }
+ }
+ },
+
+ /**
+ * Removes all event handers from an element. Typically you will use {@link Ext.Element#removeAllListeners}
+ * directly on an Element in favor of calling this version.
+ * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
+ */
+ removeAll : function(element) {
+ var el = element.dom ? element : Ext.get(element),
+ cache, events, eventName;
+
+ if (!el) {
+ return;
+ }
+ cache = (el.$cache || el.getCache());
+ events = cache.events;
+
+ for (eventName in events) {
+ if (events.hasOwnProperty(eventName)) {
+ EventManager.removeListener(el, eventName);
+ }
+ }
+ cache.events = {};
+ },
+
+ /**
+ * Recursively removes all previous added listeners from an element and its children. Typically you will use {@link Ext.Element#purgeAllListeners}
+ * directly on an Element in favor of calling this version.
+ * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
+ * @param {String} eventName (optional) The name of the event.
+ */
+ purgeElement : function(element, eventName) {
+ var dom = Ext.getDom(element),
+ i = 0, len;
+
+ if (eventName) {
+ EventManager.removeListener(element, eventName);
+ }
+ else {
+ EventManager.removeAll(element);
+ }
+
+ if (dom && dom.childNodes) {
+ for (len = element.childNodes.length; i < len; i++) {
+ EventManager.purgeElement(element.childNodes[i], eventName);
+ }
+ }
+ },
+
+ /**
+ * Create the wrapper function for the event
+ * @private
+ * @param {HTMLElement} dom The dom element
+ * @param {String} ename The event name
+ * @param {Function} fn The function to execute
+ * @param {Object} scope The scope to execute callback in
+ * @param {Object} options The options
+ * @return {Function} the wrapper function
+ */
+ createListenerWrap : function(dom, ename, fn, scope, options) {
+ options = options || {};
+
+ var f, gen, escapeRx = /\\/g, wrap = function(e, args) {
+ // Compile the implementation upon first firing
+ if (!gen) {
+ f = ['if(!' + Ext.name + ') {return;}'];
+
+ if(options.buffer || options.delay || options.freezeEvent) {
+ f.push('e = new X.EventObjectImpl(e, ' + (options.freezeEvent ? 'true' : 'false' ) + ');');
+ } else {
+ f.push('e = X.EventObject.setEvent(e);');
+ }
+
+ if (options.delegate) {
+ // double up '\' characters so escape sequences survive the
+ // string-literal translation
+ f.push('var result, t = e.getTarget("' + (options.delegate + '').replace(escapeRx, '\\\\') + '", this);');
+ f.push('if(!t) {return;}');
+ } else {
+ f.push('var t = e.target, result;');
+ }
+
+ if (options.target) {
+ f.push('if(e.target !== options.target) {return;}');
+ }
+
+ if(options.stopEvent) {
+ f.push('e.stopEvent();');
+ } else {
+ if(options.preventDefault) {
+ f.push('e.preventDefault();');
+ }
+ if(options.stopPropagation) {
+ f.push('e.stopPropagation();');
+ }
+ }
+
+ if(options.normalized === false) {
+ f.push('e = e.browserEvent;');
+ }
+
+ if(options.buffer) {
+ f.push('(wrap.task && clearTimeout(wrap.task));');
+ f.push('wrap.task = setTimeout(function() {');
+ }
+
+ if(options.delay) {
+ f.push('wrap.tasks = wrap.tasks || [];');
+ f.push('wrap.tasks.push(setTimeout(function() {');
+ }
+
+ // finally call the actual handler fn
+ f.push('result = fn.call(scope || dom, e, t, options);');
+
+ if(options.single) {
+ f.push('evtMgr.removeListener(dom, ename, fn, scope);');
+ }
+
+ // Fire the global idle event for all events except mousemove which is too common, and
+ // fires too frequently and fast to be use in tiggering onIdle processing.
+ if (ename !== 'mousemove') {
+ f.push('if (evtMgr.idleEvent.listeners.length) {');
+ f.push('evtMgr.idleEvent.fire();');
+ f.push('}');
+ }
+
+ if(options.delay) {
+ f.push('}, ' + options.delay + '));');
+ }
+
+ if(options.buffer) {
+ f.push('}, ' + options.buffer + ');');
+ }
+ f.push('return result;')
+
+ gen = Ext.cacheableFunctionFactory('e', 'options', 'fn', 'scope', 'ename', 'dom', 'wrap', 'args', 'X', 'evtMgr', f.join('\n'));
+ }
+
+ return gen.call(dom, e, options, fn, scope, ename, dom, wrap, args, Ext, EventManager);
+ };
+ return wrap;
+ },
+
+ /**
+ * Get the event cache for a particular element for a particular event
+ * @private
+ * @param {HTMLElement} element The element
+ * @param {Object} eventName The event name
+ * @return {Array} The events for the element
+ */
+ getEventListenerCache : function(element, eventName) {
+ var elementCache, eventCache;
+ if (!element) {
+ return [];
+ }
+
+ if (element.$cache) {
+ elementCache = element.$cache;
+ } else {
+ // getId will populate the cache for this element if it isn't already present
+ elementCache = Ext.cache[EventManager.getId(element)];
+ }
+ eventCache = elementCache.events || (elementCache.events = {});
+
+ return eventCache[eventName] || (eventCache[eventName] = []);
+ },
+
+ // --------------------- utility methods ---------------------
+ mouseLeaveRe: /(mouseout|mouseleave)/,
+ mouseEnterRe: /(mouseover|mouseenter)/,
+
+ /**
+ * Stop the event (preventDefault and stopPropagation)
+ * @param {Event} The event to stop
+ */
+ stopEvent: function(event) {
+ EventManager.stopPropagation(event);
+ EventManager.preventDefault(event);
+ },
+
+ /**
+ * Cancels bubbling of the event.
+ * @param {Event} The event to stop bubbling.
+ */
+ stopPropagation: function(event) {
+ event = event.browserEvent || event;
+ if (event.stopPropagation) {
+ event.stopPropagation();
+ } else {
+ event.cancelBubble = true;
+ }
+ },
+
+ /**
+ * Prevents the browsers default handling of the event.
+ * @param {Event} The event to prevent the default
+ */
+ preventDefault: function(event) {
+ event = event.browserEvent || event;
+ if (event.preventDefault) {
+ event.preventDefault();
+ } else {
+ event.returnValue = false;
+ // Some keys events require setting the keyCode to -1 to be prevented
+ try {
+ // all ctrl + X and F1 -> F12
+ if (event.ctrlKey || event.keyCode > 111 && event.keyCode < 124) {
+ event.keyCode = -1;
+ }
+ } catch (e) {
+ // see this outdated document http://support.microsoft.com/kb/934364/en-us for more info
+ }
+ }
+ },
+
+ /**
+ * Gets the related target from the event.
+ * @param {Object} event The event
+ * @return {HTMLElement} The related target.
+ */
+ getRelatedTarget: function(event) {
+ event = event.browserEvent || event;
+ var target = event.relatedTarget;
+ if (!target) {
+ if (EventManager.mouseLeaveRe.test(event.type)) {
+ target = event.toElement;
+ } else if (EventManager.mouseEnterRe.test(event.type)) {
+ target = event.fromElement;
+ }
+ }
+ return EventManager.resolveTextNode(target);
+ },
+
+ /**
+ * Gets the x coordinate from the event
+ * @param {Object} event The event
+ * @return {Number} The x coordinate
+ */
+ getPageX: function(event) {
+ return EventManager.getPageXY(event)[0];
+ },
+
+ /**
+ * Gets the y coordinate from the event
+ * @param {Object} event The event
+ * @return {Number} The y coordinate
+ */
+ getPageY: function(event) {
+ return EventManager.getPageXY(event)[1];
+ },
+
+ /**
+ * Gets the x & y coordinate from the event
+ * @param {Object} event The event
+ * @return {Number[]} The x/y coordinate
+ */
+ getPageXY: function(event) {
+ event = event.browserEvent || event;
+ var x = event.pageX,
+ y = event.pageY,
+ docEl = doc.documentElement,
+ body = doc.body;
+
+ // pageX/pageY not available (undefined, not null), use clientX/clientY instead
+ if (!x && x !== 0) {
+ x = event.clientX + (docEl && docEl.scrollLeft || body && body.scrollLeft || 0) - (docEl && docEl.clientLeft || body && body.clientLeft || 0);
+ y = event.clientY + (docEl && docEl.scrollTop || body && body.scrollTop || 0) - (docEl && docEl.clientTop || body && body.clientTop || 0);
+ }
+ return [x, y];
+ },
+
+ /**
+ * Gets the target of the event.
+ * @param {Object} event The event
+ * @return {HTMLElement} target
+ */
+ getTarget: function(event) {
+ event = event.browserEvent || event;
+ return EventManager.resolveTextNode(event.target || event.srcElement);
+ },
+
+ // technically no need to browser sniff this, however it makes
+ // no sense to check this every time, for every event, whether
+ // the string is equal.
+ /**
+ * Resolve any text nodes accounting for browser differences.
+ * @private
+ * @param {HTMLElement} node The node
+ * @return {HTMLElement} The resolved node
+ */
+ resolveTextNode: Ext.isGecko ?
+ function(node) {
+ if (!node) {
+ return;
+ }
+ // work around firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=101197
+ var s = HTMLElement.prototype.toString.call(node);
+ if (s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]') {
+ return;
+ }
+ return node.nodeType == 3 ? node.parentNode: node;
+ }: function(node) {
+ return node && node.nodeType == 3 ? node.parentNode: node;
+ },
+
+ // --------------------- custom event binding ---------------------
+
+ // Keep track of the current width/height
+ curWidth: 0,
+ curHeight: 0,
+
+ /**
+ * Adds a listener to be notified when the browser window is resized and provides resize event buffering (100 milliseconds),
+ * passes new viewport width and height to handlers.
+ * @param {Function} fn The handler function the window resize event invokes.
+ * @param {Object} scope The scope (this reference) in which the handler function executes. Defaults to the browser window.
+ * @param {Boolean} options Options object as passed to {@link Ext.Element#addListener}
+ */
+ onWindowResize: function(fn, scope, options) {
+ var resize = EventManager.resizeEvent;
+
+ if (!resize) {
+ EventManager.resizeEvent = resize = new Ext.util.Event();
+ EventManager.on(win, 'resize', EventManager.fireResize, null, {buffer: 100});
+ }
+ resize.addListener(fn, scope, options);
+ },
+
+ /**
+ * Fire the resize event.
+ * @private
+ */
+ fireResize: function() {
+ var w = Ext.Element.getViewWidth(),
+ h = Ext.Element.getViewHeight();
+
+ //whacky problem in IE where the resize event will sometimes fire even though the w/h are the same.
+ if (EventManager.curHeight != h || EventManager.curWidth != w) {
+ EventManager.curHeight = h;
+ EventManager.curWidth = w;
+ EventManager.resizeEvent.fire(w, h);
+ }
+ },
+
+ /**
+ * Removes the passed window resize listener.
+ * @param {Function} fn The method the event invokes
+ * @param {Object} scope The scope of handler
+ */
+ removeResizeListener: function(fn, scope) {
+ var resize = EventManager.resizeEvent;
+ if (resize) {
+ resize.removeListener(fn, scope);
+ }
+ },
+
+ /**
+ * Adds a listener to be notified when the browser window is unloaded.
+ * @param {Function} fn The handler function the window unload event invokes.
+ * @param {Object} scope The scope (this reference) in which the handler function executes. Defaults to the browser window.
+ * @param {Boolean} options Options object as passed to {@link Ext.Element#addListener}
+ */
+ onWindowUnload: function(fn, scope, options) {
+ var unload = EventManager.unloadEvent;
+
+ if (!unload) {
+ EventManager.unloadEvent = unload = new Ext.util.Event();
+ EventManager.addListener(win, 'unload', EventManager.fireUnload);
+ }
+ if (fn) {
+ unload.addListener(fn, scope, options);
+ }
+ },
+
+ /**
+ * Fires the unload event for items bound with onWindowUnload
+ * @private
+ */
+ fireUnload: function() {
+ // wrap in a try catch, could have some problems during unload
+ try {
+ // relinquish references.
+ doc = win = undefined;
+
+ var gridviews, i, ln,
+ el, cache;
+
+ EventManager.unloadEvent.fire();
+ // Work around FF3 remembering the last scroll position when refreshing the grid and then losing grid view
+ if (Ext.isGecko3) {
+ gridviews = Ext.ComponentQuery.query('gridview');
+ i = 0;
+ ln = gridviews.length;
+ for (; i < ln; i++) {
+ gridviews[i].scrollToTop();
+ }
+ }
+ // Purge all elements in the cache
+ cache = Ext.cache;
+
+ for (el in cache) {
+ if (cache.hasOwnProperty(el)) {
+ EventManager.removeAll(el);
+ }
+ }
+ } catch(e) {
+ }
+ },
+
+ /**
+ * Removes the passed window unload listener.
+ * @param {Function} fn The method the event invokes
+ * @param {Object} scope The scope of handler
+ */
+ removeUnloadListener: function(fn, scope) {
+ var unload = EventManager.unloadEvent;
+ if (unload) {
+ unload.removeListener(fn, scope);
+ }
+ },
+
+ /**
+ * note 1: IE fires ONLY the keydown event on specialkey autorepeat
+ * note 2: Safari < 3.1, Gecko (Mac/Linux) & Opera fire only the keypress event on specialkey autorepeat
+ * (research done by Jan Wolter at http://unixpapa.com/js/key.html)
+ * @private
+ */
+ useKeyDown: Ext.isWebKit ?
+ parseInt(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1], 10) >= 525 :
+ !((Ext.isGecko && !Ext.isWindows) || Ext.isOpera),
+
+ /**
+ * Indicates which event to use for getting key presses.
+ * @return {String} The appropriate event name.
+ */
+ getKeyEvent: function() {
+ return EventManager.useKeyDown ? 'keydown' : 'keypress';
+ }
+ });
+
+ // route "< ie9-Standards" to a legacy IE onReady implementation
+ if(!('addEventListener' in document) && document.attachEvent) {
+ Ext.apply( EventManager, {
+ /* Customized implementation for Legacy IE. The default implementation is configured for use
+ * with all other 'standards compliant' agents.
+ * References: http://javascript.nwbox.com/IEContentLoaded/
+ * licensed courtesy of http://developer.yahoo.com/yui/license.html
+ */
+
+ /**
+ * This strategy has minimal benefits for Sencha solutions that build themselves (ie. minimal initial page markup).
+ * However, progressively-enhanced pages (with image content and/or embedded frames) will benefit the most from it.
+ * Browser timer resolution is too poor to ensure a doScroll check more than once on a page loaded with minimal
+ * assets (the readystatechange event 'complete' usually beats the doScroll timer on a 'lightly-loaded' initial document).
+ */
+ pollScroll : function() {
+ var scrollable = true;
+
+ try {
+ document.documentElement.doScroll('left');
+ } catch(e) {
+ scrollable = false;
+ }
+
+ // on IE8, when running within an iFrame, document.body is not immediately available
+ if (scrollable && document.body) {
+ EventManager.onReadyEvent({
+ type:'doScroll'
+ });
+ } else {
+ /*
+ * minimize thrashing --
+ * adjusted for setTimeout's close-to-minimums (not too low),
+ * as this method SHOULD always be called once initially
+ */
+ EventManager.scrollTimeout = setTimeout(EventManager.pollScroll, 20);
+ }
+
+ return scrollable;
+ },
+
+ /**
+ * Timer for doScroll polling
+ * @private
+ */
+ scrollTimeout: null,
+
+ /* @private
+ */
+ readyStatesRe : /complete/i,
+
+ /* @private
+ */
+ checkReadyState: function() {
+ var state = document.readyState;
+
+ if (EventManager.readyStatesRe.test(state)) {
+ EventManager.onReadyEvent({
+ type: state
+ });
+ }
+ },
+
+ bindReadyEvent: function() {
+ var topContext = true;
+
+ if (EventManager.hasBoundOnReady) {
+ return;
+ }
+
+ //are we in an IFRAME? (doScroll ineffective here)
+ try {
+ topContext = window.frameElement === undefined;
+ } catch(e) {
+ // If we throw an exception, it means we're probably getting access denied,
+ // which means we're in an iframe cross domain.
+ topContext = false;
+ }
+
+ if (!topContext || !doc.documentElement.doScroll) {
+ EventManager.pollScroll = Ext.emptyFn; //then noop this test altogether
+ }
+
+ // starts doScroll polling if necessary
+ if (EventManager.pollScroll() === true) {
+ return;
+ }
+
+ // Core is loaded AFTER initial document write/load ?
+ if (doc.readyState == 'complete' ) {
+ EventManager.onReadyEvent({type: 'already ' + (doc.readyState || 'body') });
+ } else {
+ doc.attachEvent('onreadystatechange', EventManager.checkReadyState);
+ window.attachEvent('onload', EventManager.onReadyEvent);
+ EventManager.hasBoundOnReady = true;
+ }
+ },
+
+ onReadyEvent : function(e) {
+ if (e && e.type) {
+ EventManager.onReadyChain.push(e.type);
+ }
+
+ if (EventManager.hasBoundOnReady) {
+ document.detachEvent('onreadystatechange', EventManager.checkReadyState);
+ window.detachEvent('onload', EventManager.onReadyEvent);
+ }
+
+ if (Ext.isNumber(EventManager.scrollTimeout)) {
+ clearTimeout(EventManager.scrollTimeout);
+ delete EventManager.scrollTimeout;
+ }
+
+ if (!Ext.isReady) {
+ EventManager.fireDocReady();
+ }
+ },
+
+ //diags: a list of event types passed to onReadyEvent (in chron order)
+ onReadyChain : []
+ });
+ }
+
+
+ /**
+ * Alias for {@link Ext.Loader#onReady Ext.Loader.onReady} with withDomReady set to true
+ * @member Ext
+ * @method onReady
+ */
+ Ext.onReady = function(fn, scope, options) {
+ Ext.Loader.onReady(fn, scope, true, options);
+ };
+
+ /**
+ * Alias for {@link Ext.EventManager#onDocumentReady Ext.EventManager.onDocumentReady}
+ * @member Ext
+ * @method onDocumentReady
+ */
+ Ext.onDocumentReady = EventManager.onDocumentReady;
+
+ /**
+ * Alias for {@link Ext.EventManager#addListener Ext.EventManager.addListener}
+ * @member Ext.EventManager
+ * @method on
+ */
+ EventManager.on = EventManager.addListener;
+
+ /**
+ * Alias for {@link Ext.EventManager#removeListener Ext.EventManager.removeListener}
+ * @member Ext.EventManager
+ * @method un
+ */
+ EventManager.un = EventManager.removeListener;
+
+ Ext.onReady(initExtCss);
+};
+
+//@tag dom,core
+//@require EventManager.js
+//@define Ext.EventObject
+
+/**
+ * @class Ext.EventObject
+
+Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject
+wraps the browser's native event-object normalizing cross-browser differences,
+such as which mouse button is clicked, keys pressed, mechanisms to stop
+event-propagation along with a method to prevent default actions from taking place.
+
+For example:
+
+ function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
+ e.preventDefault();
+ var target = e.getTarget(); // same as t (the target HTMLElement)
+ ...
+ }
+
+ var myDiv = {@link Ext#get Ext.get}("myDiv"); // get reference to an {@link Ext.Element}
+ myDiv.on( // 'on' is shorthand for addListener
+ "click", // perform an action on click of myDiv
+ handleClick // reference to the action handler
+ );
+
+ // other methods to do the same:
+ Ext.EventManager.on("myDiv", 'click', handleClick);
+ Ext.EventManager.addListener("myDiv", 'click', handleClick);
+
+ * @singleton
+ * @markdown
+ */
+Ext.define('Ext.EventObjectImpl', {
+ uses: ['Ext.util.Point'],
+
+ /** Key constant @type Number */
+ BACKSPACE: 8,
+ /** Key constant @type Number */
+ TAB: 9,
+ /** Key constant @type Number */
+ NUM_CENTER: 12,
+ /** Key constant @type Number */
+ ENTER: 13,
+ /** Key constant @type Number */
+ RETURN: 13,
+ /** Key constant @type Number */
+ SHIFT: 16,
+ /** Key constant @type Number */
+ CTRL: 17,
+ /** Key constant @type Number */
+ ALT: 18,
+ /** Key constant @type Number */
+ PAUSE: 19,
+ /** Key constant @type Number */
+ CAPS_LOCK: 20,
+ /** Key constant @type Number */
+ ESC: 27,
+ /** Key constant @type Number */
+ SPACE: 32,
+ /** Key constant @type Number */
+ PAGE_UP: 33,
+ /** Key constant @type Number */
+ PAGE_DOWN: 34,
+ /** Key constant @type Number */
+ END: 35,
+ /** Key constant @type Number */
+ HOME: 36,
+ /** Key constant @type Number */
+ LEFT: 37,
+ /** Key constant @type Number */
+ UP: 38,
+ /** Key constant @type Number */
+ RIGHT: 39,
+ /** Key constant @type Number */
+ DOWN: 40,
+ /** Key constant @type Number */
+ PRINT_SCREEN: 44,
+ /** Key constant @type Number */
+ INSERT: 45,
+ /** Key constant @type Number */
+ DELETE: 46,
+ /** Key constant @type Number */
+ ZERO: 48,
+ /** Key constant @type Number */
+ ONE: 49,
+ /** Key constant @type Number */
+ TWO: 50,
+ /** Key constant @type Number */
+ THREE: 51,
+ /** Key constant @type Number */
+ FOUR: 52,
+ /** Key constant @type Number */
+ FIVE: 53,
+ /** Key constant @type Number */
+ SIX: 54,
+ /** Key constant @type Number */
+ SEVEN: 55,
+ /** Key constant @type Number */
+ EIGHT: 56,
+ /** Key constant @type Number */
+ NINE: 57,
+ /** Key constant @type Number */
+ A: 65,
+ /** Key constant @type Number */
+ B: 66,
+ /** Key constant @type Number */
+ C: 67,
+ /** Key constant @type Number */
+ D: 68,
+ /** Key constant @type Number */
+ E: 69,
+ /** Key constant @type Number */
+ F: 70,
+ /** Key constant @type Number */
+ G: 71,
+ /** Key constant @type Number */
+ H: 72,
+ /** Key constant @type Number */
+ I: 73,
+ /** Key constant @type Number */
+ J: 74,
+ /** Key constant @type Number */
+ K: 75,
+ /** Key constant @type Number */
+ L: 76,
+ /** Key constant @type Number */
+ M: 77,
+ /** Key constant @type Number */
+ N: 78,
+ /** Key constant @type Number */
+ O: 79,
+ /** Key constant @type Number */
+ P: 80,
+ /** Key constant @type Number */
+ Q: 81,
+ /** Key constant @type Number */
+ R: 82,
+ /** Key constant @type Number */
+ S: 83,
+ /** Key constant @type Number */
+ T: 84,
+ /** Key constant @type Number */
+ U: 85,
+ /** Key constant @type Number */
+ V: 86,
+ /** Key constant @type Number */
+ W: 87,
+ /** Key constant @type Number */
+ X: 88,
+ /** Key constant @type Number */
+ Y: 89,
+ /** Key constant @type Number */
+ Z: 90,
+ /** Key constant @type Number */
+ CONTEXT_MENU: 93,
+ /** Key constant @type Number */
+ NUM_ZERO: 96,
+ /** Key constant @type Number */
+ NUM_ONE: 97,
+ /** Key constant @type Number */
+ NUM_TWO: 98,
+ /** Key constant @type Number */
+ NUM_THREE: 99,
+ /** Key constant @type Number */
+ NUM_FOUR: 100,
+ /** Key constant @type Number */
+ NUM_FIVE: 101,
+ /** Key constant @type Number */
+ NUM_SIX: 102,
+ /** Key constant @type Number */
+ NUM_SEVEN: 103,
+ /** Key constant @type Number */
+ NUM_EIGHT: 104,
+ /** Key constant @type Number */
+ NUM_NINE: 105,
+ /** Key constant @type Number */
+ NUM_MULTIPLY: 106,
+ /** Key constant @type Number */
+ NUM_PLUS: 107,
+ /** Key constant @type Number */
+ NUM_MINUS: 109,
+ /** Key constant @type Number */
+ NUM_PERIOD: 110,
+ /** Key constant @type Number */
+ NUM_DIVISION: 111,
+ /** Key constant @type Number */
+ F1: 112,
+ /** Key constant @type Number */
+ F2: 113,
+ /** Key constant @type Number */
+ F3: 114,
+ /** Key constant @type Number */
+ F4: 115,
+ /** Key constant @type Number */
+ F5: 116,
+ /** Key constant @type Number */
+ F6: 117,
+ /** Key constant @type Number */
+ F7: 118,
+ /** Key constant @type Number */
+ F8: 119,
+ /** Key constant @type Number */
+ F9: 120,
+ /** Key constant @type Number */
+ F10: 121,
+ /** Key constant @type Number */
+ F11: 122,
+ /** Key constant @type Number */
+ F12: 123,
+ /**
+ * The mouse wheel delta scaling factor. This value depends on browser version and OS and
+ * attempts to produce a similar scrolling experience across all platforms and browsers.
+ *
+ * To change this value:
+ *
+ * Ext.EventObjectImpl.prototype.WHEEL_SCALE = 72;
+ *
+ * @type Number
+ * @markdown
+ */
+ WHEEL_SCALE: (function () {
+ var scale;
+
+ if (Ext.isGecko) {
+ // Firefox uses 3 on all platforms
+ scale = 3;
+ } else if (Ext.isMac) {
+ // Continuous scrolling devices have momentum and produce much more scroll than
+ // discrete devices on the same OS and browser. To make things exciting, Safari
+ // (and not Chrome) changed from small values to 120 (like IE).
+
+ if (Ext.isSafari && Ext.webKitVersion >= 532.0) {
+ // Safari changed the scrolling factor to match IE (for details see
+ // https://bugs.webkit.org/show_bug.cgi?id=24368). The WebKit version where this
+ // change was introduced was 532.0
+ // Detailed discussion:
+ // https://bugs.webkit.org/show_bug.cgi?id=29601
+ // http://trac.webkit.org/browser/trunk/WebKit/chromium/src/mac/WebInputEventFactory.mm#L1063
+ scale = 120;
+ } else {
+ // MS optical wheel mouse produces multiples of 12 which is close enough
+ // to help tame the speed of the continuous mice...
+ scale = 12;
+ }
+
+ // Momentum scrolling produces very fast scrolling, so increase the scale factor
+ // to help produce similar results cross platform. This could be even larger and
+ // it would help those mice, but other mice would become almost unusable as a
+ // result (since we cannot tell which device type is in use).
+ scale *= 3;
+ } else {
+ // IE, Opera and other Windows browsers use 120.
+ scale = 120;
+ }
+
+ return scale;
+ }()),
+
+ /**
+ * Simple click regex
+ * @private
+ */
+ clickRe: /(dbl)?click/,
+ // safari keypress events for special keys return bad keycodes
+ safariKeys: {
+ 3: 13, // enter
+ 63234: 37, // left
+ 63235: 39, // right
+ 63232: 38, // up
+ 63233: 40, // down
+ 63276: 33, // page up
+ 63277: 34, // page down
+ 63272: 46, // delete
+ 63273: 36, // home
+ 63275: 35 // end
+ },
+ // normalize button clicks, don't see any way to feature detect this.
+ btnMap: Ext.isIE ? {
+ 1: 0,
+ 4: 1,
+ 2: 2
+ } : {
+ 0: 0,
+ 1: 1,
+ 2: 2
+ },
+
+ /**
+ * @property {Boolean} ctrlKey
+ * True if the control key was down during the event.
+ * In Mac this will also be true when meta key was down.
+ */
+ /**
+ * @property {Boolean} altKey
+ * True if the alt key was down during the event.
+ */
+ /**
+ * @property {Boolean} shiftKey
+ * True if the shift key was down during the event.
+ */
+
+ constructor: function(event, freezeEvent){
+ if (event) {
+ this.setEvent(event.browserEvent || event, freezeEvent);
+ }
+ },
+
+ setEvent: function(event, freezeEvent){
+ var me = this, button, options;
+
+ if (event == me || (event && event.browserEvent)) { // already wrapped
+ return event;
+ }
+ me.browserEvent = event;
+ if (event) {
+ // normalize buttons
+ button = event.button ? me.btnMap[event.button] : (event.which ? event.which - 1 : -1);
+ if (me.clickRe.test(event.type) && button == -1) {
+ button = 0;
+ }
+ options = {
+ type: event.type,
+ button: button,
+ shiftKey: event.shiftKey,
+ // mac metaKey behaves like ctrlKey
+ ctrlKey: event.ctrlKey || event.metaKey || false,
+ altKey: event.altKey,
+ // in getKey these will be normalized for the mac
+ keyCode: event.keyCode,
+ charCode: event.charCode,
+ // cache the targets for the delayed and or buffered events
+ target: Ext.EventManager.getTarget(event),
+ relatedTarget: Ext.EventManager.getRelatedTarget(event),
+ currentTarget: event.currentTarget,
+ xy: (freezeEvent ? me.getXY() : null)
+ };
+ } else {
+ options = {
+ button: -1,
+ shiftKey: false,
+ ctrlKey: false,
+ altKey: false,
+ keyCode: 0,
+ charCode: 0,
+ target: null,
+ xy: [0, 0]
+ };
+ }
+ Ext.apply(me, options);
+ return me;
+ },
+
+ /**
+ * Stop the event (preventDefault and stopPropagation)
+ */
+ stopEvent: function(){
+ this.stopPropagation();
+ this.preventDefault();
+ },
+
+ /**
+ * Prevents the browsers default handling of the event.
+ */
+ preventDefault: function(){
+ if (this.browserEvent) {
+ Ext.EventManager.preventDefault(this.browserEvent);
+ }
+ },
+
+ /**
+ * Cancels bubbling of the event.
+ */
+ stopPropagation: function(){
+ var browserEvent = this.browserEvent;
+
+ if (browserEvent) {
+ if (browserEvent.type == 'mousedown') {
+ Ext.EventManager.stoppedMouseDownEvent.fire(this);
+ }
+ Ext.EventManager.stopPropagation(browserEvent);
+ }
+ },
+
+ /**
+ * Gets the character code for the event.
+ * @return {Number}
+ */
+ getCharCode: function(){
+ return this.charCode || this.keyCode;
+ },
+
+ /**
+ * Returns a normalized keyCode for the event.
+ * @return {Number} The key code
+ */
+ getKey: function(){
+ return this.normalizeKey(this.keyCode || this.charCode);
+ },
+
+ /**
+ * Normalize key codes across browsers
+ * @private
+ * @param {Number} key The key code
+ * @return {Number} The normalized code
+ */
+ normalizeKey: function(key){
+ // can't feature detect this
+ return Ext.isWebKit ? (this.safariKeys[key] || key) : key;
+ },
+
+ /**
+ * Gets the x coordinate of the event.
+ * @return {Number}
+ * @deprecated 4.0 Replaced by {@link #getX}
+ */
+ getPageX: function(){
+ return this.getX();
+ },
+
+ /**
+ * Gets the y coordinate of the event.
+ * @return {Number}
+ * @deprecated 4.0 Replaced by {@link #getY}
+ */
+ getPageY: function(){
+ return this.getY();
+ },
+
+ /**
+ * Gets the x coordinate of the event.
+ * @return {Number}
+ */
+ getX: function() {
+ return this.getXY()[0];
+ },
+
+ /**
+ * Gets the y coordinate of the event.
+ * @return {Number}
+ */
+ getY: function() {
+ return this.getXY()[1];
+ },
+
+ /**
+ * Gets the page coordinates of the event.
+ * @return {Number[]} The xy values like [x, y]
+ */
+ getXY: function() {
+ if (!this.xy) {
+ // same for XY
+ this.xy = Ext.EventManager.getPageXY(this.browserEvent);
+ }
+ return this.xy;
+ },
+
+ /**
+ * Gets the target for the event.
+ * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
+ * @param {Number/HTMLElement} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body)
+ * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
+ * @return {HTMLElement}
+ */
+ getTarget : function(selector, maxDepth, returnEl){
+ if (selector) {
+ return Ext.fly(this.target).findParent(selector, maxDepth, returnEl);
+ }
+ return returnEl ? Ext.get(this.target) : this.target;
+ },
+
+ /**
+ * Gets the related target.
+ * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
+ * @param {Number/HTMLElement} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body)
+ * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
+ * @return {HTMLElement}
+ */
+ getRelatedTarget : function(selector, maxDepth, returnEl){
+ if (selector) {
+ return Ext.fly(this.relatedTarget).findParent(selector, maxDepth, returnEl);
+ }
+ return returnEl ? Ext.get(this.relatedTarget) : this.relatedTarget;
+ },
+
+ /**
+ * Correctly scales a given wheel delta.
+ * @param {Number} delta The delta value.
+ */
+ correctWheelDelta : function (delta) {
+ var scale = this.WHEEL_SCALE,
+ ret = Math.round(delta / scale);
+
+ if (!ret && delta) {
+ ret = (delta < 0) ? -1 : 1; // don't allow non-zero deltas to go to zero!
+ }
+
+ return ret;
+ },
+
+ /**
+ * Returns the mouse wheel deltas for this event.
+ * @return {Object} An object with "x" and "y" properties holding the mouse wheel deltas.
+ */
+ getWheelDeltas : function () {
+ var me = this,
+ event = me.browserEvent,
+ dx = 0, dy = 0; // the deltas
+
+ if (Ext.isDefined(event.wheelDeltaX)) { // WebKit has both dimensions
+ dx = event.wheelDeltaX;
+ dy = event.wheelDeltaY;
+ } else if (event.wheelDelta) { // old WebKit and IE
+ dy = event.wheelDelta;
+ } else if (event.detail) { // Gecko
+ dy = -event.detail; // gecko is backwards
+
+ // Gecko sometimes returns really big values if the user changes settings to
+ // scroll a whole page per scroll
+ if (dy > 100) {
+ dy = 3;
+ } else if (dy < -100) {
+ dy = -3;
+ }
+
+ // Firefox 3.1 adds an axis field to the event to indicate direction of
+ // scroll. See https://developer.mozilla.org/en/Gecko-Specific_DOM_Events
+ if (Ext.isDefined(event.axis) && event.axis === event.HORIZONTAL_AXIS) {
+ dx = dy;
+ dy = 0;
+ }
+ }
+
+ return {
+ x: me.correctWheelDelta(dx),
+ y: me.correctWheelDelta(dy)
+ };
+ },
+
+ /**
+ * Normalizes mouse wheel y-delta across browsers. To get x-delta information, use
+ * {@link #getWheelDeltas} instead.
+ * @return {Number} The mouse wheel y-delta
+ */
+ getWheelDelta : function(){
+ var deltas = this.getWheelDeltas();
+
+ return deltas.y;
+ },
+
+ /**
+ * Returns true if the target of this event is a child of el. Unless the allowEl parameter is set, it will return false if if the target is el.
+ * Example usage:
+// Handle click on any child of an element
+Ext.getBody().on('click', function(e){
+ if(e.within('some-el')){
+ alert('Clicked on a child of some-el!');
+ }
+});
+
+// Handle click directly on an element, ignoring clicks on child nodes
+Ext.getBody().on('click', function(e,t){
+ if((t.id == 'some-el') && !e.within(t, true)){
+ alert('Clicked directly on some-el!');
+ }
+});
+
+ * @param {String/HTMLElement/Ext.Element} el The id, DOM element or Ext.Element to check
+ * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
+ * @param {Boolean} allowEl (optional) true to also check if the passed element is the target or related target
+ * @return {Boolean}
+ */
+ within : function(el, related, allowEl){
+ if(el){
+ var t = related ? this.getRelatedTarget() : this.getTarget(),
+ result;
+
+ if (t) {
+ result = Ext.fly(el).contains(t);
+ if (!result && allowEl) {
+ result = t == Ext.getDom(el);
+ }
+ return result;
+ }
+ }
+ return false;
+ },
+
+ /**
+ * Checks if the key pressed was a "navigation" key
+ * @return {Boolean} True if the press is a navigation keypress
+ */
+ isNavKeyPress : function(){
+ var me = this,
+ k = this.normalizeKey(me.keyCode);
+
+ return (k >= 33 && k <= 40) || // Page Up/Down, End, Home, Left, Up, Right, Down
+ k == me.RETURN ||
+ k == me.TAB ||
+ k == me.ESC;
+ },
+
+ /**
+ * Checks if the key pressed was a "special" key
+ * @return {Boolean} True if the press is a special keypress
+ */
+ isSpecialKey : function(){
+ var k = this.normalizeKey(this.keyCode);
+ return (this.type == 'keypress' && this.ctrlKey) ||
+ this.isNavKeyPress() ||
+ (k == this.BACKSPACE) || // Backspace
+ (k >= 16 && k <= 20) || // Shift, Ctrl, Alt, Pause, Caps Lock
+ (k >= 44 && k <= 46); // Print Screen, Insert, Delete
+ },
+
+ /**
+ * Returns a point object that consists of the object coordinates.
+ * @return {Ext.util.Point} point
+ */
+ getPoint : function(){
+ var xy = this.getXY();
+ return new Ext.util.Point(xy[0], xy[1]);
+ },
+
+ /**
+ * Returns true if the control, meta, shift or alt key was pressed during this event.
+ * @return {Boolean}
+ */
+ hasModifier : function(){
+ return this.ctrlKey || this.altKey || this.shiftKey || this.metaKey;
+ },
+
+ /**
+ * Injects a DOM event using the data in this object and (optionally) a new target.
+ * This is a low-level technique and not likely to be used by application code. The
+ * currently supported event types are:
+ * HTMLEvents
+ *
+ * load
+ * unload
+ * select
+ * change
+ * submit
+ * reset
+ * resize
+ * scroll
+ *
+ * MouseEvents
+ *
+ * click
+ * dblclick
+ * mousedown
+ * mouseup
+ * mouseover
+ * mousemove
+ * mouseout
+ *
+ * UIEvents
+ *
+ * focusin
+ * focusout
+ * activate
+ * focus
+ * blur
+ *
+ * @param {Ext.Element/HTMLElement} target (optional) If specified, the target for the event. This
+ * is likely to be used when relaying a DOM event. If not specified, {@link #getTarget}
+ * is used to determine the target.
+ */
+ injectEvent: (function () {
+ var API,
+ dispatchers = {}, // keyed by event type (e.g., 'mousedown')
+ crazyIEButtons;
+
+ // Good reference: http://developer.yahoo.com/yui/docs/UserAction.js.html
+
+ // IE9 has createEvent, but this code causes major problems with htmleditor (it
+ // blocks all mouse events and maybe more). TODO
+
+ if (!Ext.isIE && document.createEvent) { // if (DOM compliant)
+ API = {
+ createHtmlEvent: function (doc, type, bubbles, cancelable) {
+ var event = doc.createEvent('HTMLEvents');
+
+ event.initEvent(type, bubbles, cancelable);
+ return event;
+ },
+
+ createMouseEvent: function (doc, type, bubbles, cancelable, detail,
+ clientX, clientY, ctrlKey, altKey, shiftKey, metaKey,
+ button, relatedTarget) {
+ var event = doc.createEvent('MouseEvents'),
+ view = doc.defaultView || window;
+
+ if (event.initMouseEvent) {
+ event.initMouseEvent(type, bubbles, cancelable, view, detail,
+ clientX, clientY, clientX, clientY, ctrlKey, altKey,
+ shiftKey, metaKey, button, relatedTarget);
+ } else { // old Safari
+ event = doc.createEvent('UIEvents');
+ event.initEvent(type, bubbles, cancelable);
+ event.view = view;
+ event.detail = detail;
+ event.screenX = clientX;
+ event.screenY = clientY;
+ event.clientX = clientX;
+ event.clientY = clientY;
+ event.ctrlKey = ctrlKey;
+ event.altKey = altKey;
+ event.metaKey = metaKey;
+ event.shiftKey = shiftKey;
+ event.button = button;
+ event.relatedTarget = relatedTarget;
+ }
+
+ return event;
+ },
+
+ createUIEvent: function (doc, type, bubbles, cancelable, detail) {
+ var event = doc.createEvent('UIEvents'),
+ view = doc.defaultView || window;
+
+ event.initUIEvent(type, bubbles, cancelable, view, detail);
+ return event;
+ },
+
+ fireEvent: function (target, type, event) {
+ target.dispatchEvent(event);
+ },
+
+ fixTarget: function (target) {
+ // Safari3 doesn't have window.dispatchEvent()
+ if (target == window && !target.dispatchEvent) {
+ return document;
+ }
+
+ return target;
+ }
+ };
+ } else if (document.createEventObject) { // else if (IE)
+ crazyIEButtons = { 0: 1, 1: 4, 2: 2 };
+
+ API = {
+ createHtmlEvent: function (doc, type, bubbles, cancelable) {
+ var event = doc.createEventObject();
+ event.bubbles = bubbles;
+ event.cancelable = cancelable;
+ return event;
+ },
+
+ createMouseEvent: function (doc, type, bubbles, cancelable, detail,
+ clientX, clientY, ctrlKey, altKey, shiftKey, metaKey,
+ button, relatedTarget) {
+ var event = doc.createEventObject();
+ event.bubbles = bubbles;
+ event.cancelable = cancelable;
+ event.detail = detail;
+ event.screenX = clientX;
+ event.screenY = clientY;
+ event.clientX = clientX;
+ event.clientY = clientY;
+ event.ctrlKey = ctrlKey;
+ event.altKey = altKey;
+ event.shiftKey = shiftKey;
+ event.metaKey = metaKey;
+ event.button = crazyIEButtons[button] || button;
+ event.relatedTarget = relatedTarget; // cannot assign to/fromElement
+ return event;
+ },
+
+ createUIEvent: function (doc, type, bubbles, cancelable, detail) {
+ var event = doc.createEventObject();
+ event.bubbles = bubbles;
+ event.cancelable = cancelable;
+ return event;
+ },
+
+ fireEvent: function (target, type, event) {
+ target.fireEvent('on' + type, event);
+ },
+
+ fixTarget: function (target) {
+ if (target == document) {
+ // IE6,IE7 thinks window==document and doesn't have window.fireEvent()
+ // IE6,IE7 cannot properly call document.fireEvent()
+ return document.documentElement;
+ }
+
+ return target;
+ }
+ };
+ }
+
+ //----------------
+ // HTMLEvents
+
+ Ext.Object.each({
+ load: [false, false],
+ unload: [false, false],
+ select: [true, false],
+ change: [true, false],
+ submit: [true, true],
+ reset: [true, false],
+ resize: [true, false],
+ scroll: [true, false]
+ },
+ function (name, value) {
+ var bubbles = value[0], cancelable = value[1];
+ dispatchers[name] = function (targetEl, srcEvent) {
+ var e = API.createHtmlEvent(name, bubbles, cancelable);
+ API.fireEvent(targetEl, name, e);
+ };
+ });
+
+ //----------------
+ // MouseEvents
+
+ function createMouseEventDispatcher (type, detail) {
+ var cancelable = (type != 'mousemove');
+ return function (targetEl, srcEvent) {
+ var xy = srcEvent.getXY(),
+ e = API.createMouseEvent(targetEl.ownerDocument, type, true, cancelable,
+ detail, xy[0], xy[1], srcEvent.ctrlKey, srcEvent.altKey,
+ srcEvent.shiftKey, srcEvent.metaKey, srcEvent.button,
+ srcEvent.relatedTarget);
+ API.fireEvent(targetEl, type, e);
+ };
+ }
+
+ Ext.each(['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mousemove', 'mouseout'],
+ function (eventName) {
+ dispatchers[eventName] = createMouseEventDispatcher(eventName, 1);
+ });
+
+ //----------------
+ // UIEvents
+
+ Ext.Object.each({
+ focusin: [true, false],
+ focusout: [true, false],
+ activate: [true, true],
+ focus: [false, false],
+ blur: [false, false]
+ },
+ function (name, value) {
+ var bubbles = value[0], cancelable = value[1];
+ dispatchers[name] = function (targetEl, srcEvent) {
+ var e = API.createUIEvent(targetEl.ownerDocument, name, bubbles, cancelable, 1);
+ API.fireEvent(targetEl, name, e);
+ };
+ });
+
+ //---------
+ if (!API) {
+ // not even sure what ancient browsers fall into this category...
+
+ dispatchers = {}; // never mind all those we just built :P
+
+ API = {
+ fixTarget: function (t) {
+ return t;
+ }
+ };
+ }
+
+ function cannotInject (target, srcEvent) {
+ // TODO log something
+ }
+
+ return function (target) {
+ var me = this,
+ dispatcher = dispatchers[me.type] || cannotInject,
+ t = target ? (target.dom || target) : me.getTarget();
+
+ t = API.fixTarget(t);
+ dispatcher(t, me);
+ };
+ }()) // call to produce method
+
+}, function() {
+
+Ext.EventObject = new Ext.EventObjectImpl();
+
+});
+
+
+//@tag dom,core
+//@require ../EventObject.js
+
+/**
+ * @class Ext.dom.AbstractQuery
+ * @private
+ */
+Ext.define('Ext.dom.AbstractQuery', {
+ /**
+ * Selects a group of elements.
+ * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
+ * @param {HTMLElement/String} [root] The start of the query (defaults to document).
+ * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are
+ * no matches, and empty Array is returned.
+ */
+ select: function(q, root) {
+ var results = [],
+ nodes,
+ i,
+ j,
+ qlen,
+ nlen;
+
+ root = root || document;
+
+ if (typeof root == 'string') {
+ root = document.getElementById(root);
+ }
+
+ q = q.split(",");
+
+ for (i = 0,qlen = q.length; i < qlen; i++) {
+ if (typeof q[i] == 'string') {
+
+ //support for node attribute selection
+ if (typeof q[i][0] == '@') {
+ nodes = root.getAttributeNode(q[i].substring(1));
+ results.push(nodes);
+ } else {
+ nodes = root.querySelectorAll(q[i]);
+
+ for (j = 0,nlen = nodes.length; j < nlen; j++) {
+ results.push(nodes[j]);
+ }
+ }
+ }
+ }
+
+ return results;
+ },
+
+ /**
+ * Selects a single element.
+ * @param {String} selector The selector/xpath query
+ * @param {HTMLElement/String} [root] The start of the query (defaults to document).
+ * @return {HTMLElement} The DOM element which matched the selector.
+ */
+ selectNode: function(q, root) {
+ return this.select(q, root)[0];
+ },
+
+ /**
+ * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
+ * @param {String/HTMLElement/Array} el An element id, element or array of elements
+ * @param {String} selector The simple selector to test
+ * @return {Boolean}
+ */
+ is: function(el, q) {
+ if (typeof el == "string") {
+ el = document.getElementById(el);
+ }
+ return this.select(q).indexOf(el) !== -1;
+ }
+
+});
+
+//@tag dom,core
+//@require AbstractQuery.js
+
+/**
+ * Abstract base class for {@link Ext.dom.Helper}.
+ * @private
+ */
+Ext.define('Ext.dom.AbstractHelper', {
+ emptyTags : /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
+ confRe : /(?:tag|children|cn|html|tpl|tplData)$/i,
+ endRe : /end/i,
+
+ // Since cls & for are reserved words, we need to transform them
+ attributeTransform: { cls : 'class', htmlFor : 'for' },
+
+ closeTags: {},
+
+ decamelizeName : (function () {
+ var camelCaseRe = /([a-z])([A-Z])/g,
+ cache = {};
+
+ function decamel (match, p1, p2) {
+ return p1 + '-' + p2.toLowerCase();
+ }
+
+ return function (s) {
+ return cache[s] || (cache[s] = s.replace(camelCaseRe, decamel));
+ };
+ }()),
+
+ generateMarkup: function(spec, buffer) {
+ var me = this,
+ attr, val, tag, i, closeTags;
+
+ if (typeof spec == "string") {
+ buffer.push(spec);
+ } else if (Ext.isArray(spec)) {
+ for (i = 0; i < spec.length; i++) {
+ if (spec[i]) {
+ me.generateMarkup(spec[i], buffer);
+ }
+ }
+ } else {
+ tag = spec.tag || 'div';
+ buffer.push('<', tag);
+
+ for (attr in spec) {
+ if (spec.hasOwnProperty(attr)) {
+ val = spec[attr];
+ if (!me.confRe.test(attr)) {
+ if (typeof val == "object") {
+ buffer.push(' ', attr, '="');
+ me.generateStyles(val, buffer).push('"');
+ } else {
+ buffer.push(' ', me.attributeTransform[attr] || attr, '="', val, '"');
+ }
+ }
+ }
+ }
+
+ // Now either just close the tag or try to add children and close the tag.
+ if (me.emptyTags.test(tag)) {
+ buffer.push('/>');
+ } else {
+ buffer.push('>');
+
+ // Apply the tpl html, and cn specifications
+ if ((val = spec.tpl)) {
+ val.applyOut(spec.tplData, buffer);
+ }
+ if ((val = spec.html)) {
+ buffer.push(val);
+ }
+ if ((val = spec.cn || spec.children)) {
+ me.generateMarkup(val, buffer);
+ }
+
+ // we generate a lot of close tags, so cache them rather than push 3 parts
+ closeTags = me.closeTags;
+ buffer.push(closeTags[tag] || (closeTags[tag] = '' + tag + '>'));
+ }
+ }
+
+ return buffer;
+ },
+
+ /**
+ * Converts the styles from the given object to text. The styles are CSS style names
+ * with their associated value.
+ *
+ * The basic form of this method returns a string:
+ *
+ * var s = Ext.DomHelper.generateStyles({
+ * backgroundColor: 'red'
+ * });
+ *
+ * // s = 'background-color:red;'
+ *
+ * Alternatively, this method can append to an output array.
+ *
+ * var buf = [];
+ *
+ * ...
+ *
+ * Ext.DomHelper.generateStyles({
+ * backgroundColor: 'red'
+ * }, buf);
+ *
+ * In this case, the style text is pushed on to the array and the array is returned.
+ *
+ * @param {Object} styles The object describing the styles.
+ * @param {String[]} [buffer] The output buffer.
+ * @return {String/String[]} If buffer is passed, it is returned. Otherwise the style
+ * string is returned.
+ */
+ generateStyles: function (styles, buffer) {
+ var a = buffer || [],
+ name;
+
+ for (name in styles) {
+ if (styles.hasOwnProperty(name)) {
+ a.push(this.decamelizeName(name), ':', styles[name], ';');
+ }
+ }
+
+ return buffer || a.join('');
+ },
+
+ /**
+ * Returns the markup for the passed Element(s) config.
+ * @param {Object} spec The DOM object spec (and children)
+ * @return {String}
+ */
+ markup: function(spec) {
+ if (typeof spec == "string") {
+ return spec;
+ }
+
+ var buf = this.generateMarkup(spec, []);
+ return buf.join('');
+ },
+
+ /**
+ * Applies a style specification to an element.
+ * @param {String/HTMLElement} el The element to apply styles to
+ * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
+ * a function which returns such a specification.
+ */
+ applyStyles: function(el, styles) {
+ if (styles) {
+ var i = 0,
+ len,
+ style;
+
+ el = Ext.fly(el);
+ if (typeof styles == 'function') {
+ styles = styles.call();
+ }
+ if (typeof styles == 'string'){
+ styles = Ext.util.Format.trim(styles).split(/\s*(?::|;)\s*/);
+ for(len = styles.length; i < len;){
+ el.setStyle(styles[i++], styles[i++]);
+ }
+ } else if (Ext.isObject(styles)) {
+ el.setStyle(styles);
+ }
+ }
+ },
+
+ /**
+ * Inserts an HTML fragment into the DOM.
+ * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
+ *
+ * For example take the following HTML: `Contents
`
+ *
+ * Using different `where` values inserts element to the following places:
+ *
+ * - beforeBegin: `Contents
`
+ * - afterBegin: `Contents
`
+ * - beforeEnd: `Contents
`
+ * - afterEnd: `Contents
`
+ *
+ * @param {HTMLElement/TextNode} el The context element
+ * @param {String} html The HTML fragment
+ * @return {HTMLElement} The new node
+ */
+ insertHtml: function(where, el, html) {
+ var hash = {},
+ hashVal,
+ setStart,
+ range,
+ frag,
+ rangeEl,
+ rs;
+
+ where = where.toLowerCase();
+
+ // add these here because they are used in both branches of the condition.
+ hash['beforebegin'] = ['BeforeBegin', 'previousSibling'];
+ hash['afterend'] = ['AfterEnd', 'nextSibling'];
+
+ range = el.ownerDocument.createRange();
+ setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before');
+ if (hash[where]) {
+ range[setStart](el);
+ frag = range.createContextualFragment(html);
+ el.parentNode.insertBefore(frag, where == 'beforebegin' ? el : el.nextSibling);
+ return el[(where == 'beforebegin' ? 'previous' : 'next') + 'Sibling'];
+ }
+ else {
+ rangeEl = (where == 'afterbegin' ? 'first' : 'last') + 'Child';
+ if (el.firstChild) {
+ range[setStart](el[rangeEl]);
+ frag = range.createContextualFragment(html);
+ if (where == 'afterbegin') {
+ el.insertBefore(frag, el.firstChild);
+ }
+ else {
+ el.appendChild(frag);
+ }
+ }
+ else {
+ el.innerHTML = html;
+ }
+ return el[rangeEl];
+ }
+
+ throw 'Illegal insertion point -> "' + where + '"';
+ },
+
+ /**
+ * Creates new DOM element(s) and inserts them before el.
+ * @param {String/HTMLElement/Ext.Element} el The context element
+ * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
+ * @param {Boolean} [returnElement] true to return a Ext.Element
+ * @return {HTMLElement/Ext.Element} The new node
+ */
+ insertBefore: function(el, o, returnElement) {
+ return this.doInsert(el, o, returnElement, 'beforebegin');
+ },
+
+ /**
+ * Creates new DOM element(s) and inserts them after el.
+ * @param {String/HTMLElement/Ext.Element} el The context element
+ * @param {Object} o The DOM object spec (and children)
+ * @param {Boolean} [returnElement] true to return a Ext.Element
+ * @return {HTMLElement/Ext.Element} The new node
+ */
+ insertAfter: function(el, o, returnElement) {
+ return this.doInsert(el, o, returnElement, 'afterend', 'nextSibling');
+ },
+
+ /**
+ * Creates new DOM element(s) and inserts them as the first child of el.
+ * @param {String/HTMLElement/Ext.Element} el The context element
+ * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
+ * @param {Boolean} [returnElement] true to return a Ext.Element
+ * @return {HTMLElement/Ext.Element} The new node
+ */
+ insertFirst: function(el, o, returnElement) {
+ return this.doInsert(el, o, returnElement, 'afterbegin', 'firstChild');
+ },
+
+ /**
+ * Creates new DOM element(s) and appends them to el.
+ * @param {String/HTMLElement/Ext.Element} el The context element
+ * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
+ * @param {Boolean} [returnElement] true to return a Ext.Element
+ * @return {HTMLElement/Ext.Element} The new node
+ */
+ append: function(el, o, returnElement) {
+ return this.doInsert(el, o, returnElement, 'beforeend', '', true);
+ },
+
+ /**
+ * Creates new DOM element(s) and overwrites the contents of el with them.
+ * @param {String/HTMLElement/Ext.Element} el The context element
+ * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
+ * @param {Boolean} [returnElement] true to return a Ext.Element
+ * @return {HTMLElement/Ext.Element} The new node
+ */
+ overwrite: function(el, o, returnElement) {
+ el = Ext.getDom(el);
+ el.innerHTML = this.markup(o);
+ return returnElement ? Ext.get(el.firstChild) : el.firstChild;
+ },
+
+ doInsert: function(el, o, returnElement, pos, sibling, append) {
+ var newNode = this.insertHtml(pos, Ext.getDom(el), this.markup(o));
+ return returnElement ? Ext.get(newNode, true) : newNode;
+ }
+
+});
+
+//@tag dom,core
+//@require AbstractHelper.js
+//@require Ext.Supports
+//@require Ext.EventManager
+//@define Ext.dom.AbstractElement
+
+/**
+ * @class Ext.dom.AbstractElement
+ * @extend Ext.Base
+ * @private
+ */
+(function() {
+
+var document = window.document,
+ trimRe = /^\s+|\s+$/g,
+ whitespaceRe = /\s/;
+
+if (!Ext.cache){
+ Ext.cache = {};
+}
+
+Ext.define('Ext.dom.AbstractElement', {
+
+ inheritableStatics: {
+
+ /**
+ * Retrieves Ext.dom.Element objects. {@link Ext#get} is alias for {@link Ext.dom.Element#get}.
+ *
+ * **This method does not retrieve {@link Ext.Component Component}s.** This method retrieves Ext.dom.Element
+ * objects which encapsulate DOM elements. To retrieve a Component by its ID, use {@link Ext.ComponentManager#get}.
+ *
+ * Uses simple caching to consistently return the same object. Automatically fixes if an object was recreated with
+ * the same id via AJAX or DOM.
+ *
+ * @param {String/HTMLElement/Ext.Element} el The id of the node, a DOM Node or an existing Element.
+ * @return {Ext.dom.Element} The Element object (or null if no matching element was found)
+ * @static
+ * @inheritable
+ */
+ get: function(el) {
+ var me = this,
+ El = Ext.dom.Element,
+ cacheItem,
+ extEl,
+ dom,
+ id;
+
+ if (!el) {
+ return null;
+ }
+
+ if (typeof el == "string") { // element id
+ if (el == Ext.windowId) {
+ return El.get(window);
+ } else if (el == Ext.documentId) {
+ return El.get(document);
+ }
+
+ cacheItem = Ext.cache[el];
+ // This code is here to catch the case where we've got a reference to a document of an iframe
+ // It getElementById will fail because it's not part of the document, so if we're skipping
+ // GC it means it's a window/document object that isn't the default window/document, which we have
+ // already handled above
+ if (cacheItem && cacheItem.skipGarbageCollection) {
+ extEl = cacheItem.el;
+ return extEl;
+ }
+
+ if (!(dom = document.getElementById(el))) {
+ return null;
+ }
+
+ if (cacheItem && cacheItem.el) {
+ extEl = Ext.updateCacheEntry(cacheItem, dom).el;
+ } else {
+ // Force new element if there's a cache but no el attached
+ extEl = new El(dom, !!cacheItem);
+ }
+ return extEl;
+ } else if (el.tagName) { // dom element
+ if (!(id = el.id)) {
+ id = Ext.id(el);
+ }
+ cacheItem = Ext.cache[id];
+ if (cacheItem && cacheItem.el) {
+ extEl = Ext.updateCacheEntry(cacheItem, el).el;
+ } else {
+ // Force new element if there's a cache but no el attached
+ extEl = new El(el, !!cacheItem);
+ }
+ return extEl;
+ } else if (el instanceof me) {
+ if (el != me.docEl && el != me.winEl) {
+ id = el.id;
+ // refresh dom element in case no longer valid,
+ // catch case where it hasn't been appended
+ cacheItem = Ext.cache[id];
+ if (cacheItem) {
+ Ext.updateCacheEntry(cacheItem, document.getElementById(id) || el.dom);
+ }
+ }
+ return el;
+ } else if (el.isComposite) {
+ return el;
+ } else if (Ext.isArray(el)) {
+ return me.select(el);
+ } else if (el === document) {
+ // create a bogus element object representing the document object
+ if (!me.docEl) {
+ me.docEl = Ext.Object.chain(El.prototype);
+ me.docEl.dom = document;
+ me.docEl.id = Ext.id(document);
+ me.addToCache(me.docEl);
+ }
+ return me.docEl;
+ } else if (el === window) {
+ if (!me.winEl) {
+ me.winEl = Ext.Object.chain(El.prototype);
+ me.winEl.dom = window;
+ me.winEl.id = Ext.id(window);
+ me.addToCache(me.winEl);
+ }
+ return me.winEl;
+ }
+ return null;
+ },
+
+ addToCache: function(el, id) {
+ if (el) {
+ Ext.addCacheEntry(id, el);
+ }
+ return el;
+ },
+
+ addMethods: function() {
+ this.override.apply(this, arguments);
+ },
+
+ /**
+ * Returns an array of unique class names based upon the input strings, or string arrays.
+ * The number of parameters is unlimited.
+ * Example
+// Add x-invalid and x-mandatory classes, do not duplicate
+myElement.dom.className = Ext.core.Element.mergeClsList(this.initialClasses, 'x-invalid x-mandatory');
+
+ * @param {Mixed} clsList1 A string of class names, or an array of class names.
+ * @param {Mixed} clsList2 A string of class names, or an array of class names.
+ * @return {Array} An array of strings representing remaining unique, merged class names. If class names were added to the first list, the changed property will be true.
+ * @static
+ * @inheritable
+ */
+ mergeClsList: function() {
+ var clsList, clsHash = {},
+ i, length, j, listLength, clsName, result = [],
+ changed = false;
+
+ for (i = 0, length = arguments.length; i < length; i++) {
+ clsList = arguments[i];
+ if (Ext.isString(clsList)) {
+ clsList = clsList.replace(trimRe, '').split(whitespaceRe);
+ }
+ if (clsList) {
+ for (j = 0, listLength = clsList.length; j < listLength; j++) {
+ clsName = clsList[j];
+ if (!clsHash[clsName]) {
+ if (i) {
+ changed = true;
+ }
+ clsHash[clsName] = true;
+ }
+ }
+ }
+ }
+
+ for (clsName in clsHash) {
+ result.push(clsName);
+ }
+ result.changed = changed;
+ return result;
+ },
+
+ /**
+ * Returns an array of unique class names deom the first parameter with all class names
+ * from the second parameter removed.
+ * Example
+// Remove x-invalid and x-mandatory classes if present.
+myElement.dom.className = Ext.core.Element.removeCls(this.initialClasses, 'x-invalid x-mandatory');
+
+ * @param {Mixed} existingClsList A string of class names, or an array of class names.
+ * @param {Mixed} removeClsList A string of class names, or an array of class names to remove from existingClsList.
+ * @return {Array} An array of strings representing remaining class names. If class names were removed, the changed property will be true.
+ * @static
+ * @inheritable
+ */
+ removeCls: function(existingClsList, removeClsList) {
+ var clsHash = {},
+ i, length, clsName, result = [],
+ changed = false;
+
+ if (existingClsList) {
+ if (Ext.isString(existingClsList)) {
+ existingClsList = existingClsList.replace(trimRe, '').split(whitespaceRe);
+ }
+ for (i = 0, length = existingClsList.length; i < length; i++) {
+ clsHash[existingClsList[i]] = true;
+ }
+ }
+ if (removeClsList) {
+ if (Ext.isString(removeClsList)) {
+ removeClsList = removeClsList.split(whitespaceRe);
+ }
+ for (i = 0, length = removeClsList.length; i < length; i++) {
+ clsName = removeClsList[i];
+ if (clsHash[clsName]) {
+ changed = true;
+ delete clsHash[clsName];
+ }
+ }
+ }
+ for (clsName in clsHash) {
+ result.push(clsName);
+ }
+ result.changed = changed;
+ return result;
+ },
+
+ /**
+ * @property
+ * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}.
+ * Use the CSS 'visibility' property to hide the element.
+ *
+ * Note that in this mode, {@link Ext.dom.Element#isVisible isVisible} may return true
+ * for an element even though it actually has a parent element that is hidden. For this
+ * reason, and in most cases, using the {@link #OFFSETS} mode is a better choice.
+ * @static
+ * @inheritable
+ */
+ VISIBILITY: 1,
+
+ /**
+ * @property
+ * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}.
+ * Use the CSS 'display' property to hide the element.
+ * @static
+ * @inheritable
+ */
+ DISPLAY: 2,
+
+ /**
+ * @property
+ * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}.
+ * Use CSS absolute positioning and top/left offsets to hide the element.
+ * @static
+ * @inheritable
+ */
+ OFFSETS: 3,
+
+ /**
+ * @property
+ * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}.
+ * Add or remove the {@link Ext.Layer#visibilityCls} class to hide the element.
+ * @static
+ * @inheritable
+ */
+ ASCLASS: 4
+ },
+
+ constructor: function(element, forceNew) {
+ var me = this,
+ dom = typeof element == 'string'
+ ? document.getElementById(element)
+ : element,
+ id;
+
+ if (!dom) {
+ return null;
+ }
+
+ id = dom.id;
+ if (!forceNew && id && Ext.cache[id]) {
+ // element object already exists
+ return Ext.cache[id].el;
+ }
+
+ /**
+ * @property {HTMLElement} dom
+ * The DOM element
+ */
+ me.dom = dom;
+
+ /**
+ * @property {String} id
+ * The DOM element ID
+ */
+ me.id = id || Ext.id(dom);
+
+ me.self.addToCache(me);
+ },
+
+ /**
+ * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
+ * @param {Object} o The object with the attributes
+ * @param {Boolean} [useSet=true] false to override the default setAttribute to use expandos.
+ * @return {Ext.dom.Element} this
+ */
+ set: function(o, useSet) {
+ var el = this.dom,
+ attr,
+ value;
+
+ for (attr in o) {
+ if (o.hasOwnProperty(attr)) {
+ value = o[attr];
+ if (attr == 'style') {
+ this.applyStyles(value);
+ }
+ else if (attr == 'cls') {
+ el.className = value;
+ }
+ else if (useSet !== false) {
+ if (value === undefined) {
+ el.removeAttribute(attr);
+ } else {
+ el.setAttribute(attr, value);
+ }
+ }
+ else {
+ el[attr] = value;
+ }
+ }
+ }
+ return this;
+ },
+
+ /**
+ * @property {String} defaultUnit
+ * The default unit to append to CSS values where a unit isn't provided.
+ */
+ defaultUnit: "px",
+
+ /**
+ * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
+ * @param {String} selector The simple selector to test
+ * @return {Boolean} True if this element matches the selector, else false
+ */
+ is: function(simpleSelector) {
+ return Ext.DomQuery.is(this.dom, simpleSelector);
+ },
+
+ /**
+ * Returns the value of the "value" attribute
+ * @param {Boolean} asNumber true to parse the value as a number
+ * @return {String/Number}
+ */
+ getValue: function(asNumber) {
+ var val = this.dom.value;
+ return asNumber ? parseInt(val, 10) : val;
+ },
+
+ /**
+ * Removes this element's dom reference. Note that event and cache removal is handled at {@link Ext#removeNode
+ * Ext.removeNode}
+ */
+ remove: function() {
+ var me = this,
+ dom = me.dom;
+
+ if (dom) {
+ Ext.removeNode(dom);
+ delete me.dom;
+ }
+ },
+
+ /**
+ * Returns true if this element is an ancestor of the passed element
+ * @param {HTMLElement/String} el The element to check
+ * @return {Boolean} True if this element is an ancestor of el, else false
+ */
+ contains: function(el) {
+ if (!el) {
+ return false;
+ }
+
+ var me = this,
+ dom = el.dom || el;
+
+ // we need el-contains-itself logic here because isAncestor does not do that:
+ return (dom === me.dom) || Ext.dom.AbstractElement.isAncestor(me.dom, dom);
+ },
+
+ /**
+ * Returns the value of an attribute from the element's underlying DOM node.
+ * @param {String} name The attribute name
+ * @param {String} [namespace] The namespace in which to look for the attribute
+ * @return {String} The attribute value
+ */
+ getAttribute: function(name, ns) {
+ var dom = this.dom;
+ return dom.getAttributeNS(ns, name) || dom.getAttribute(ns + ":" + name) || dom.getAttribute(name) || dom[name];
+ },
+
+ /**
+ * Update the innerHTML of this element
+ * @param {String} html The new HTML
+ * @return {Ext.dom.Element} this
+ */
+ update: function(html) {
+ if (this.dom) {
+ this.dom.innerHTML = html;
+ }
+ return this;
+ },
+
+
+ /**
+ * Set the innerHTML of this element
+ * @param {String} html The new HTML
+ * @return {Ext.Element} this
+ */
+ setHTML: function(html) {
+ if(this.dom) {
+ this.dom.innerHTML = html;
+ }
+ return this;
+ },
+
+ /**
+ * Returns the innerHTML of an Element or an empty string if the element's
+ * dom no longer exists.
+ */
+ getHTML: function() {
+ return this.dom ? this.dom.innerHTML : '';
+ },
+
+ /**
+ * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
+ * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
+ * @return {Ext.Element} this
+ */
+ hide: function() {
+ this.setVisible(false);
+ return this;
+ },
+
+ /**
+ * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
+ * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
+ * @return {Ext.Element} this
+ */
+ show: function() {
+ this.setVisible(true);
+ return this;
+ },
+
+ /**
+ * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
+ * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
+ * @param {Boolean} visible Whether the element is visible
+ * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
+ * @return {Ext.Element} this
+ */
+ setVisible: function(visible, animate) {
+ var me = this,
+ statics = me.self,
+ mode = me.getVisibilityMode(),
+ prefix = Ext.baseCSSPrefix;
+
+ switch (mode) {
+ case statics.VISIBILITY:
+ me.removeCls([prefix + 'hidden-display', prefix + 'hidden-offsets']);
+ me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-visibility');
+ break;
+
+ case statics.DISPLAY:
+ me.removeCls([prefix + 'hidden-visibility', prefix + 'hidden-offsets']);
+ me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-display');
+ break;
+
+ case statics.OFFSETS:
+ me.removeCls([prefix + 'hidden-visibility', prefix + 'hidden-display']);
+ me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-offsets');
+ break;
+ }
+
+ return me;
+ },
+
+ getVisibilityMode: function() {
+ // Only flyweights won't have a $cache object, by calling getCache the cache
+ // will be created for future accesses. As such, we're eliminating the method
+ // call since it's mostly redundant
+ var data = (this.$cache || this.getCache()).data,
+ visMode = data.visibilityMode;
+
+ if (visMode === undefined) {
+ data.visibilityMode = visMode = this.self.DISPLAY;
+ }
+
+ return visMode;
+ },
+
+ /**
+ * Use this to change the visibility mode between {@link #VISIBILITY}, {@link #DISPLAY}, {@link #OFFSETS} or {@link #ASCLASS}.
+ */
+ setVisibilityMode: function(mode) {
+ (this.$cache || this.getCache()).data.visibilityMode = mode;
+ return this;
+ },
+
+ getCache: function() {
+ var me = this,
+ id = me.dom.id || Ext.id(me.dom);
+
+ // Note that we do not assign an ID to the calling object here.
+ // An Ext.dom.Element will have one assigned at construction, and an Ext.dom.AbstractElement.Fly must not have one.
+ // We assign an ID to the DOM element if it does not have one.
+ me.$cache = Ext.cache[id] || Ext.addCacheEntry(id, null, me.dom);
+
+ return me.$cache;
+ }
+
+}, function() {
+ var AbstractElement = this;
+
+ /**
+ * @private
+ * @member Ext
+ */
+ Ext.getDetachedBody = function () {
+ var detachedEl = AbstractElement.detachedBodyEl;
+
+ if (!detachedEl) {
+ detachedEl = document.createElement('div');
+ AbstractElement.detachedBodyEl = detachedEl = new AbstractElement.Fly(detachedEl);
+ detachedEl.isDetachedBody = true;
+ }
+
+ return detachedEl;
+ };
+
+ /**
+ * @private
+ * @member Ext
+ */
+ Ext.getElementById = function (id) {
+ var el = document.getElementById(id),
+ detachedBodyEl;
+
+ if (!el && (detachedBodyEl = AbstractElement.detachedBodyEl)) {
+ el = detachedBodyEl.dom.querySelector('#' + Ext.escapeId(id));
+ }
+
+ return el;
+ };
+
+ /**
+ * @member Ext
+ * @method get
+ * @inheritdoc Ext.dom.Element#get
+ */
+ Ext.get = function(el) {
+ return Ext.dom.Element.get(el);
+ };
+
+ this.addStatics({
+ /**
+ * @class Ext.dom.AbstractElement.Fly
+ * @extends Ext.dom.AbstractElement
+ *
+ * A non-persistent wrapper for a DOM element which may be used to execute methods of {@link Ext.dom.Element}
+ * upon a DOM element without creating an instance of {@link Ext.dom.Element}.
+ *
+ * A **singleton** instance of this class is returned when you use {@link Ext#fly}
+ *
+ * Because it is a singleton, this Flyweight does not have an ID, and must be used and discarded in a single line.
+ * You should not keep and use the reference to this singleton over multiple lines because methods that you call
+ * may themselves make use of {@link Ext#fly} and may change the DOM element to which the instance refers.
+ */
+ Fly: new Ext.Class({
+ extend: AbstractElement,
+
+ /**
+ * @property {Boolean} isFly
+ * This is `true` to identify Element flyweights
+ */
+ isFly: true,
+
+ constructor: function(dom) {
+ this.dom = dom;
+ },
+
+ /**
+ * @private
+ * Attach this fliyweight instance to the passed DOM element.
+ *
+ * Note that a flightweight does **not** have an ID, and does not acquire the ID of the DOM element.
+ */
+ attach: function (dom) {
+
+ // Attach to the passed DOM element. The same code as in Ext.Fly
+ this.dom = dom;
+ // Use cached data if there is existing cached data for the referenced DOM element,
+ // otherwise it will be created when needed by getCache.
+ this.$cache = dom.id ? Ext.cache[dom.id] : null;
+ return this;
+ }
+ }),
+
+ _flyweights: {},
+
+ /**
+ * Gets the singleton {@link Ext.dom.AbstractElement.Fly flyweight} element, with the passed node as the active element.
+ *
+ * Because it is a singleton, this Flyweight does not have an ID, and must be used and discarded in a single line.
+ * You may not keep and use the reference to this singleton over multiple lines because methods that you call
+ * may themselves make use of {@link Ext#fly} and may change the DOM element to which the instance refers.
+ *
+ * {@link Ext#fly} is alias for {@link Ext.dom.AbstractElement#fly}.
+ *
+ * Use this to make one-time references to DOM elements which are not going to be accessed again either by
+ * application code, or by Ext's classes. If accessing an element which will be processed regularly, then {@link
+ * Ext#get Ext.get} will be more appropriate to take advantage of the caching provided by the Ext.dom.Element
+ * class.
+ *
+ * @param {String/HTMLElement} dom The dom node or id
+ * @param {String} [named] Allows for creation of named reusable flyweights to prevent conflicts (e.g.
+ * internally Ext uses "_global")
+ * @return {Ext.dom.AbstractElement.Fly} The singleton flyweight object (or null if no matching element was found)
+ * @static
+ * @member Ext.dom.AbstractElement
+ */
+ fly: function(dom, named) {
+ var fly = null,
+ _flyweights = AbstractElement._flyweights;
+
+ named = named || '_global';
+
+ dom = Ext.getDom(dom);
+
+ if (dom) {
+ fly = _flyweights[named] || (_flyweights[named] = new AbstractElement.Fly());
+
+ // Attach to the passed DOM element.
+ // This code performs the same function as Fly.attach, but inline it for efficiency
+ fly.dom = dom;
+ // Use cached data if there is existing cached data for the referenced DOM element,
+ // otherwise it will be created when needed by getCache.
+ fly.$cache = dom.id ? Ext.cache[dom.id] : null;
+ }
+ return fly;
+ }
+ });
+
+ /**
+ * @member Ext
+ * @method fly
+ * @inheritdoc Ext.dom.AbstractElement#fly
+ */
+ Ext.fly = function() {
+ return AbstractElement.fly.apply(AbstractElement, arguments);
+ };
+
+ (function (proto) {
+ /**
+ * @method destroy
+ * @member Ext.dom.AbstractElement
+ * @inheritdoc Ext.dom.AbstractElement#remove
+ * Alias to {@link #remove}.
+ */
+ proto.destroy = proto.remove;
+
+ /**
+ * Returns a child element of this element given its `id`.
+ * @method getById
+ * @member Ext.dom.AbstractElement
+ * @param {String} id The id of the desired child element.
+ * @param {Boolean} [asDom=false] True to return the DOM element, false to return a
+ * wrapped Element object.
+ */
+ if (document.querySelector) {
+ proto.getById = function (id, asDom) {
+ // for normal elements getElementById is the best solution, but if the el is
+ // not part of the document.body, we have to resort to querySelector
+ var dom = document.getElementById(id) ||
+ this.dom.querySelector('#'+Ext.escapeId(id));
+ return asDom ? dom : (dom ? Ext.get(dom) : null);
+ };
+ } else {
+ proto.getById = function (id, asDom) {
+ var dom = document.getElementById(id);
+ return asDom ? dom : (dom ? Ext.get(dom) : null);
+ };
+ }
+ }(this.prototype));
+});
+
+}());
+
+//@tag dom,core
+//@require AbstractElement.js
+//@define Ext.dom.AbstractElement-static
+//@define Ext.dom.AbstractElement
+
+/**
+ * @class Ext.dom.AbstractElement
+ */
+Ext.dom.AbstractElement.addInheritableStatics({
+ unitRe: /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i,
+ camelRe: /(-[a-z])/gi,
+ cssRe: /([a-z0-9\-]+)\s*:\s*([^;\s]+(?:\s*[^;\s]+)*);?/gi,
+ opacityRe: /alpha\(opacity=(.*)\)/i,
+ propertyCache: {},
+ defaultUnit : "px",
+ borders: {l: 'border-left-width', r: 'border-right-width', t: 'border-top-width', b: 'border-bottom-width'},
+ paddings: {l: 'padding-left', r: 'padding-right', t: 'padding-top', b: 'padding-bottom'},
+ margins: {l: 'margin-left', r: 'margin-right', t: 'margin-top', b: 'margin-bottom'},
+ /**
+ * Test if size has a unit, otherwise appends the passed unit string, or the default for this Element.
+ * @param size {Object} The size to set
+ * @param units {String} The units to append to a numeric size value
+ * @private
+ * @static
+ */
+ addUnits: function(size, units) {
+ // Most common case first: Size is set to a number
+ if (typeof size == 'number') {
+ return size + (units || this.defaultUnit || 'px');
+ }
+
+ // Size set to a value which means "auto"
+ if (size === "" || size == "auto" || size === undefined || size === null) {
+ return size || '';
+ }
+
+ // Otherwise, warn if it's not a valid CSS measurement
+ if (!this.unitRe.test(size)) {
+ if (Ext.isDefined(Ext.global.console)) {
+ Ext.global.console.warn("Warning, size detected as NaN on Element.addUnits.");
+ }
+ return size || '';
+ }
+
+ return size;
+ },
+
+ /**
+ * @static
+ * @private
+ */
+ isAncestor: function(p, c) {
+ var ret = false;
+
+ p = Ext.getDom(p);
+ c = Ext.getDom(c);
+ if (p && c) {
+ if (p.contains) {
+ return p.contains(c);
+ } else if (p.compareDocumentPosition) {
+ return !!(p.compareDocumentPosition(c) & 16);
+ } else {
+ while ((c = c.parentNode)) {
+ ret = c == p || ret;
+ }
+ }
+ }
+ return ret;
+ },
+
+ /**
+ * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
+ * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
+ * @static
+ * @param {Number/String} box The encoded margins
+ * @return {Object} An object with margin sizes for top, right, bottom and left
+ */
+ parseBox: function(box) {
+ if (typeof box != 'string') {
+ box = box.toString();
+ }
+ var parts = box.split(' '),
+ ln = parts.length;
+
+ if (ln == 1) {
+ parts[1] = parts[2] = parts[3] = parts[0];
+ }
+ else if (ln == 2) {
+ parts[2] = parts[0];
+ parts[3] = parts[1];
+ }
+ else if (ln == 3) {
+ parts[3] = parts[1];
+ }
+
+ return {
+ top :parseFloat(parts[0]) || 0,
+ right :parseFloat(parts[1]) || 0,
+ bottom:parseFloat(parts[2]) || 0,
+ left :parseFloat(parts[3]) || 0
+ };
+ },
+
+ /**
+ * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
+ * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
+ * @static
+ * @param {Number/String} box The encoded margins
+ * @param {String} units The type of units to add
+ * @return {String} An string with unitized (px if units is not specified) metrics for top, right, bottom and left
+ */
+ unitizeBox: function(box, units) {
+ var a = this.addUnits,
+ b = this.parseBox(box);
+
+ return a(b.top, units) + ' ' +
+ a(b.right, units) + ' ' +
+ a(b.bottom, units) + ' ' +
+ a(b.left, units);
+
+ },
+
+ // private
+ camelReplaceFn: function(m, a) {
+ return a.charAt(1).toUpperCase();
+ },
+
+ /**
+ * Normalizes CSS property keys from dash delimited to camel case JavaScript Syntax.
+ * For example:
+ *
+ * - border-width -> borderWidth
+ * - padding-top -> paddingTop
+ *
+ * @static
+ * @param {String} prop The property to normalize
+ * @return {String} The normalized string
+ */
+ normalize: function(prop) {
+ // TODO: Mobile optimization?
+ if (prop == 'float') {
+ prop = Ext.supports.Float ? 'cssFloat' : 'styleFloat';
+ }
+ return this.propertyCache[prop] || (this.propertyCache[prop] = prop.replace(this.camelRe, this.camelReplaceFn));
+ },
+
+ /**
+ * Retrieves the document height
+ * @static
+ * @return {Number} documentHeight
+ */
+ getDocumentHeight: function() {
+ return Math.max(!Ext.isStrict ? document.body.scrollHeight : document.documentElement.scrollHeight, this.getViewportHeight());
+ },
+
+ /**
+ * Retrieves the document width
+ * @static
+ * @return {Number} documentWidth
+ */
+ getDocumentWidth: function() {
+ return Math.max(!Ext.isStrict ? document.body.scrollWidth : document.documentElement.scrollWidth, this.getViewportWidth());
+ },
+
+ /**
+ * Retrieves the viewport height of the window.
+ * @static
+ * @return {Number} viewportHeight
+ */
+ getViewportHeight: function(){
+ return window.innerHeight;
+ },
+
+ /**
+ * Retrieves the viewport width of the window.
+ * @static
+ * @return {Number} viewportWidth
+ */
+ getViewportWidth: function() {
+ return window.innerWidth;
+ },
+
+ /**
+ * Retrieves the viewport size of the window.
+ * @static
+ * @return {Object} object containing width and height properties
+ */
+ getViewSize: function() {
+ return {
+ width: window.innerWidth,
+ height: window.innerHeight
+ };
+ },
+
+ /**
+ * Retrieves the current orientation of the window. This is calculated by
+ * determing if the height is greater than the width.
+ * @static
+ * @return {String} Orientation of window: 'portrait' or 'landscape'
+ */
+ getOrientation: function() {
+ if (Ext.supports.OrientationChange) {
+ return (window.orientation == 0) ? 'portrait' : 'landscape';
+ }
+
+ return (window.innerHeight > window.innerWidth) ? 'portrait' : 'landscape';
+ },
+
+ /**
+ * Returns the top Element that is located at the passed coordinates
+ * @static
+ * @param {Number} x The x coordinate
+ * @param {Number} y The y coordinate
+ * @return {String} The found Element
+ */
+ fromPoint: function(x, y) {
+ return Ext.get(document.elementFromPoint(x, y));
+ },
+
+ /**
+ * Converts a CSS string into an object with a property for each style.
+ *
+ * The sample code below would return an object with 2 properties, one
+ * for background-color and one for color.
+ *
+ * var css = 'background-color: red;color: blue; ';
+ * console.log(Ext.dom.Element.parseStyles(css));
+ *
+ * @static
+ * @param {String} styles A CSS string
+ * @return {Object} styles
+ */
+ parseStyles: function(styles){
+ var out = {},
+ cssRe = this.cssRe,
+ matches;
+
+ if (styles) {
+ // Since we're using the g flag on the regex, we need to set the lastIndex.
+ // This automatically happens on some implementations, but not others, see:
+ // http://stackoverflow.com/questions/2645273/javascript-regular-expression-literal-persists-between-function-calls
+ // http://blog.stevenlevithan.com/archives/fixing-javascript-regexp
+ cssRe.lastIndex = 0;
+ while ((matches = cssRe.exec(styles))) {
+ out[matches[1]] = matches[2];
+ }
+ }
+ return out;
+ }
+});
+
+//TODO Need serious cleanups
+(function(){
+ var doc = document,
+ AbstractElement = Ext.dom.AbstractElement,
+ activeElement = null,
+ isCSS1 = doc.compatMode == "CSS1Compat",
+ flyInstance,
+ fly = function (el) {
+ if (!flyInstance) {
+ flyInstance = new AbstractElement.Fly();
+ }
+ flyInstance.attach(el);
+ return flyInstance;
+ };
+
+ // If the browser does not support document.activeElement we need some assistance.
+ // This covers old Safari 3.2 (4.0 added activeElement along with just about all
+ // other browsers). We need this support to handle issues with old Safari.
+ if (!('activeElement' in doc) && doc.addEventListener) {
+ doc.addEventListener('focus',
+ function (ev) {
+ if (ev && ev.target) {
+ activeElement = (ev.target == doc) ? null : ev.target;
+ }
+ }, true);
+ }
+
+ /*
+ * Helper function to create the function that will restore the selection.
+ */
+ function makeSelectionRestoreFn (activeEl, start, end) {
+ return function () {
+ activeEl.selectionStart = start;
+ activeEl.selectionEnd = end;
+ };
+ }
+
+ AbstractElement.addInheritableStatics({
+ /**
+ * Returns the active element in the DOM. If the browser supports activeElement
+ * on the document, this is returned. If not, the focus is tracked and the active
+ * element is maintained internally.
+ * @return {HTMLElement} The active (focused) element in the document.
+ */
+ getActiveElement: function () {
+ return doc.activeElement || activeElement;
+ },
+
+ /**
+ * Creates a function to call to clean up problems with the work-around for the
+ * WebKit RightMargin bug. The work-around is to add "display: 'inline-block'" to
+ * the element before calling getComputedStyle and then to restore its original
+ * display value. The problem with this is that it corrupts the selection of an
+ * INPUT or TEXTAREA element (as in the "I-beam" goes away but ths focus remains).
+ * To cleanup after this, we need to capture the selection of any such element and
+ * then restore it after we have restored the display style.
+ *
+ * @param {Ext.dom.Element} target The top-most element being adjusted.
+ * @private
+ */
+ getRightMarginFixCleaner: function (target) {
+ var supports = Ext.supports,
+ hasInputBug = supports.DisplayChangeInputSelectionBug,
+ hasTextAreaBug = supports.DisplayChangeTextAreaSelectionBug,
+ activeEl,
+ tag,
+ start,
+ end;
+
+ if (hasInputBug || hasTextAreaBug) {
+ activeEl = doc.activeElement || activeElement; // save a call
+ tag = activeEl && activeEl.tagName;
+
+ if ((hasTextAreaBug && tag == 'TEXTAREA') ||
+ (hasInputBug && tag == 'INPUT' && activeEl.type == 'text')) {
+ if (Ext.dom.Element.isAncestor(target, activeEl)) {
+ start = activeEl.selectionStart;
+ end = activeEl.selectionEnd;
+
+ if (Ext.isNumber(start) && Ext.isNumber(end)) { // to be safe...
+ // We don't create the raw closure here inline because that
+ // will be costly even if we don't want to return it (nested
+ // function decls and exprs are often instantiated on entry
+ // regardless of whether execution ever reaches them):
+ return makeSelectionRestoreFn(activeEl, start, end);
+ }
+ }
+ }
+ }
+
+ return Ext.emptyFn; // avoid special cases, just return a nop
+ },
+
+ getViewWidth: function(full) {
+ return full ? Ext.dom.Element.getDocumentWidth() : Ext.dom.Element.getViewportWidth();
+ },
+
+ getViewHeight: function(full) {
+ return full ? Ext.dom.Element.getDocumentHeight() : Ext.dom.Element.getViewportHeight();
+ },
+
+ getDocumentHeight: function() {
+ return Math.max(!isCSS1 ? doc.body.scrollHeight : doc.documentElement.scrollHeight, Ext.dom.Element.getViewportHeight());
+ },
+
+ getDocumentWidth: function() {
+ return Math.max(!isCSS1 ? doc.body.scrollWidth : doc.documentElement.scrollWidth, Ext.dom.Element.getViewportWidth());
+ },
+
+ getViewportHeight: function(){
+ return Ext.isIE ?
+ (Ext.isStrict ? doc.documentElement.clientHeight : doc.body.clientHeight) :
+ self.innerHeight;
+ },
+
+ getViewportWidth: function() {
+ return (!Ext.isStrict && !Ext.isOpera) ? doc.body.clientWidth :
+ Ext.isIE ? doc.documentElement.clientWidth : self.innerWidth;
+ },
+
+ getY: function(el) {
+ return Ext.dom.Element.getXY(el)[1];
+ },
+
+ getX: function(el) {
+ return Ext.dom.Element.getXY(el)[0];
+ },
+
+ getXY: function(el) {
+ var bd = doc.body,
+ docEl = doc.documentElement,
+ leftBorder = 0,
+ topBorder = 0,
+ ret = [0,0],
+ round = Math.round,
+ box,
+ scroll;
+
+ el = Ext.getDom(el);
+
+ if(el != doc && el != bd){
+ // IE has the potential to throw when getBoundingClientRect called
+ // on element not attached to dom
+ if (Ext.isIE) {
+ try {
+ box = el.getBoundingClientRect();
+ // In some versions of IE, the documentElement (HTML element) will have a 2px border that gets included, so subtract it off
+ topBorder = docEl.clientTop || bd.clientTop;
+ leftBorder = docEl.clientLeft || bd.clientLeft;
+ } catch (ex) {
+ box = { left: 0, top: 0 };
+ }
+ } else {
+ box = el.getBoundingClientRect();
+ }
+
+ scroll = fly(document).getScroll();
+ ret = [round(box.left + scroll.left - leftBorder), round(box.top + scroll.top - topBorder)];
+ }
+ return ret;
+ },
+
+ setXY: function(el, xy) {
+ (el = Ext.fly(el, '_setXY')).position();
+
+ var pts = el.translatePoints(xy),
+ style = el.dom.style,
+ pos;
+
+ for (pos in pts) {
+ if (!isNaN(pts[pos])) {
+ style[pos] = pts[pos] + "px";
+ }
+ }
+ },
+
+ setX: function(el, x) {
+ Ext.dom.Element.setXY(el, [x, false]);
+ },
+
+ setY: function(el, y) {
+ Ext.dom.Element.setXY(el, [false, y]);
+ },
+
+ /**
+ * Serializes a DOM form into a url encoded string
+ * @param {Object} form The form
+ * @return {String} The url encoded form
+ */
+ serializeForm: function(form) {
+ var fElements = form.elements || (document.forms[form] || Ext.getDom(form)).elements,
+ hasSubmit = false,
+ encoder = encodeURIComponent,
+ data = '',
+ eLen = fElements.length,
+ element, name, type, options, hasValue, e,
+ o, oLen, opt;
+
+ for (e = 0; e < eLen; e++) {
+ element = fElements[e];
+ name = element.name;
+ type = element.type;
+ options = element.options;
+
+ if (!element.disabled && name) {
+ if (/select-(one|multiple)/i.test(type)) {
+ oLen = options.length;
+ for (o = 0; o < oLen; o++) {
+ opt = options[o];
+ if (opt.selected) {
+ hasValue = opt.hasAttribute ? opt.hasAttribute('value') : opt.getAttributeNode('value').specified;
+ data += Ext.String.format("{0}={1}&", encoder(name), encoder(hasValue ? opt.value : opt.text));
+ }
+ }
+ } else if (!(/file|undefined|reset|button/i.test(type))) {
+ if (!(/radio|checkbox/i.test(type) && !element.checked) && !(type == 'submit' && hasSubmit)) {
+ data += encoder(name) + '=' + encoder(element.value) + '&';
+ hasSubmit = /submit/i.test(type);
+ }
+ }
+ }
+ }
+ return data.substr(0, data.length - 1);
+ }
+ });
+}());
+
+//@tag dom,core
+//@require Ext.dom.AbstractElement-static
+//@define Ext.dom.AbstractElement-alignment
+
+/**
+ * @class Ext.dom.AbstractElement
+ */
+Ext.dom.AbstractElement.override({
+
+ /**
+ * Gets the x,y coordinates specified by the anchor position on the element.
+ * @param {String} [anchor] The specified anchor position (defaults to "c"). See {@link Ext.dom.Element#alignTo}
+ * for details on supported anchor positions.
+ * @param {Boolean} [local] True to get the local (element top/left-relative) anchor position instead
+ * of page coordinates
+ * @param {Object} [size] An object containing the size to use for calculating anchor position
+ * {width: (target width), height: (target height)} (defaults to the element's current size)
+ * @return {Array} [x, y] An array containing the element's x and y coordinates
+ */
+ getAnchorXY: function(anchor, local, size) {
+ //Passing a different size is useful for pre-calculating anchors,
+ //especially for anchored animations that change the el size.
+ anchor = (anchor || "tl").toLowerCase();
+ size = size || {};
+
+ var me = this,
+ vp = me.dom == document.body || me.dom == document,
+ width = size.width || vp ? window.innerWidth: me.getWidth(),
+ height = size.height || vp ? window.innerHeight: me.getHeight(),
+ xy,
+ rnd = Math.round,
+ myXY = me.getXY(),
+ extraX = vp ? 0: !local ? myXY[0] : 0,
+ extraY = vp ? 0: !local ? myXY[1] : 0,
+ hash = {
+ c: [rnd(width * 0.5), rnd(height * 0.5)],
+ t: [rnd(width * 0.5), 0],
+ l: [0, rnd(height * 0.5)],
+ r: [width, rnd(height * 0.5)],
+ b: [rnd(width * 0.5), height],
+ tl: [0, 0],
+ bl: [0, height],
+ br: [width, height],
+ tr: [width, 0]
+ };
+
+ xy = hash[anchor];
+ return [xy[0] + extraX, xy[1] + extraY];
+ },
+
+ alignToRe: /^([a-z]+)-([a-z]+)(\?)?$/,
+
+ /**
+ * Gets the x,y coordinates to align this element with another element. See {@link Ext.dom.Element#alignTo} for more info on the
+ * supported position values.
+ * @param {Ext.Element/HTMLElement/String} element The element to align to.
+ * @param {String} [position="tl-bl?"] The position to align to.
+ * @param {Array} [offsets=[0,0]] Offset the positioning by [x, y]
+ * @return {Array} [x, y]
+ */
+ getAlignToXY: function(el, position, offsets, local) {
+ local = !!local;
+ el = Ext.get(el);
+
+ if (!el || !el.dom) {
+ throw new Error("Element.alignToXY with an element that doesn't exist");
+ }
+ offsets = offsets || [0, 0];
+
+ if (!position || position == '?') {
+ position = 'tl-bl?';
+ }
+ else if (! (/-/).test(position) && position !== "") {
+ position = 'tl-' + position;
+ }
+ position = position.toLowerCase();
+
+ var me = this,
+ matches = position.match(this.alignToRe),
+ dw = window.innerWidth,
+ dh = window.innerHeight,
+ p1 = "",
+ p2 = "",
+ a1,
+ a2,
+ x,
+ y,
+ swapX,
+ swapY,
+ p1x,
+ p1y,
+ p2x,
+ p2y,
+ width,
+ height,
+ region,
+ constrain;
+
+ if (!matches) {
+ throw "Element.alignTo with an invalid alignment " + position;
+ }
+
+ p1 = matches[1];
+ p2 = matches[2];
+ constrain = !!matches[3];
+
+ //Subtract the aligned el's internal xy from the target's offset xy
+ //plus custom offset to get the aligned el's new offset xy
+ a1 = me.getAnchorXY(p1, true);
+ a2 = el.getAnchorXY(p2, local);
+
+ x = a2[0] - a1[0] + offsets[0];
+ y = a2[1] - a1[1] + offsets[1];
+
+ if (constrain) {
+ width = me.getWidth();
+ height = me.getHeight();
+
+ region = el.getPageBox();
+
+ //If we are at a viewport boundary and the aligned el is anchored on a target border that is
+ //perpendicular to the vp border, allow the aligned el to slide on that border,
+ //otherwise swap the aligned el to the opposite border of the target.
+ p1y = p1.charAt(0);
+ p1x = p1.charAt(p1.length - 1);
+ p2y = p2.charAt(0);
+ p2x = p2.charAt(p2.length - 1);
+
+ swapY = ((p1y == "t" && p2y == "b") || (p1y == "b" && p2y == "t"));
+ swapX = ((p1x == "r" && p2x == "l") || (p1x == "l" && p2x == "r"));
+
+ if (x + width > dw) {
+ x = swapX ? region.left - width: dw - width;
+ }
+ if (x < 0) {
+ x = swapX ? region.right: 0;
+ }
+ if (y + height > dh) {
+ y = swapY ? region.top - height: dh - height;
+ }
+ if (y < 0) {
+ y = swapY ? region.bottom: 0;
+ }
+ }
+
+ return [x, y];
+ },
+
+ // private
+ getAnchor: function(){
+ var data = (this.$cache || this.getCache()).data,
+ anchor;
+
+ if (!this.dom) {
+ return;
+ }
+ anchor = data._anchor;
+
+ if(!anchor){
+ anchor = data._anchor = {};
+ }
+ return anchor;
+ },
+
+ // private ==> used outside of core
+ adjustForConstraints: function(xy, parent) {
+ var vector = this.getConstrainVector(parent, xy);
+ if (vector) {
+ xy[0] += vector[0];
+ xy[1] += vector[1];
+ }
+ return xy;
+ }
+
+});
+
+//@tag dom,core
+//@require Ext.dom.AbstractElement-alignment
+//@define Ext.dom.AbstractElement-insertion
+//@define Ext.dom.AbstractElement
+
+/**
+ * @class Ext.dom.AbstractElement
+ */
+Ext.dom.AbstractElement.addMethods({
+ /**
+ * Appends the passed element(s) to this element
+ * @param {String/HTMLElement/Ext.dom.AbstractElement} el
+ * The id of the node, a DOM Node or an existing Element.
+ * @return {Ext.dom.AbstractElement} This element
+ */
+ appendChild: function(el) {
+ return Ext.get(el).appendTo(this);
+ },
+
+ /**
+ * Appends this element to the passed element
+ * @param {String/HTMLElement/Ext.dom.AbstractElement} el The new parent element.
+ * The id of the node, a DOM Node or an existing Element.
+ * @return {Ext.dom.AbstractElement} This element
+ */
+ appendTo: function(el) {
+ Ext.getDom(el).appendChild(this.dom);
+ return this;
+ },
+
+ /**
+ * Inserts this element before the passed element in the DOM
+ * @param {String/HTMLElement/Ext.dom.AbstractElement} el The element before which this element will be inserted.
+ * The id of the node, a DOM Node or an existing Element.
+ * @return {Ext.dom.AbstractElement} This element
+ */
+ insertBefore: function(el) {
+ el = Ext.getDom(el);
+ el.parentNode.insertBefore(this.dom, el);
+ return this;
+ },
+
+ /**
+ * Inserts this element after the passed element in the DOM
+ * @param {String/HTMLElement/Ext.dom.AbstractElement} el The element to insert after.
+ * The id of the node, a DOM Node or an existing Element.
+ * @return {Ext.dom.AbstractElement} This element
+ */
+ insertAfter: function(el) {
+ el = Ext.getDom(el);
+ el.parentNode.insertBefore(this.dom, el.nextSibling);
+ return this;
+ },
+
+ /**
+ * Inserts (or creates) an element (or DomHelper config) as the first child of this element
+ * @param {String/HTMLElement/Ext.dom.AbstractElement/Object} el The id or element to insert or a DomHelper config
+ * to create and insert
+ * @return {Ext.dom.AbstractElement} The new child
+ */
+ insertFirst: function(el, returnDom) {
+ el = el || {};
+ if (el.nodeType || el.dom || typeof el == 'string') { // element
+ el = Ext.getDom(el);
+ this.dom.insertBefore(el, this.dom.firstChild);
+ return !returnDom ? Ext.get(el) : el;
+ }
+ else { // dh config
+ return this.createChild(el, this.dom.firstChild, returnDom);
+ }
+ },
+
+ /**
+ * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
+ * @param {String/HTMLElement/Ext.dom.AbstractElement/Object/Array} el The id, element to insert or a DomHelper config
+ * to create and insert *or* an array of any of those.
+ * @param {String} [where='before'] 'before' or 'after'
+ * @param {Boolean} [returnDom=false] True to return the .;ll;l,raw DOM element instead of Ext.dom.AbstractElement
+ * @return {Ext.dom.AbstractElement} The inserted Element. If an array is passed, the last inserted element is returned.
+ */
+ insertSibling: function(el, where, returnDom){
+ var me = this,
+ isAfter = (where || 'before').toLowerCase() == 'after',
+ rt, insertEl, eLen, e;
+
+ if (Ext.isArray(el)) {
+ insertEl = me;
+ eLen = el.length;
+
+ for (e = 0; e < eLen; e++) {
+ rt = Ext.fly(insertEl, '_internal').insertSibling(el[e], where, returnDom);
+
+ if (isAfter) {
+ insertEl = rt;
+ }
+ }
+
+ return rt;
+ }
+
+ el = el || {};
+
+ if(el.nodeType || el.dom){
+ rt = me.dom.parentNode.insertBefore(Ext.getDom(el), isAfter ? me.dom.nextSibling : me.dom);
+ if (!returnDom) {
+ rt = Ext.get(rt);
+ }
+ }else{
+ if (isAfter && !me.dom.nextSibling) {
+ rt = Ext.core.DomHelper.append(me.dom.parentNode, el, !returnDom);
+ } else {
+ rt = Ext.core.DomHelper[isAfter ? 'insertAfter' : 'insertBefore'](me.dom, el, !returnDom);
+ }
+ }
+ return rt;
+ },
+
+ /**
+ * Replaces the passed element with this element
+ * @param {String/HTMLElement/Ext.dom.AbstractElement} el The element to replace.
+ * The id of the node, a DOM Node or an existing Element.
+ * @return {Ext.dom.AbstractElement} This element
+ */
+ replace: function(el) {
+ el = Ext.get(el);
+ this.insertBefore(el);
+ el.remove();
+ return this;
+ },
+
+ /**
+ * Replaces this element with the passed element
+ * @param {String/HTMLElement/Ext.dom.AbstractElement/Object} el The new element (id of the node, a DOM Node
+ * or an existing Element) or a DomHelper config of an element to create
+ * @return {Ext.dom.AbstractElement} This element
+ */
+ replaceWith: function(el){
+ var me = this;
+
+ if(el.nodeType || el.dom || typeof el == 'string'){
+ el = Ext.get(el);
+ me.dom.parentNode.insertBefore(el, me.dom);
+ }else{
+ el = Ext.core.DomHelper.insertBefore(me.dom, el);
+ }
+
+ delete Ext.cache[me.id];
+ Ext.removeNode(me.dom);
+ me.id = Ext.id(me.dom = el);
+ Ext.dom.AbstractElement.addToCache(me.isFlyweight ? new Ext.dom.AbstractElement(me.dom) : me);
+ return me;
+ },
+
+ /**
+ * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
+ * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
+ * automatically generated with the specified attributes.
+ * @param {HTMLElement} [insertBefore] a child element of this element
+ * @param {Boolean} [returnDom=false] true to return the dom node instead of creating an Element
+ * @return {Ext.dom.AbstractElement} The new child element
+ */
+ createChild: function(config, insertBefore, returnDom) {
+ config = config || {tag:'div'};
+ if (insertBefore) {
+ return Ext.core.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
+ }
+ else {
+ return Ext.core.DomHelper[!this.dom.firstChild ? 'insertFirst' : 'append'](this.dom, config, returnDom !== true);
+ }
+ },
+
+ /**
+ * Creates and wraps this element with another element
+ * @param {Object} [config] DomHelper element config object for the wrapper element or null for an empty div
+ * @param {Boolean} [returnDom=false] True to return the raw DOM element instead of Ext.dom.AbstractElement
+ * @param {String} [selector] A {@link Ext.dom.Query DomQuery} selector to select a descendant node within the created element to use as the wrapping element.
+ * @return {HTMLElement/Ext.dom.AbstractElement} The newly created wrapper element
+ */
+ wrap: function(config, returnDom, selector) {
+ var newEl = Ext.core.DomHelper.insertBefore(this.dom, config || {tag: "div"}, true),
+ target = newEl;
+
+ if (selector) {
+ target = Ext.DomQuery.selectNode(selector, newEl.dom);
+ }
+
+ target.appendChild(this.dom);
+ return returnDom ? newEl.dom : newEl;
+ },
+
+ /**
+ * Inserts an html fragment into this element
+ * @param {String} where Where to insert the html in relation to this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
+ * See {@link Ext.dom.Helper#insertHtml} for details.
+ * @param {String} html The HTML fragment
+ * @param {Boolean} [returnEl=false] True to return an Ext.dom.AbstractElement
+ * @return {HTMLElement/Ext.dom.AbstractElement} The inserted node (or nearest related if more than 1 inserted)
+ */
+ insertHtml: function(where, html, returnEl) {
+ var el = Ext.core.DomHelper.insertHtml(where, this.dom, html);
+ return returnEl ? Ext.get(el) : el;
+ }
+});
+
+//@tag dom,core
+//@require Ext.dom.AbstractElement-insertion
+//@define Ext.dom.AbstractElement-position
+//@define Ext.dom.AbstractElement
+
+/**
+ * @class Ext.dom.AbstractElement
+ */
+(function(){
+
+var Element = Ext.dom.AbstractElement;
+
+Element.override({
+
+ /**
+ * Gets the current X position of the element based on page coordinates. Element must be part of the DOM
+ * tree to have page coordinates (display:none or elements not appended return false).
+ * @return {Number} The X position of the element
+ */
+ getX: function(el) {
+ return this.getXY(el)[0];
+ },
+
+ /**
+ * Gets the current Y position of the element based on page coordinates. Element must be part of the DOM
+ * tree to have page coordinates (display:none or elements not appended return false).
+ * @return {Number} The Y position of the element
+ */
+ getY: function(el) {
+ return this.getXY(el)[1];
+ },
+
+ /**
+ * Gets the current position of the element based on page coordinates. Element must be part of the DOM
+ * tree to have page coordinates (display:none or elements not appended return false).
+ * @return {Array} The XY position of the element
+ */
+ getXY: function() {
+ // @FEATUREDETECT
+ var point = window.webkitConvertPointFromNodeToPage(this.dom, new WebKitPoint(0, 0));
+ return [point.x, point.y];
+ },
+
+ /**
+ * Returns the offsets of this element from the passed element. Both element must be part of the DOM
+ * tree and not have display:none to have page coordinates.
+ * @param {Ext.Element/HTMLElement/String} element The element to get the offsets from.
+ * @return {Array} The XY page offsets (e.g. [100, -200])
+ */
+ getOffsetsTo: function(el){
+ var o = this.getXY(),
+ e = Ext.fly(el, '_internal').getXY();
+ return [o[0]-e[0],o[1]-e[1]];
+ },
+
+ /**
+ * Sets the X position of the element based on page coordinates. Element must be part of the DOM tree
+ * to have page coordinates (display:none or elements not appended return false).
+ * @param {Number} The X position of the element
+ * @param {Boolean/Object} [animate] True for the default animation, or a standard Element
+ * animation config object
+ * @return {Ext.dom.AbstractElement} this
+ */
+ setX: function(x){
+ return this.setXY([x, this.getY()]);
+ },
+
+ /**
+ * Sets the Y position of the element based on page coordinates. Element must be part of the DOM tree
+ * to have page coordinates (display:none or elements not appended return false).
+ * @param {Number} The Y position of the element
+ * @param {Boolean/Object} [animate] True for the default animation, or a standard Element
+ * animation config object
+ * @return {Ext.dom.AbstractElement} this
+ */
+ setY: function(y) {
+ return this.setXY([this.getX(), y]);
+ },
+
+ /**
+ * Sets the element's left position directly using CSS style (instead of {@link #setX}).
+ * @param {String} left The left CSS property value
+ * @return {Ext.dom.AbstractElement} this
+ */
+ setLeft: function(left) {
+ this.setStyle('left', Element.addUnits(left));
+ return this;
+ },
+
+ /**
+ * Sets the element's top position directly using CSS style (instead of {@link #setY}).
+ * @param {String} top The top CSS property value
+ * @return {Ext.dom.AbstractElement} this
+ */
+ setTop: function(top) {
+ this.setStyle('top', Element.addUnits(top));
+ return this;
+ },
+
+ /**
+ * Sets the element's CSS right style.
+ * @param {String} right The right CSS property value
+ * @return {Ext.dom.AbstractElement} this
+ */
+ setRight: function(right) {
+ this.setStyle('right', Element.addUnits(right));
+ return this;
+ },
+
+ /**
+ * Sets the element's CSS bottom style.
+ * @param {String} bottom The bottom CSS property value
+ * @return {Ext.dom.AbstractElement} this
+ */
+ setBottom: function(bottom) {
+ this.setStyle('bottom', Element.addUnits(bottom));
+ return this;
+ },
+
+ /**
+ * Sets the position of the element in page coordinates, regardless of how the element is positioned.
+ * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
+ * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
+ * @param {Boolean/Object} [animate] True for the default animation, or a standard Element animation config object
+ * @return {Ext.dom.AbstractElement} this
+ */
+ setXY: function(pos) {
+ var me = this,
+ pts,
+ style,
+ pt;
+
+ if (arguments.length > 1) {
+ pos = [pos, arguments[1]];
+ }
+
+ // me.position();
+ pts = me.translatePoints(pos);
+ style = me.dom.style;
+
+ for (pt in pts) {
+ if (!pts.hasOwnProperty(pt)) {
+ continue;
+ }
+ if (!isNaN(pts[pt])) {
+ style[pt] = pts[pt] + "px";
+ }
+ }
+ return me;
+ },
+
+ /**
+ * Gets the left X coordinate
+ * @param {Boolean} local True to get the local css position instead of page coordinate
+ * @return {Number}
+ */
+ getLeft: function(local) {
+ return parseInt(this.getStyle('left'), 10) || 0;
+ },
+
+ /**
+ * Gets the right X coordinate of the element (element X position + element width)
+ * @param {Boolean} local True to get the local css position instead of page coordinate
+ * @return {Number}
+ */
+ getRight: function(local) {
+ return parseInt(this.getStyle('right'), 10) || 0;
+ },
+
+ /**
+ * Gets the top Y coordinate
+ * @param {Boolean} local True to get the local css position instead of page coordinate
+ * @return {Number}
+ */
+ getTop: function(local) {
+ return parseInt(this.getStyle('top'), 10) || 0;
+ },
+
+ /**
+ * Gets the bottom Y coordinate of the element (element Y position + element height)
+ * @param {Boolean} local True to get the local css position instead of page coordinate
+ * @return {Number}
+ */
+ getBottom: function(local) {
+ return parseInt(this.getStyle('bottom'), 10) || 0;
+ },
+
+ /**
+ * Translates the passed page coordinates into left/top css values for this element
+ * @param {Number/Array} x The page x or an array containing [x, y]
+ * @param {Number} [y] The page y, required if x is not an array
+ * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
+ */
+ translatePoints: function(x, y) {
+ y = isNaN(x[1]) ? y : x[1];
+ x = isNaN(x[0]) ? x : x[0];
+ var me = this,
+ relative = me.isStyle('position', 'relative'),
+ o = me.getXY(),
+ l = parseInt(me.getStyle('left'), 10),
+ t = parseInt(me.getStyle('top'), 10);
+
+ l = !isNaN(l) ? l : (relative ? 0 : me.dom.offsetLeft);
+ t = !isNaN(t) ? t : (relative ? 0 : me.dom.offsetTop);
+
+ return {left: (x - o[0] + l), top: (y - o[1] + t)};
+ },
+
+ /**
+ * Sets the element's box. Use getBox() on another element to get a box obj.
+ * If animate is true then width, height, x and y will be animated concurrently.
+ * @param {Object} box The box to fill {x, y, width, height}
+ * @param {Boolean} [adjust] Whether to adjust for box-model issues automatically
+ * @param {Boolean/Object} [animate] true for the default animation or a standard
+ * Element animation config object
+ * @return {Ext.dom.AbstractElement} this
+ */
+ setBox: function(box) {
+ var me = this,
+ width = box.width,
+ height = box.height,
+ top = box.top,
+ left = box.left;
+
+ if (left !== undefined) {
+ me.setLeft(left);
+ }
+ if (top !== undefined) {
+ me.setTop(top);
+ }
+ if (width !== undefined) {
+ me.setWidth(width);
+ }
+ if (height !== undefined) {
+ me.setHeight(height);
+ }
+
+ return this;
+ },
+
+ /**
+ * Return an object defining the area of this Element which can be passed to {@link #setBox} to
+ * set another Element's size/location to match this element.
+ *
+ * @param {Boolean} [contentBox] If true a box for the content of the element is returned.
+ * @param {Boolean} [local] If true the element's left and top are returned instead of page x/y.
+ * @return {Object} box An object in the format:
+ *
+ * {
+ * x: ,
+ * y: ,
+ * width: ,
+ * height: ,
+ * bottom: ,
+ * right:
+ * }
+ *
+ * The returned object may also be addressed as an Array where index 0 contains the X position
+ * and index 1 contains the Y position. So the result may also be used for {@link #setXY}
+ */
+ getBox: function(contentBox, local) {
+ var me = this,
+ dom = me.dom,
+ width = dom.offsetWidth,
+ height = dom.offsetHeight,
+ xy, box, l, r, t, b;
+
+ if (!local) {
+ xy = me.getXY();
+ }
+ else if (contentBox) {
+ xy = [0,0];
+ }
+ else {
+ xy = [parseInt(me.getStyle("left"), 10) || 0, parseInt(me.getStyle("top"), 10) || 0];
+ }
+
+ if (!contentBox) {
+ box = {
+ x: xy[0],
+ y: xy[1],
+ 0: xy[0],
+ 1: xy[1],
+ width: width,
+ height: height
+ };
+ }
+ else {
+ l = me.getBorderWidth.call(me, "l") + me.getPadding.call(me, "l");
+ r = me.getBorderWidth.call(me, "r") + me.getPadding.call(me, "r");
+ t = me.getBorderWidth.call(me, "t") + me.getPadding.call(me, "t");
+ b = me.getBorderWidth.call(me, "b") + me.getPadding.call(me, "b");
+ box = {
+ x: xy[0] + l,
+ y: xy[1] + t,
+ 0: xy[0] + l,
+ 1: xy[1] + t,
+ width: width - (l + r),
+ height: height - (t + b)
+ };
+ }
+
+ box.left = box.x;
+ box.top = box.y;
+ box.right = box.x + box.width;
+ box.bottom = box.y + box.height;
+
+ return box;
+ },
+
+ /**
+ * Return an object defining the area of this Element which can be passed to {@link #setBox} to
+ * set another Element's size/location to match this element.
+ *
+ * @param {Boolean} [asRegion] If true an Ext.util.Region will be returned
+ * @return {Object} box An object in the format
+ *
+ * {
+ * left: ,
+ * top: ,
+ * width: ,
+ * height: ,
+ * bottom: ,
+ * right:
+ * }
+ *
+ * The returned object may also be addressed as an Array where index 0 contains the X position
+ * and index 1 contains the Y position. So the result may also be used for {@link #setXY}
+ */
+ getPageBox: function(getRegion) {
+ var me = this,
+ el = me.dom,
+ w = el.offsetWidth,
+ h = el.offsetHeight,
+ xy = me.getXY(),
+ t = xy[1],
+ r = xy[0] + w,
+ b = xy[1] + h,
+ l = xy[0];
+
+ if (!el) {
+ return new Ext.util.Region();
+ }
+
+ if (getRegion) {
+ return new Ext.util.Region(t, r, b, l);
+ }
+ else {
+ return {
+ left: l,
+ top: t,
+ width: w,
+ height: h,
+ right: r,
+ bottom: b
+ };
+ }
+ }
+});
+
+}());
+
+//@tag dom,core
+//@require Ext.dom.AbstractElement-position
+//@define Ext.dom.AbstractElement-style
+//@define Ext.dom.AbstractElement
+
+/**
+ * @class Ext.dom.AbstractElement
+ */
+(function(){
+ // local style camelizing for speed
+ var Element = Ext.dom.AbstractElement,
+ view = document.defaultView,
+ array = Ext.Array,
+ trimRe = /^\s+|\s+$/g,
+ wordsRe = /\w/g,
+ spacesRe = /\s+/,
+ transparentRe = /^(?:transparent|(?:rgba[(](?:\s*\d+\s*[,]){3}\s*0\s*[)]))$/i,
+ hasClassList = Ext.supports.ClassList,
+ PADDING = 'padding',
+ MARGIN = 'margin',
+ BORDER = 'border',
+ LEFT_SUFFIX = '-left',
+ RIGHT_SUFFIX = '-right',
+ TOP_SUFFIX = '-top',
+ BOTTOM_SUFFIX = '-bottom',
+ WIDTH = '-width',
+ // special markup used throughout Ext when box wrapping elements
+ borders = {l: BORDER + LEFT_SUFFIX + WIDTH, r: BORDER + RIGHT_SUFFIX + WIDTH, t: BORDER + TOP_SUFFIX + WIDTH, b: BORDER + BOTTOM_SUFFIX + WIDTH},
+ paddings = {l: PADDING + LEFT_SUFFIX, r: PADDING + RIGHT_SUFFIX, t: PADDING + TOP_SUFFIX, b: PADDING + BOTTOM_SUFFIX},
+ margins = {l: MARGIN + LEFT_SUFFIX, r: MARGIN + RIGHT_SUFFIX, t: MARGIN + TOP_SUFFIX, b: MARGIN + BOTTOM_SUFFIX};
+
+
+ Element.override({
+
+ /**
+ * This shared object is keyed by style name (e.g., 'margin-left' or 'marginLeft'). The
+ * values are objects with the following properties:
+ *
+ * * `name` (String) : The actual name to be presented to the DOM. This is typically the value
+ * returned by {@link #normalize}.
+ * * `get` (Function) : A hook function that will perform the get on this style. These
+ * functions receive "(dom, el)" arguments. The `dom` parameter is the DOM Element
+ * from which to get ths tyle. The `el` argument (may be null) is the Ext.Element.
+ * * `set` (Function) : A hook function that will perform the set on this style. These
+ * functions receive "(dom, value, el)" arguments. The `dom` parameter is the DOM Element
+ * from which to get ths tyle. The `value` parameter is the new value for the style. The
+ * `el` argument (may be null) is the Ext.Element.
+ *
+ * The `this` pointer is the object that contains `get` or `set`, which means that
+ * `this.name` can be accessed if needed. The hook functions are both optional.
+ * @private
+ */
+ styleHooks: {},
+
+ // private
+ addStyles : function(sides, styles){
+ var totalSize = 0,
+ sidesArr = (sides || '').match(wordsRe),
+ i,
+ len = sidesArr.length,
+ side,
+ styleSides = [];
+
+ if (len == 1) {
+ totalSize = Math.abs(parseFloat(this.getStyle(styles[sidesArr[0]])) || 0);
+ } else if (len) {
+ for (i = 0; i < len; i++) {
+ side = sidesArr[i];
+ styleSides.push(styles[side]);
+ }
+ //Gather all at once, returning a hash
+ styleSides = this.getStyle(styleSides);
+
+ for (i=0; i < len; i++) {
+ side = sidesArr[i];
+ totalSize += Math.abs(parseFloat(styleSides[styles[side]]) || 0);
+ }
+ }
+
+ return totalSize;
+ },
+
+ /**
+ * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
+ * @param {String/String[]} className The CSS classes to add separated by space, or an array of classes
+ * @return {Ext.dom.Element} this
+ * @method
+ */
+ addCls: hasClassList ?
+ function (className) {
+ if (String(className).indexOf('undefined') > -1) {
+ Ext.Logger.warn("called with an undefined className: " + className);
+ }
+ var me = this,
+ dom = me.dom,
+ classList,
+ newCls,
+ i,
+ len,
+ cls;
+
+ if (typeof(className) == 'string') {
+ // split string on spaces to make an array of className
+ className = className.replace(trimRe, '').split(spacesRe);
+ }
+
+ // the gain we have here is that we can skip parsing className and use the
+ // classList.contains method, so now O(M) not O(M+N)
+ if (dom && className && !!(len = className.length)) {
+ if (!dom.className) {
+ dom.className = className.join(' ');
+ } else {
+ classList = dom.classList;
+ for (i = 0; i < len; ++i) {
+ cls = className[i];
+ if (cls) {
+ if (!classList.contains(cls)) {
+ if (newCls) {
+ newCls.push(cls);
+ } else {
+ newCls = dom.className.replace(trimRe, '');
+ newCls = newCls ? [newCls, cls] : [cls];
+ }
+ }
+ }
+ }
+
+ if (newCls) {
+ dom.className = newCls.join(' '); // write to DOM once
+ }
+ }
+ }
+ return me;
+ } :
+ function(className) {
+ if (String(className).indexOf('undefined') > -1) {
+ Ext.Logger.warn("called with an undefined className: '" + className + "'");
+ }
+ var me = this,
+ dom = me.dom,
+ changed,
+ elClasses;
+
+ if (dom && className && className.length) {
+ elClasses = Ext.Element.mergeClsList(dom.className, className);
+ if (elClasses.changed) {
+ dom.className = elClasses.join(' '); // write to DOM once
+ }
+ }
+ return me;
+ },
+
+
+ /**
+ * Removes one or more CSS classes from the element.
+ * @param {String/String[]} className The CSS classes to remove separated by space, or an array of classes
+ * @return {Ext.dom.Element} this
+ */
+ removeCls: function(className) {
+ var me = this,
+ dom = me.dom,
+ len,
+ elClasses;
+
+ if (typeof(className) == 'string') {
+ // split string on spaces to make an array of className
+ className = className.replace(trimRe, '').split(spacesRe);
+ }
+
+ if (dom && dom.className && className && !!(len = className.length)) {
+ if (len == 1 && hasClassList) {
+ if (className[0]) {
+ dom.classList.remove(className[0]); // one DOM write
+ }
+ } else {
+ elClasses = Ext.Element.removeCls(dom.className, className);
+ if (elClasses.changed) {
+ dom.className = elClasses.join(' ');
+ }
+ }
+ }
+ return me;
+ },
+
+ /**
+ * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
+ * @param {String/String[]} className The CSS class to add, or an array of classes
+ * @return {Ext.dom.Element} this
+ */
+ radioCls: function(className) {
+ var cn = this.dom.parentNode.childNodes,
+ v,
+ i, len;
+ className = Ext.isArray(className) ? className: [className];
+ for (i = 0, len = cn.length; i < len; i++) {
+ v = cn[i];
+ if (v && v.nodeType == 1) {
+ Ext.fly(v, '_internal').removeCls(className);
+ }
+ }
+ return this.addCls(className);
+ },
+
+ /**
+ * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
+ * @param {String} className The CSS class to toggle
+ * @return {Ext.dom.Element} this
+ * @method
+ */
+ toggleCls: hasClassList ?
+ function (className) {
+ var me = this,
+ dom = me.dom;
+
+ if (dom) {
+ className = className.replace(trimRe, '');
+ if (className) {
+ dom.classList.toggle(className);
+ }
+ }
+
+ return me;
+ } :
+ function(className) {
+ var me = this;
+ return me.hasCls(className) ? me.removeCls(className) : me.addCls(className);
+ },
+
+ /**
+ * Checks if the specified CSS class exists on this element's DOM node.
+ * @param {String} className The CSS class to check for
+ * @return {Boolean} True if the class exists, else false
+ * @method
+ */
+ hasCls: hasClassList ?
+ function (className) {
+ var dom = this.dom;
+ return (dom && className) ? dom.classList.contains(className) : false;
+ } :
+ function(className) {
+ var dom = this.dom;
+ return dom ? className && (' '+dom.className+' ').indexOf(' '+className+' ') != -1 : false;
+ },
+
+ /**
+ * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
+ * @param {String} oldClassName The CSS class to replace
+ * @param {String} newClassName The replacement CSS class
+ * @return {Ext.dom.Element} this
+ */
+ replaceCls: function(oldClassName, newClassName){
+ return this.removeCls(oldClassName).addCls(newClassName);
+ },
+
+ /**
+ * Checks if the current value of a style is equal to a given value.
+ * @param {String} style property whose value is returned.
+ * @param {String} value to check against.
+ * @return {Boolean} true for when the current value equals the given value.
+ */
+ isStyle: function(style, val) {
+ return this.getStyle(style) == val;
+ },
+
+ /**
+ * Returns a named style property based on computed/currentStyle (primary) and
+ * inline-style if primary is not available.
+ *
+ * @param {String/String[]} property The style property (or multiple property names
+ * in an array) whose value is returned.
+ * @param {Boolean} [inline=false] if `true` only inline styles will be returned.
+ * @return {String/Object} The current value of the style property for this element
+ * (or a hash of named style values if multiple property arguments are requested).
+ * @method
+ */
+ getStyle: function (property, inline) {
+ var me = this,
+ dom = me.dom,
+ multiple = typeof property != 'string',
+ hooks = me.styleHooks,
+ prop = property,
+ props = prop,
+ len = 1,
+ domStyle, camel, values, hook, out, style, i;
+
+ if (multiple) {
+ values = {};
+ prop = props[0];
+ i = 0;
+ if (!(len = props.length)) {
+ return values;
+ }
+ }
+
+ if (!dom || dom.documentElement) {
+ return values || '';
+ }
+
+ domStyle = dom.style;
+
+ if (inline) {
+ style = domStyle;
+ } else {
+ // Caution: Firefox will not render "presentation" (ie. computed styles) in
+ // iframes that are display:none or those inheriting display:none. Similar
+ // issues with legacy Safari.
+ //
+ style = dom.ownerDocument.defaultView.getComputedStyle(dom, null);
+
+ // fallback to inline style if rendering context not available
+ if (!style) {
+ inline = true;
+ style = domStyle;
+ }
+ }
+
+ do {
+ hook = hooks[prop];
+
+ if (!hook) {
+ hooks[prop] = hook = { name: Element.normalize(prop) };
+ }
+
+ if (hook.get) {
+ out = hook.get(dom, me, inline, style);
+ } else {
+ camel = hook.name;
+ out = style[camel];
+ }
+
+ if (!multiple) {
+ return out;
+ }
+
+ values[prop] = out;
+ prop = props[++i];
+ } while (i < len);
+
+ return values;
+ },
+
+ getStyles: function () {
+ var props = Ext.Array.slice(arguments),
+ len = props.length,
+ inline;
+
+ if (len && typeof props[len-1] == 'boolean') {
+ inline = props.pop();
+ }
+
+ return this.getStyle(props, inline);
+ },
+
+ /**
+ * Returns true if the value of the given property is visually transparent. This
+ * may be due to a 'transparent' style value or an rgba value with 0 in the alpha
+ * component.
+ * @param {String} prop The style property whose value is to be tested.
+ * @return {Boolean} True if the style property is visually transparent.
+ */
+ isTransparent: function (prop) {
+ var value = this.getStyle(prop);
+ return value ? transparentRe.test(value) : false;
+ },
+
+ /**
+ * Wrapper for setting style properties, also takes single object parameter of multiple styles.
+ * @param {String/Object} property The style property to be set, or an object of multiple styles.
+ * @param {String} [value] The value to apply to the given property, or null if an object was passed.
+ * @return {Ext.dom.Element} this
+ */
+ setStyle: function(prop, value) {
+ var me = this,
+ dom = me.dom,
+ hooks = me.styleHooks,
+ style = dom.style,
+ name = prop,
+ hook;
+
+ // we don't promote the 2-arg form to object-form to avoid the overhead...
+ if (typeof name == 'string') {
+ hook = hooks[name];
+ if (!hook) {
+ hooks[name] = hook = { name: Element.normalize(name) };
+ }
+ value = (value == null) ? '' : value;
+ if (hook.set) {
+ hook.set(dom, value, me);
+ } else {
+ style[hook.name] = value;
+ }
+ if (hook.afterSet) {
+ hook.afterSet(dom, value, me);
+ }
+ } else {
+ for (name in prop) {
+ if (prop.hasOwnProperty(name)) {
+ hook = hooks[name];
+ if (!hook) {
+ hooks[name] = hook = { name: Element.normalize(name) };
+ }
+ value = prop[name];
+ value = (value == null) ? '' : value;
+ if (hook.set) {
+ hook.set(dom, value, me);
+ } else {
+ style[hook.name] = value;
+ }
+ if (hook.afterSet) {
+ hook.afterSet(dom, value, me);
+ }
+ }
+ }
+ }
+
+ return me;
+ },
+
+ /**
+ * Returns the offset height of the element
+ * @param {Boolean} [contentHeight] true to get the height minus borders and padding
+ * @return {Number} The element's height
+ */
+ getHeight: function(contentHeight) {
+ var dom = this.dom,
+ height = contentHeight ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight;
+ return height > 0 ? height: 0;
+ },
+
+ /**
+ * Returns the offset width of the element
+ * @param {Boolean} [contentWidth] true to get the width minus borders and padding
+ * @return {Number} The element's width
+ */
+ getWidth: function(contentWidth) {
+ var dom = this.dom,
+ width = contentWidth ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth;
+ return width > 0 ? width: 0;
+ },
+
+ /**
+ * Set the width of this Element.
+ * @param {Number/String} width The new width. This may be one of:
+ *
+ * - A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).
+ * - A String used to set the CSS width style. Animation may **not** be used.
+ *
+ * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object
+ * @return {Ext.dom.Element} this
+ */
+ setWidth: function(width) {
+ var me = this;
+ me.dom.style.width = Element.addUnits(width);
+ return me;
+ },
+
+ /**
+ * Set the height of this Element.
+ *
+ * // change the height to 200px and animate with default configuration
+ * Ext.fly('elementId').setHeight(200, true);
+ *
+ * // change the height to 150px and animate with a custom configuration
+ * Ext.fly('elId').setHeight(150, {
+ * duration : 500, // animation will have a duration of .5 seconds
+ * // will change the content to "finished"
+ * callback: function(){ this.{@link #update}("finished"); }
+ * });
+ *
+ * @param {Number/String} height The new height. This may be one of:
+ *
+ * - A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels.)
+ * - A String used to set the CSS height style. Animation may **not** be used.
+ *
+ * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object
+ * @return {Ext.dom.Element} this
+ */
+ setHeight: function(height) {
+ var me = this;
+ me.dom.style.height = Element.addUnits(height);
+ return me;
+ },
+
+ /**
+ * Gets the width of the border(s) for the specified side(s)
+ * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
+ * passing `'lr'` would get the border **l**eft width + the border **r**ight width.
+ * @return {Number} The width of the sides passed added together
+ */
+ getBorderWidth: function(side){
+ return this.addStyles(side, borders);
+ },
+
+ /**
+ * Gets the width of the padding(s) for the specified side(s)
+ * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
+ * passing `'lr'` would get the padding **l**eft + the padding **r**ight.
+ * @return {Number} The padding of the sides passed added together
+ */
+ getPadding: function(side){
+ return this.addStyles(side, paddings);
+ },
+
+ margins : margins,
+
+ /**
+ * More flexible version of {@link #setStyle} for setting style properties.
+ * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
+ * a function which returns such a specification.
+ * @return {Ext.dom.Element} this
+ */
+ applyStyles: function(styles) {
+ if (styles) {
+ var i,
+ len,
+ dom = this.dom;
+
+ if (typeof styles == 'function') {
+ styles = styles.call();
+ }
+ if (typeof styles == 'string') {
+ styles = Ext.util.Format.trim(styles).split(/\s*(?::|;)\s*/);
+ for (i = 0, len = styles.length; i < len;) {
+ dom.style[Element.normalize(styles[i++])] = styles[i++];
+ }
+ }
+ else if (typeof styles == 'object') {
+ this.setStyle(styles);
+ }
+ }
+ },
+
+ /**
+ * Set the size of this Element. If animation is true, both width and height will be animated concurrently.
+ * @param {Number/String} width The new width. This may be one of:
+ *
+ * - A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).
+ * - A String used to set the CSS width style. Animation may **not** be used.
+ * - A size object in the format `{width: widthValue, height: heightValue}`.
+ *
+ * @param {Number/String} height The new height. This may be one of:
+ *
+ * - A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels).
+ * - A String used to set the CSS height style. Animation may **not** be used.
+ *
+ * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object
+ * @return {Ext.dom.Element} this
+ */
+ setSize: function(width, height) {
+ var me = this,
+ style = me.dom.style;
+
+ if (Ext.isObject(width)) {
+ // in case of object from getSize()
+ height = width.height;
+ width = width.width;
+ }
+
+ style.width = Element.addUnits(width);
+ style.height = Element.addUnits(height);
+ return me;
+ },
+
+ /**
+ * Returns the dimensions of the element available to lay content out in.
+ *
+ * If the element (or any ancestor element) has CSS style `display: none`, the dimensions will be zero.
+ *
+ * Example:
+ *
+ * var vpSize = Ext.getBody().getViewSize();
+ *
+ * // all Windows created afterwards will have a default value of 90% height and 95% width
+ * Ext.Window.override({
+ * width: vpSize.width * 0.9,
+ * height: vpSize.height * 0.95
+ * });
+ * // To handle window resizing you would have to hook onto onWindowResize.
+ *
+ * getViewSize utilizes clientHeight/clientWidth which excludes sizing of scrollbars.
+ * To obtain the size including scrollbars, use getStyleSize
+ *
+ * Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc.
+ *
+ * @return {Object} Object describing width and height.
+ * @return {Number} return.width
+ * @return {Number} return.height
+ */
+ getViewSize: function() {
+ var doc = document,
+ dom = this.dom;
+
+ if (dom == doc || dom == doc.body) {
+ return {
+ width: Element.getViewportWidth(),
+ height: Element.getViewportHeight()
+ };
+ }
+ else {
+ return {
+ width: dom.clientWidth,
+ height: dom.clientHeight
+ };
+ }
+ },
+
+ /**
+ * Returns the size of the element.
+ * @param {Boolean} [contentSize] true to get the width/size minus borders and padding
+ * @return {Object} An object containing the element's size:
+ * @return {Number} return.width
+ * @return {Number} return.height
+ */
+ getSize: function(contentSize) {
+ var dom = this.dom;
+ return {
+ width: Math.max(0, contentSize ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth),
+ height: Math.max(0, contentSize ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight)
+ };
+ },
+
+ /**
+ * Forces the browser to repaint this element
+ * @return {Ext.dom.Element} this
+ */
+ repaint: function(){
+ var dom = this.dom;
+ this.addCls(Ext.baseCSSPrefix + 'repaint');
+ setTimeout(function(){
+ Ext.fly(dom).removeCls(Ext.baseCSSPrefix + 'repaint');
+ }, 1);
+ return this;
+ },
+
+ /**
+ * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
+ * then it returns the calculated width of the sides (see getPadding)
+ * @param {String} [sides] Any combination of l, r, t, b to get the sum of those sides
+ * @return {Object/Number}
+ */
+ getMargin: function(side){
+ var me = this,
+ hash = {t:"top", l:"left", r:"right", b: "bottom"},
+ key,
+ o,
+ margins;
+
+ if (!side) {
+ margins = [];
+ for (key in me.margins) {
+ if(me.margins.hasOwnProperty(key)) {
+ margins.push(me.margins[key]);
+ }
+ }
+ o = me.getStyle(margins);
+ if(o && typeof o == 'object') {
+ //now mixin nomalized values (from hash table)
+ for (key in me.margins) {
+ if(me.margins.hasOwnProperty(key)) {
+ o[hash[key]] = parseFloat(o[me.margins[key]]) || 0;
+ }
+ }
+ }
+
+ return o;
+ } else {
+ return me.addStyles.call(me, side, me.margins);
+ }
+ },
+
+ /**
+ * Puts a mask over this element to disable user interaction. Requires core.css.
+ * This method can only be applied to elements which accept child nodes.
+ * @param {String} [msg] A message to display in the mask
+ * @param {String} [msgCls] A css class to apply to the msg element
+ */
+ mask: function(msg, msgCls, transparent) {
+ var me = this,
+ dom = me.dom,
+ data = (me.$cache || me.getCache()).data,
+ el = data.mask,
+ mask,
+ size,
+ cls = '',
+ prefix = Ext.baseCSSPrefix;
+
+ me.addCls(prefix + 'masked');
+ if (me.getStyle("position") == "static") {
+ me.addCls(prefix + 'masked-relative');
+ }
+ if (el) {
+ el.remove();
+ }
+ if (msgCls && typeof msgCls == 'string' ) {
+ cls = ' ' + msgCls;
+ }
+ else {
+ cls = ' ' + prefix + 'mask-gray';
+ }
+
+ mask = me.createChild({
+ cls: prefix + 'mask' + ((transparent !== false) ? '' : (' ' + prefix + 'mask-gray')),
+ html: msg ? ('' + msg + '
') : ''
+ });
+
+ size = me.getSize();
+
+ data.mask = mask;
+
+ if (dom === document.body) {
+ size.height = window.innerHeight;
+ if (me.orientationHandler) {
+ Ext.EventManager.unOrientationChange(me.orientationHandler, me);
+ }
+
+ me.orientationHandler = function() {
+ size = me.getSize();
+ size.height = window.innerHeight;
+ mask.setSize(size);
+ };
+
+ Ext.EventManager.onOrientationChange(me.orientationHandler, me);
+ }
+ mask.setSize(size);
+ if (Ext.is.iPad) {
+ Ext.repaint();
+ }
+ },
+
+ /**
+ * Removes a previously applied mask.
+ */
+ unmask: function() {
+ var me = this,
+ data = (me.$cache || me.getCache()).data,
+ mask = data.mask,
+ prefix = Ext.baseCSSPrefix;
+
+ if (mask) {
+ mask.remove();
+ delete data.mask;
+ }
+ me.removeCls([prefix + 'masked', prefix + 'masked-relative']);
+
+ if (me.dom === document.body) {
+ Ext.EventManager.unOrientationChange(me.orientationHandler, me);
+ delete me.orientationHandler;
+ }
+ }
+ });
+
+ /**
+ * Creates mappings for 'margin-before' to 'marginLeft' (etc.) given the output
+ * map and an ordering pair (e.g., ['left', 'right']). The ordering pair is in
+ * before/after order.
+ */
+ Element.populateStyleMap = function (map, order) {
+ var baseStyles = ['margin-', 'padding-', 'border-width-'],
+ beforeAfter = ['before', 'after'],
+ index, style, name, i;
+
+ for (index = baseStyles.length; index--; ) {
+ for (i = 2; i--; ) {
+ style = baseStyles[index] + beforeAfter[i]; // margin-before
+ // ex: maps margin-before and marginBefore to marginLeft
+ map[Element.normalize(style)] = map[style] = {
+ name: Element.normalize(baseStyles[index] + order[i])
+ };
+ }
+ }
+ };
+
+ Ext.onReady(function () {
+ var supports = Ext.supports,
+ styleHooks,
+ colorStyles, i, name, camel;
+
+ function fixTransparent (dom, el, inline, style) {
+ var value = style[this.name] || '';
+ return transparentRe.test(value) ? 'transparent' : value;
+ }
+
+ function fixRightMargin (dom, el, inline, style) {
+ var result = style.marginRight,
+ domStyle, display;
+
+ // Ignore cases when the margin is correctly reported as 0, the bug only shows
+ // numbers larger.
+ if (result != '0px') {
+ domStyle = dom.style;
+ display = domStyle.display;
+ domStyle.display = 'inline-block';
+ result = (inline ? style : dom.ownerDocument.defaultView.getComputedStyle(dom, null)).marginRight;
+ domStyle.display = display;
+ }
+
+ return result;
+ }
+
+ function fixRightMarginAndInputFocus (dom, el, inline, style) {
+ var result = style.marginRight,
+ domStyle, cleaner, display;
+
+ if (result != '0px') {
+ domStyle = dom.style;
+ cleaner = Element.getRightMarginFixCleaner(dom);
+ display = domStyle.display;
+ domStyle.display = 'inline-block';
+ result = (inline ? style : dom.ownerDocument.defaultView.getComputedStyle(dom, '')).marginRight;
+ domStyle.display = display;
+ cleaner();
+ }
+
+ return result;
+ }
+
+ styleHooks = Element.prototype.styleHooks;
+
+ // Populate the LTR flavors of margin-before et.al. (see Ext.rtl.AbstractElement):
+ Element.populateStyleMap(styleHooks, ['left', 'right']);
+
+ // Ext.supports needs to be initialized (we run very early in the onready sequence),
+ // but it is OK to call Ext.supports.init() more times than necessary...
+ if (supports.init) {
+ supports.init();
+ }
+
+ // Fix bug caused by this: https://bugs.webkit.org/show_bug.cgi?id=13343
+ if (!supports.RightMargin) {
+ styleHooks.marginRight = styleHooks['margin-right'] = {
+ name: 'marginRight',
+ // TODO - Touch should use conditional compilation here or ensure that the
+ // underlying Ext.supports flags are set correctly...
+ get: (supports.DisplayChangeInputSelectionBug || supports.DisplayChangeTextAreaSelectionBug) ?
+ fixRightMarginAndInputFocus : fixRightMargin
+ };
+ }
+
+ if (!supports.TransparentColor) {
+ colorStyles = ['background-color', 'border-color', 'color', 'outline-color'];
+ for (i = colorStyles.length; i--; ) {
+ name = colorStyles[i];
+ camel = Element.normalize(name);
+
+ styleHooks[name] = styleHooks[camel] = {
+ name: camel,
+ get: fixTransparent
+ };
+ }
+ }
+ });
+}());
+
+//@tag dom,core
+//@require Ext.dom.AbstractElement-style
+//@define Ext.dom.AbstractElement-traversal
+//@define Ext.dom.AbstractElement
+
+/**
+ * @class Ext.dom.AbstractElement
+ */
+Ext.dom.AbstractElement.override({
+ /**
+ * Looks at this node and then at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
+ * @param {String} selector The simple selector to test
+ * @param {Number/String/HTMLElement/Ext.Element} [limit]
+ * The max depth to search as a number or an element which causes the upward traversal to stop
+ * and is not considered for inclusion as the result. (defaults to 50 || document.documentElement)
+ * @param {Boolean} [returnEl=false] True to return a Ext.Element object instead of DOM node
+ * @return {HTMLElement} The matching DOM node (or null if no match was found)
+ */
+ findParent: function(simpleSelector, limit, returnEl) {
+ var target = this.dom,
+ topmost = document.documentElement,
+ depth = 0,
+ stopEl;
+
+ limit = limit || 50;
+ if (isNaN(limit)) {
+ stopEl = Ext.getDom(limit);
+ limit = Number.MAX_VALUE;
+ }
+ while (target && target.nodeType == 1 && depth < limit && target != topmost && target != stopEl) {
+ if (Ext.DomQuery.is(target, simpleSelector)) {
+ return returnEl ? Ext.get(target) : target;
+ }
+ depth++;
+ target = target.parentNode;
+ }
+ return null;
+ },
+
+ /**
+ * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
+ * @param {String} selector The simple selector to test
+ * @param {Number/String/HTMLElement/Ext.Element} [limit]
+ * The max depth to search as a number or an element which causes the upward traversal to stop
+ * and is not considered for inclusion as the result. (defaults to 50 || document.documentElement)
+ * @param {Boolean} [returnEl=false] True to return a Ext.Element object instead of DOM node
+ * @return {HTMLElement} The matching DOM node (or null if no match was found)
+ */
+ findParentNode: function(simpleSelector, limit, returnEl) {
+ var p = Ext.fly(this.dom.parentNode, '_internal');
+ return p ? p.findParent(simpleSelector, limit, returnEl) : null;
+ },
+
+ /**
+ * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
+ * This is a shortcut for findParentNode() that always returns an Ext.dom.Element.
+ * @param {String} selector The simple selector to test
+ * @param {Number/String/HTMLElement/Ext.Element} [limit]
+ * The max depth to search as a number or an element which causes the upward traversal to stop
+ * and is not considered for inclusion as the result. (defaults to 50 || document.documentElement)
+ * @return {Ext.Element} The matching DOM node (or null if no match was found)
+ */
+ up: function(simpleSelector, limit) {
+ return this.findParentNode(simpleSelector, limit, true);
+ },
+
+ /**
+ * Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
+ * @param {String} selector The CSS selector
+ * @param {Boolean} [unique] True to create a unique Ext.Element for each element. Defaults to a shared flyweight object.
+ * @return {Ext.CompositeElement} The composite element
+ */
+ select: function(selector, composite) {
+ return Ext.dom.Element.select(selector, this.dom, composite);
+ },
+
+ /**
+ * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
+ * @param {String} selector The CSS selector
+ * @return {HTMLElement[]} An array of the matched nodes
+ */
+ query: function(selector) {
+ return Ext.DomQuery.select(selector, this.dom);
+ },
+
+ /**
+ * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
+ * @param {String} selector The CSS selector
+ * @param {Boolean} [returnDom=false] True to return the DOM node instead of Ext.dom.Element
+ * @return {HTMLElement/Ext.dom.Element} The child Ext.dom.Element (or DOM node if returnDom = true)
+ */
+ down: function(selector, returnDom) {
+ var n = Ext.DomQuery.selectNode(selector, this.dom);
+ return returnDom ? n : Ext.get(n);
+ },
+
+ /**
+ * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
+ * @param {String} selector The CSS selector
+ * @param {Boolean} [returnDom=false] True to return the DOM node instead of Ext.dom.Element.
+ * @return {HTMLElement/Ext.dom.Element} The child Ext.dom.Element (or DOM node if returnDom = true)
+ */
+ child: function(selector, returnDom) {
+ var node,
+ me = this,
+ id;
+
+ // Pull the ID from the DOM (Ext.id also ensures that there *is* an ID).
+ // If this object is a Flyweight, it will not have an ID
+ id = Ext.id(me.dom);
+ // Escape "invalid" chars
+ id = Ext.escapeId(id);
+ node = Ext.DomQuery.selectNode('#' + id + " > " + selector, me.dom);
+ return returnDom ? node : Ext.get(node);
+ },
+
+ /**
+ * Gets the parent node for this element, optionally chaining up trying to match a selector
+ * @param {String} [selector] Find a parent node that matches the passed simple selector
+ * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element
+ * @return {Ext.dom.Element/HTMLElement} The parent node or null
+ */
+ parent: function(selector, returnDom) {
+ return this.matchNode('parentNode', 'parentNode', selector, returnDom);
+ },
+
+ /**
+ * Gets the next sibling, skipping text nodes
+ * @param {String} [selector] Find the next sibling that matches the passed simple selector
+ * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element
+ * @return {Ext.dom.Element/HTMLElement} The next sibling or null
+ */
+ next: function(selector, returnDom) {
+ return this.matchNode('nextSibling', 'nextSibling', selector, returnDom);
+ },
+
+ /**
+ * Gets the previous sibling, skipping text nodes
+ * @param {String} [selector] Find the previous sibling that matches the passed simple selector
+ * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element
+ * @return {Ext.dom.Element/HTMLElement} The previous sibling or null
+ */
+ prev: function(selector, returnDom) {
+ return this.matchNode('previousSibling', 'previousSibling', selector, returnDom);
+ },
+
+
+ /**
+ * Gets the first child, skipping text nodes
+ * @param {String} [selector] Find the next sibling that matches the passed simple selector
+ * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element
+ * @return {Ext.dom.Element/HTMLElement} The first child or null
+ */
+ first: function(selector, returnDom) {
+ return this.matchNode('nextSibling', 'firstChild', selector, returnDom);
+ },
+
+ /**
+ * Gets the last child, skipping text nodes
+ * @param {String} [selector] Find the previous sibling that matches the passed simple selector
+ * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element
+ * @return {Ext.dom.Element/HTMLElement} The last child or null
+ */
+ last: function(selector, returnDom) {
+ return this.matchNode('previousSibling', 'lastChild', selector, returnDom);
+ },
+
+ matchNode: function(dir, start, selector, returnDom) {
+ if (!this.dom) {
+ return null;
+ }
+
+ var n = this.dom[start];
+ while (n) {
+ if (n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))) {
+ return !returnDom ? Ext.get(n) : n;
+ }
+ n = n[dir];
+ }
+ return null;
+ },
+
+ isAncestor: function(element) {
+ return this.self.isAncestor.call(this.self, this.dom, element);
+ }
+});
+
+//@tag dom,core
+//@define Ext.DomHelper
+//@define Ext.core.DomHelper
+//@require Ext.dom.AbstractElement-traversal
+
+/**
+ * @class Ext.DomHelper
+ * @extends Ext.dom.Helper
+ * @alternateClassName Ext.core.DomHelper
+ * @singleton
+ *
+ * The DomHelper class provides a layer of abstraction from DOM and transparently supports creating elements via DOM or
+ * using HTML fragments. It also has the ability to create HTML fragment templates from your DOM building code.
+ *
+ * # DomHelper element specification object
+ *
+ * A specification object is used when creating elements. Attributes of this object are assumed to be element
+ * attributes, except for 4 special attributes:
+ *
+ * - **tag** - The tag name of the element.
+ * - **children** or **cn** - An array of the same kind of element definition objects to be created and appended.
+ * These can be nested as deep as you want.
+ * - **cls** - The class attribute of the element. This will end up being either the "class" attribute on a HTML
+ * fragment or className for a DOM node, depending on whether DomHelper is using fragments or DOM.
+ * - **html** - The innerHTML for the element.
+ *
+ * **NOTE:** For other arbitrary attributes, the value will currently **not** be automatically HTML-escaped prior to
+ * building the element's HTML string. This means that if your attribute value contains special characters that would
+ * not normally be allowed in a double-quoted attribute value, you **must** manually HTML-encode it beforehand (see
+ * {@link Ext.String#htmlEncode}) or risk malformed HTML being created. This behavior may change in a future release.
+ *
+ * # Insertion methods
+ *
+ * Commonly used insertion methods:
+ *
+ * - **{@link #append}**
+ * - **{@link #insertBefore}**
+ * - **{@link #insertAfter}**
+ * - **{@link #overwrite}**
+ * - **{@link #createTemplate}**
+ * - **{@link #insertHtml}**
+ *
+ * # Example
+ *
+ * This is an example, where an unordered list with 3 children items is appended to an existing element with
+ * id 'my-div':
+ *
+ * var dh = Ext.DomHelper; // create shorthand alias
+ * // specification object
+ * var spec = {
+ * id: 'my-ul',
+ * tag: 'ul',
+ * cls: 'my-list',
+ * // append children after creating
+ * children: [ // may also specify 'cn' instead of 'children'
+ * {tag: 'li', id: 'item0', html: 'List Item 0'},
+ * {tag: 'li', id: 'item1', html: 'List Item 1'},
+ * {tag: 'li', id: 'item2', html: 'List Item 2'}
+ * ]
+ * };
+ * var list = dh.append(
+ * 'my-div', // the context element 'my-div' can either be the id or the actual node
+ * spec // the specification object
+ * );
+ *
+ * Element creation specification parameters in this class may also be passed as an Array of specification objects. This
+ * can be used to insert multiple sibling nodes into an existing container very efficiently. For example, to add more
+ * list items to the example above:
+ *
+ * dh.append('my-ul', [
+ * {tag: 'li', id: 'item3', html: 'List Item 3'},
+ * {tag: 'li', id: 'item4', html: 'List Item 4'}
+ * ]);
+ *
+ * # Templating
+ *
+ * The real power is in the built-in templating. Instead of creating or appending any elements, {@link #createTemplate}
+ * returns a Template object which can be used over and over to insert new elements. Revisiting the example above, we
+ * could utilize templating this time:
+ *
+ * // create the node
+ * var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
+ * // get template
+ * var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
+ *
+ * for(var i = 0; i < 5, i++){
+ * tpl.append(list, [i]); // use template to append to the actual node
+ * }
+ *
+ * An example using a template:
+ *
+ * var html = '{2} ';
+ *
+ * var tpl = new Ext.DomHelper.createTemplate(html);
+ * tpl.append('blog-roll', ['link1', 'http://www.edspencer.net/', "Ed's Site"]);
+ * tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin's Site"]);
+ *
+ * The same example using named parameters:
+ *
+ * var html = '{text} ';
+ *
+ * var tpl = new Ext.DomHelper.createTemplate(html);
+ * tpl.append('blog-roll', {
+ * id: 'link1',
+ * url: 'http://www.edspencer.net/',
+ * text: "Ed's Site"
+ * });
+ * tpl.append('blog-roll', {
+ * id: 'link2',
+ * url: 'http://www.dustindiaz.com/',
+ * text: "Dustin's Site"
+ * });
+ *
+ * # Compiling Templates
+ *
+ * Templates are applied using regular expressions. The performance is great, but if you are adding a bunch of DOM
+ * elements using the same template, you can increase performance even further by {@link Ext.Template#compile
+ * "compiling"} the template. The way "{@link Ext.Template#compile compile()}" works is the template is parsed and
+ * broken up at the different variable points and a dynamic function is created and eval'ed. The generated function
+ * performs string concatenation of these parts and the passed variables instead of using regular expressions.
+ *
+ * var html = '{text} ';
+ *
+ * var tpl = new Ext.DomHelper.createTemplate(html);
+ * tpl.compile();
+ *
+ * //... use template like normal
+ *
+ * # Performance Boost
+ *
+ * DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead of DOM can significantly
+ * boost performance.
+ *
+ * Element creation specification parameters may also be strings. If {@link #useDom} is false, then the string is used
+ * as innerHTML. If {@link #useDom} is true, a string specification results in the creation of a text node. Usage:
+ *
+ * Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance
+ *
+ */
+(function() {
+
+// kill repeat to save bytes
+var afterbegin = 'afterbegin',
+ afterend = 'afterend',
+ beforebegin = 'beforebegin',
+ beforeend = 'beforeend',
+ ts = '',
+ tbs = ts+'',
+ tbe = ' '+te,
+ trs = tbs + '',
+ tre = ' '+tbe,
+ detachedDiv = document.createElement('div'),
+ bbValues = ['BeforeBegin', 'previousSibling'],
+ aeValues = ['AfterEnd', 'nextSibling'],
+ bb_ae_PositionHash = {
+ beforebegin: bbValues,
+ afterend: aeValues
+ },
+ fullPositionHash = {
+ beforebegin: bbValues,
+ afterend: aeValues,
+ afterbegin: ['AfterBegin', 'firstChild'],
+ beforeend: ['BeforeEnd', 'lastChild']
+ };
+
+/**
+ * The actual class of which {@link Ext.DomHelper} is instance of.
+ *
+ * Use singleton {@link Ext.DomHelper} instead.
+ *
+ * @private
+ */
+Ext.define('Ext.dom.Helper', {
+ extend: 'Ext.dom.AbstractHelper',
+ requires:['Ext.dom.AbstractElement'],
+
+ tableRe: /^table|tbody|tr|td$/i,
+
+ tableElRe: /td|tr|tbody/i,
+
+ /**
+ * @property {Boolean} useDom
+ * True to force the use of DOM instead of html fragments.
+ */
+ useDom : false,
+
+ /**
+ * Creates new DOM element(s) without inserting them to the document.
+ * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
+ * @return {HTMLElement} The new uninserted node
+ */
+ createDom: function(o, parentNode){
+ var el,
+ doc = document,
+ useSet,
+ attr,
+ val,
+ cn,
+ i, l;
+
+ if (Ext.isArray(o)) { // Allow Arrays of siblings to be inserted
+ el = doc.createDocumentFragment(); // in one shot using a DocumentFragment
+ for (i = 0, l = o.length; i < l; i++) {
+ this.createDom(o[i], el);
+ }
+ } else if (typeof o == 'string') { // Allow a string as a child spec.
+ el = doc.createTextNode(o);
+ } else {
+ el = doc.createElement(o.tag || 'div');
+ useSet = !!el.setAttribute; // In IE some elements don't have setAttribute
+ for (attr in o) {
+ if (!this.confRe.test(attr)) {
+ val = o[attr];
+ if (attr == 'cls') {
+ el.className = val;
+ } else {
+ if (useSet) {
+ el.setAttribute(attr, val);
+ } else {
+ el[attr] = val;
+ }
+ }
+ }
+ }
+ Ext.DomHelper.applyStyles(el, o.style);
+
+ if ((cn = o.children || o.cn)) {
+ this.createDom(cn, el);
+ } else if (o.html) {
+ el.innerHTML = o.html;
+ }
+ }
+ if (parentNode) {
+ parentNode.appendChild(el);
+ }
+ return el;
+ },
+
+ ieTable: function(depth, openingTags, htmlContent, closingTags){
+ detachedDiv.innerHTML = [openingTags, htmlContent, closingTags].join('');
+
+ var i = -1,
+ el = detachedDiv,
+ ns;
+
+ while (++i < depth) {
+ el = el.firstChild;
+ }
+ // If the result is multiple siblings, then encapsulate them into one fragment.
+ ns = el.nextSibling;
+
+ if (ns) {
+ el = document.createDocumentFragment();
+ while (ns) {
+ el.appendChild(ns);
+ ns = ns.nextSibling;
+ }
+ }
+ return el;
+ },
+
+ /**
+ * @private
+ * Nasty code for IE's broken table implementation
+ */
+ insertIntoTable: function(tag, where, destinationEl, html) {
+ var node,
+ before,
+ bb = where == beforebegin,
+ ab = where == afterbegin,
+ be = where == beforeend,
+ ae = where == afterend;
+
+ if (tag == 'td' && (ab || be) || !this.tableElRe.test(tag) && (bb || ae)) {
+ return null;
+ }
+ before = bb ? destinationEl :
+ ae ? destinationEl.nextSibling :
+ ab ? destinationEl.firstChild : null;
+
+ if (bb || ae) {
+ destinationEl = destinationEl.parentNode;
+ }
+
+ if (tag == 'td' || (tag == 'tr' && (be || ab))) {
+ node = this.ieTable(4, trs, html, tre);
+ } else if ((tag == 'tbody' && (be || ab)) ||
+ (tag == 'tr' && (bb || ae))) {
+ node = this.ieTable(3, tbs, html, tbe);
+ } else {
+ node = this.ieTable(2, ts, html, te);
+ }
+ destinationEl.insertBefore(node, before);
+ return node;
+ },
+
+ /**
+ * @private
+ * Fix for IE9 createContextualFragment missing method
+ */
+ createContextualFragment: function(html) {
+ var fragment = document.createDocumentFragment(),
+ length, childNodes;
+
+ detachedDiv.innerHTML = html;
+ childNodes = detachedDiv.childNodes;
+ length = childNodes.length;
+
+ // Move nodes into fragment, don't clone: http://jsperf.com/create-fragment
+ while (length--) {
+ fragment.appendChild(childNodes[0]);
+ }
+ return fragment;
+ },
+
+ applyStyles: function(el, styles) {
+ if (styles) {
+ el = Ext.fly(el);
+ if (typeof styles == "function") {
+ styles = styles.call();
+ }
+ if (typeof styles == "string") {
+ styles = Ext.dom.Element.parseStyles(styles);
+ }
+ if (typeof styles == "object") {
+ el.setStyle(styles);
+ }
+ }
+ },
+
+ /**
+ * Alias for {@link #markup}.
+ * @inheritdoc Ext.dom.AbstractHelper#markup
+ */
+ createHtml: function(spec) {
+ return this.markup(spec);
+ },
+
+ doInsert: function(el, o, returnElement, pos, sibling, append) {
+
+ el = el.dom || Ext.getDom(el);
+
+ var newNode;
+
+ if (this.useDom) {
+ newNode = this.createDom(o, null);
+
+ if (append) {
+ el.appendChild(newNode);
+ }
+ else {
+ (sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el);
+ }
+
+ } else {
+ newNode = this.insertHtml(pos, el, this.markup(o));
+ }
+ return returnElement ? Ext.get(newNode, true) : newNode;
+ },
+
+ /**
+ * Creates new DOM element(s) and overwrites the contents of el with them.
+ * @param {String/HTMLElement/Ext.Element} el The context element
+ * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
+ * @param {Boolean} [returnElement] true to return an Ext.Element
+ * @return {HTMLElement/Ext.Element} The new node
+ */
+ overwrite: function(el, html, returnElement) {
+ var newNode;
+
+ el = Ext.getDom(el);
+ html = this.markup(html);
+
+ // IE Inserting HTML into a table/tbody/tr requires extra processing: http://www.ericvasilik.com/2006/07/code-karma.html
+ if (Ext.isIE && this.tableRe.test(el.tagName)) {
+ // Clearing table elements requires removal of all elements.
+ while (el.firstChild) {
+ el.removeChild(el.firstChild);
+ }
+ if (html) {
+ newNode = this.insertHtml('afterbegin', el, html);
+ return returnElement ? Ext.get(newNode) : newNode;
+ }
+ return null;
+ }
+ el.innerHTML = html;
+ return returnElement ? Ext.get(el.firstChild) : el.firstChild;
+ },
+
+ insertHtml: function(where, el, html) {
+ var hashVal,
+ range,
+ rangeEl,
+ setStart,
+ frag;
+
+ where = where.toLowerCase();
+
+ // Has fast HTML insertion into existing DOM: http://www.w3.org/TR/html5/apis-in-html-documents.html#insertadjacenthtml
+ if (el.insertAdjacentHTML) {
+
+ // IE's incomplete table implementation: http://www.ericvasilik.com/2006/07/code-karma.html
+ if (Ext.isIE && this.tableRe.test(el.tagName) && (frag = this.insertIntoTable(el.tagName.toLowerCase(), where, el, html))) {
+ return frag;
+ }
+
+ if ((hashVal = fullPositionHash[where])) {
+ el.insertAdjacentHTML(hashVal[0], html);
+ return el[hashVal[1]];
+ }
+ // if (not IE and context element is an HTMLElement) or TextNode
+ } else {
+ // we cannot insert anything inside a textnode so...
+ if (el.nodeType === 3) {
+ where = where === 'afterbegin' ? 'beforebegin' : where;
+ where = where === 'beforeend' ? 'afterend' : where;
+ }
+ range = Ext.supports.CreateContextualFragment ? el.ownerDocument.createRange() : undefined;
+ setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before');
+ if (bb_ae_PositionHash[where]) {
+ if (range) {
+ range[setStart](el);
+ frag = range.createContextualFragment(html);
+ } else {
+ frag = this.createContextualFragment(html);
+ }
+ el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);
+ return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];
+ } else {
+ rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';
+ if (el.firstChild) {
+ if (range) {
+ range[setStart](el[rangeEl]);
+ frag = range.createContextualFragment(html);
+ } else {
+ frag = this.createContextualFragment(html);
+ }
+
+ if (where == afterbegin) {
+ el.insertBefore(frag, el.firstChild);
+ } else {
+ el.appendChild(frag);
+ }
+ } else {
+ el.innerHTML = html;
+ }
+ return el[rangeEl];
+ }
+ }
+ Ext.Error.raise({
+ sourceClass: 'Ext.DomHelper',
+ sourceMethod: 'insertHtml',
+ htmlToInsert: html,
+ targetElement: el,
+ msg: 'Illegal insertion point reached: "' + where + '"'
+ });
+ },
+
+ /**
+ * Creates a new Ext.Template from the DOM object spec.
+ * @param {Object} o The DOM object spec (and children)
+ * @return {Ext.Template} The new template
+ */
+ createTemplate: function(o) {
+ var html = this.markup(o);
+ return new Ext.Template(html);
+ }
+
+}, function() {
+ Ext.ns('Ext.core');
+ Ext.DomHelper = Ext.core.DomHelper = new this;
+});
+
+
+}());
+
+//@tag dom,core
+//@require Helper.js
+//@define Ext.dom.Query
+//@define Ext.core.Query
+//@define Ext.DomQuery
+
+/*
+ * This is code is also distributed under MIT license for use
+ * with jQuery and prototype JavaScript libraries.
+ */
+/**
+ * @class Ext.dom.Query
+ * @alternateClassName Ext.DomQuery
+ * @alternateClassName Ext.core.DomQuery
+ * @singleton
+ *
+ * Provides high performance selector/xpath processing by compiling queries into reusable functions. New pseudo classes
+ * and matchers can be plugged. It works on HTML and XML documents (if a content node is passed in).
+ *
+ * DomQuery supports most of the [CSS3 selectors spec][1], along with some custom selectors and basic XPath.
+ *
+ * All selectors, attribute filters and pseudos below can be combined infinitely in any order. For example
+ * `div.foo:nth-child(odd)[@foo=bar].bar:first` would be a perfectly valid selector. Node filters are processed
+ * in the order in which they appear, which allows you to optimize your queries for your document structure.
+ *
+ * ## Element Selectors:
+ *
+ * - **`*`** any element
+ * - **`E`** an element with the tag E
+ * - **`E F`** All descendent elements of E that have the tag F
+ * - **`E > F`** or **E/F** all direct children elements of E that have the tag F
+ * - **`E + F`** all elements with the tag F that are immediately preceded by an element with the tag E
+ * - **`E ~ F`** all elements with the tag F that are preceded by a sibling element with the tag E
+ *
+ * ## Attribute Selectors:
+ *
+ * The use of `@` and quotes are optional. For example, `div[@foo='bar']` is also a valid attribute selector.
+ *
+ * - **`E[foo]`** has an attribute "foo"
+ * - **`E[foo=bar]`** has an attribute "foo" that equals "bar"
+ * - **`E[foo^=bar]`** has an attribute "foo" that starts with "bar"
+ * - **`E[foo$=bar]`** has an attribute "foo" that ends with "bar"
+ * - **`E[foo*=bar]`** has an attribute "foo" that contains the substring "bar"
+ * - **`E[foo%=2]`** has an attribute "foo" that is evenly divisible by 2
+ * - **`E[foo!=bar]`** attribute "foo" does not equal "bar"
+ *
+ * ## Pseudo Classes:
+ *
+ * - **`E:first-child`** E is the first child of its parent
+ * - **`E:last-child`** E is the last child of its parent
+ * - **`E:nth-child(_n_)`** E is the _n_th child of its parent (1 based as per the spec)
+ * - **`E:nth-child(odd)`** E is an odd child of its parent
+ * - **`E:nth-child(even)`** E is an even child of its parent
+ * - **`E:only-child`** E is the only child of its parent
+ * - **`E:checked`** E is an element that is has a checked attribute that is true (e.g. a radio or checkbox)
+ * - **`E:first`** the first E in the resultset
+ * - **`E:last`** the last E in the resultset
+ * - **`E:nth(_n_)`** the _n_th E in the resultset (1 based)
+ * - **`E:odd`** shortcut for :nth-child(odd)
+ * - **`E:even`** shortcut for :nth-child(even)
+ * - **`E:contains(foo)`** E's innerHTML contains the substring "foo"
+ * - **`E:nodeValue(foo)`** E contains a textNode with a nodeValue that equals "foo"
+ * - **`E:not(S)`** an E element that does not match simple selector S
+ * - **`E:has(S)`** an E element that has a descendent that matches simple selector S
+ * - **`E:next(S)`** an E element whose next sibling matches simple selector S
+ * - **`E:prev(S)`** an E element whose previous sibling matches simple selector S
+ * - **`E:any(S1|S2|S2)`** an E element which matches any of the simple selectors S1, S2 or S3
+ *
+ * ## CSS Value Selectors:
+ *
+ * - **`E{display=none}`** css value "display" that equals "none"
+ * - **`E{display^=none}`** css value "display" that starts with "none"
+ * - **`E{display$=none}`** css value "display" that ends with "none"
+ * - **`E{display*=none}`** css value "display" that contains the substring "none"
+ * - **`E{display%=2}`** css value "display" that is evenly divisible by 2
+ * - **`E{display!=none}`** css value "display" that does not equal "none"
+ *
+ * [1]: http://www.w3.org/TR/2005/WD-css3-selectors-20051215/#selectors
+ */
+Ext.ns('Ext.core');
+
+Ext.dom.Query = Ext.core.DomQuery = Ext.DomQuery = (function(){
+ var cache = {},
+ simpleCache = {},
+ valueCache = {},
+ nonSpace = /\S/,
+ trimRe = /^\s+|\s+$/g,
+ tplRe = /\{(\d+)\}/g,
+ modeRe = /^(\s?[\/>+~]\s?|\s|$)/,
+ tagTokenRe = /^(#)?([\w\-\*\\]+)/,
+ nthRe = /(\d*)n\+?(\d*)/,
+ nthRe2 = /\D/,
+ startIdRe = /^\s*\#/,
+ // This is for IE MSXML which does not support expandos.
+ // IE runs the same speed using setAttribute, however FF slows way down
+ // and Safari completely fails so they need to continue to use expandos.
+ isIE = window.ActiveXObject ? true : false,
+ key = 30803,
+ longHex = /\\([0-9a-fA-F]{6})/g,
+ shortHex = /\\([0-9a-fA-F]{1,6})\s{0,1}/g,
+ nonHex = /\\([^0-9a-fA-F]{1})/g,
+ escapes = /\\/g,
+ num, hasEscapes,
+
+ // replaces a long hex regex match group with the appropriate ascii value
+ // $args indicate regex match pos
+ longHexToChar = function($0, $1) {
+ return String.fromCharCode(parseInt($1, 16));
+ },
+
+ // converts a shortHex regex match to the long form
+ shortToLongHex = function($0, $1) {
+ while ($1.length < 6) {
+ $1 = '0' + $1;
+ }
+ return '\\' + $1;
+ },
+
+ // converts a single char escape to long escape form
+ charToLongHex = function($0, $1) {
+ num = $1.charCodeAt(0).toString(16);
+ if (num.length === 1) {
+ num = '0' + num;
+ }
+ return '\\0000' + num;
+ },
+
+ // Un-escapes an input selector string. Assumes all escape sequences have been
+ // normalized to the css '\\0000##' 6-hex-digit style escape sequence :
+ // will not handle any other escape formats
+ unescapeCssSelector = function (selector) {
+ return (hasEscapes)
+ ? selector.replace(longHex, longHexToChar)
+ : selector;
+ },
+
+ // checks if the path has escaping & does any appropriate replacements
+ setupEscapes = function(path){
+ hasEscapes = (path.indexOf('\\') > -1);
+ if (hasEscapes) {
+ path = path
+ .replace(shortHex, shortToLongHex)
+ .replace(nonHex, charToLongHex)
+ .replace(escapes, '\\\\'); // double the '\' for js compilation
+ }
+ return path;
+ };
+
+ // this eval is stop the compressor from
+ // renaming the variable to something shorter
+ eval("var batch = 30803;");
+
+ // Retrieve the child node from a particular
+ // parent at the specified index.
+ function child(parent, index){
+ var i = 0,
+ n = parent.firstChild;
+ while(n){
+ if(n.nodeType == 1){
+ if(++i == index){
+ return n;
+ }
+ }
+ n = n.nextSibling;
+ }
+ return null;
+ }
+
+ // retrieve the next element node
+ function next(n){
+ while((n = n.nextSibling) && n.nodeType != 1);
+ return n;
+ }
+
+ // retrieve the previous element node
+ function prev(n){
+ while((n = n.previousSibling) && n.nodeType != 1);
+ return n;
+ }
+
+ // Mark each child node with a nodeIndex skipping and
+ // removing empty text nodes.
+ function children(parent){
+ var n = parent.firstChild,
+ nodeIndex = -1,
+ nextNode;
+ while(n){
+ nextNode = n.nextSibling;
+ // clean worthless empty nodes.
+ if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
+ parent.removeChild(n);
+ }else{
+ // add an expando nodeIndex
+ n.nodeIndex = ++nodeIndex;
+ }
+ n = nextNode;
+ }
+ return this;
+ }
+
+ // nodeSet - array of nodes
+ // cls - CSS Class
+ function byClassName(nodeSet, cls){
+ cls = unescapeCssSelector(cls);
+ if(!cls){
+ return nodeSet;
+ }
+ var result = [], ri = -1,
+ i, ci;
+ for(i = 0, ci; ci = nodeSet[i]; i++){
+ if((' '+ci.className+' ').indexOf(cls) != -1){
+ result[++ri] = ci;
+ }
+ }
+ return result;
+ }
+
+ function attrValue(n, attr){
+ // if its an array, use the first node.
+ if(!n.tagName && typeof n.length != "undefined"){
+ n = n[0];
+ }
+ if(!n){
+ return null;
+ }
+
+ if(attr == "for"){
+ return n.htmlFor;
+ }
+ if(attr == "class" || attr == "className"){
+ return n.className;
+ }
+ return n.getAttribute(attr) || n[attr];
+
+ }
+
+
+ // ns - nodes
+ // mode - false, /, >, +, ~
+ // tagName - defaults to "*"
+ function getNodes(ns, mode, tagName){
+ var result = [], ri = -1, cs,
+ i, ni, j, ci, cn, utag, n, cj;
+ if(!ns){
+ return result;
+ }
+ tagName = tagName || "*";
+ // convert to array
+ if(typeof ns.getElementsByTagName != "undefined"){
+ ns = [ns];
+ }
+
+ // no mode specified, grab all elements by tagName
+ // at any depth
+ if(!mode){
+ for(i = 0, ni; ni = ns[i]; i++){
+ cs = ni.getElementsByTagName(tagName);
+ for(j = 0, ci; ci = cs[j]; j++){
+ result[++ri] = ci;
+ }
+ }
+ // Direct Child mode (/ or >)
+ // E > F or E/F all direct children elements of E that have the tag
+ } else if(mode == "/" || mode == ">"){
+ utag = tagName.toUpperCase();
+ for(i = 0, ni, cn; ni = ns[i]; i++){
+ cn = ni.childNodes;
+ for(j = 0, cj; cj = cn[j]; j++){
+ if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
+ result[++ri] = cj;
+ }
+ }
+ }
+ // Immediately Preceding mode (+)
+ // E + F all elements with the tag F that are immediately preceded by an element with the tag E
+ }else if(mode == "+"){
+ utag = tagName.toUpperCase();
+ for(i = 0, n; n = ns[i]; i++){
+ while((n = n.nextSibling) && n.nodeType != 1);
+ if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
+ result[++ri] = n;
+ }
+ }
+ // Sibling mode (~)
+ // E ~ F all elements with the tag F that are preceded by a sibling element with the tag E
+ }else if(mode == "~"){
+ utag = tagName.toUpperCase();
+ for(i = 0, n; n = ns[i]; i++){
+ while((n = n.nextSibling)){
+ if (n.nodeName == utag || n.nodeName == tagName || tagName == '*'){
+ result[++ri] = n;
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ function concat(a, b){
+ if(b.slice){
+ return a.concat(b);
+ }
+ for(var i = 0, l = b.length; i < l; i++){
+ a[a.length] = b[i];
+ }
+ return a;
+ }
+
+ function byTag(cs, tagName){
+ if(cs.tagName || cs == document){
+ cs = [cs];
+ }
+ if(!tagName){
+ return cs;
+ }
+ var result = [], ri = -1,
+ i, ci;
+ tagName = tagName.toLowerCase();
+ for(i = 0, ci; ci = cs[i]; i++){
+ if(ci.nodeType == 1 && ci.tagName.toLowerCase() == tagName){
+ result[++ri] = ci;
+ }
+ }
+ return result;
+ }
+
+ function byId(cs, id){
+ id = unescapeCssSelector(id);
+ if(cs.tagName || cs == document){
+ cs = [cs];
+ }
+ if(!id){
+ return cs;
+ }
+ var result = [], ri = -1,
+ i, ci;
+ for(i = 0, ci; ci = cs[i]; i++){
+ if(ci && ci.id == id){
+ result[++ri] = ci;
+ return result;
+ }
+ }
+ return result;
+ }
+
+ // operators are =, !=, ^=, $=, *=, %=, |= and ~=
+ // custom can be "{"
+ function byAttribute(cs, attr, value, op, custom){
+ var result = [],
+ ri = -1,
+ useGetStyle = custom == "{",
+ fn = Ext.DomQuery.operators[op],
+ a,
+ xml,
+ hasXml,
+ i, ci;
+
+ value = unescapeCssSelector(value);
+
+ for(i = 0, ci; ci = cs[i]; i++){
+ // skip non-element nodes.
+ if(ci.nodeType != 1){
+ continue;
+ }
+ // only need to do this for the first node
+ if(!hasXml){
+ xml = Ext.DomQuery.isXml(ci);
+ hasXml = true;
+ }
+
+ // we only need to change the property names if we're dealing with html nodes, not XML
+ if(!xml){
+ if(useGetStyle){
+ a = Ext.DomQuery.getStyle(ci, attr);
+ } else if (attr == "class" || attr == "className"){
+ a = ci.className;
+ } else if (attr == "for"){
+ a = ci.htmlFor;
+ } else if (attr == "href"){
+ // getAttribute href bug
+ // http://www.glennjones.net/Post/809/getAttributehrefbug.htm
+ a = ci.getAttribute("href", 2);
+ } else{
+ a = ci.getAttribute(attr);
+ }
+ }else{
+ a = ci.getAttribute(attr);
+ }
+ if((fn && fn(a, value)) || (!fn && a)){
+ result[++ri] = ci;
+ }
+ }
+ return result;
+ }
+
+ function byPseudo(cs, name, value){
+ value = unescapeCssSelector(value);
+ return Ext.DomQuery.pseudos[name](cs, value);
+ }
+
+ function nodupIEXml(cs){
+ var d = ++key,
+ r,
+ i, len, c;
+ cs[0].setAttribute("_nodup", d);
+ r = [cs[0]];
+ for(i = 1, len = cs.length; i < len; i++){
+ c = cs[i];
+ if(!c.getAttribute("_nodup") != d){
+ c.setAttribute("_nodup", d);
+ r[r.length] = c;
+ }
+ }
+ for(i = 0, len = cs.length; i < len; i++){
+ cs[i].removeAttribute("_nodup");
+ }
+ return r;
+ }
+
+ function nodup(cs){
+ if(!cs){
+ return [];
+ }
+ var len = cs.length, c, i, r = cs, cj, ri = -1, d, j;
+ if(!len || typeof cs.nodeType != "undefined" || len == 1){
+ return cs;
+ }
+ if(isIE && typeof cs[0].selectSingleNode != "undefined"){
+ return nodupIEXml(cs);
+ }
+ d = ++key;
+ cs[0]._nodup = d;
+ for(i = 1; c = cs[i]; i++){
+ if(c._nodup != d){
+ c._nodup = d;
+ }else{
+ r = [];
+ for(j = 0; j < i; j++){
+ r[++ri] = cs[j];
+ }
+ for(j = i+1; cj = cs[j]; j++){
+ if(cj._nodup != d){
+ cj._nodup = d;
+ r[++ri] = cj;
+ }
+ }
+ return r;
+ }
+ }
+ return r;
+ }
+
+ function quickDiffIEXml(c1, c2){
+ var d = ++key,
+ r = [],
+ i, len;
+ for(i = 0, len = c1.length; i < len; i++){
+ c1[i].setAttribute("_qdiff", d);
+ }
+ for(i = 0, len = c2.length; i < len; i++){
+ if(c2[i].getAttribute("_qdiff") != d){
+ r[r.length] = c2[i];
+ }
+ }
+ for(i = 0, len = c1.length; i < len; i++){
+ c1[i].removeAttribute("_qdiff");
+ }
+ return r;
+ }
+
+ function quickDiff(c1, c2){
+ var len1 = c1.length,
+ d = ++key,
+ r = [],
+ i, len;
+ if(!len1){
+ return c2;
+ }
+ if(isIE && typeof c1[0].selectSingleNode != "undefined"){
+ return quickDiffIEXml(c1, c2);
+ }
+ for(i = 0; i < len1; i++){
+ c1[i]._qdiff = d;
+ }
+ for(i = 0, len = c2.length; i < len; i++){
+ if(c2[i]._qdiff != d){
+ r[r.length] = c2[i];
+ }
+ }
+ return r;
+ }
+
+ function quickId(ns, mode, root, id){
+ if(ns == root){
+ id = unescapeCssSelector(id);
+ var d = root.ownerDocument || root;
+ return d.getElementById(id);
+ }
+ ns = getNodes(ns, mode, "*");
+ return byId(ns, id);
+ }
+
+ return {
+ getStyle : function(el, name){
+ return Ext.fly(el).getStyle(name);
+ },
+ /**
+ * Compiles a selector/xpath query into a reusable function. The returned function
+ * takes one parameter "root" (optional), which is the context node from where the query should start.
+ * @param {String} selector The selector/xpath query
+ * @param {String} [type="select"] Either "select" or "simple" for a simple selector match
+ * @return {Function}
+ */
+ compile : function(path, type){
+ type = type || "select";
+
+ // setup fn preamble
+ var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"],
+ mode,
+ lastPath,
+ matchers = Ext.DomQuery.matchers,
+ matchersLn = matchers.length,
+ modeMatch,
+ // accept leading mode switch
+ lmode = path.match(modeRe),
+ tokenMatch, matched, j, t, m;
+
+ path = setupEscapes(path);
+
+ if(lmode && lmode[1]){
+ fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
+ path = path.replace(lmode[1], "");
+ }
+
+ // strip leading slashes
+ while(path.substr(0, 1)=="/"){
+ path = path.substr(1);
+ }
+
+ while(path && lastPath != path){
+ lastPath = path;
+ tokenMatch = path.match(tagTokenRe);
+ if(type == "select"){
+ if(tokenMatch){
+ // ID Selector
+ if(tokenMatch[1] == "#"){
+ fn[fn.length] = 'n = quickId(n, mode, root, "'+tokenMatch[2]+'");';
+ }else{
+ fn[fn.length] = 'n = getNodes(n, mode, "'+tokenMatch[2]+'");';
+ }
+ path = path.replace(tokenMatch[0], "");
+ }else if(path.substr(0, 1) != '@'){
+ fn[fn.length] = 'n = getNodes(n, mode, "*");';
+ }
+ // type of "simple"
+ }else{
+ if(tokenMatch){
+ if(tokenMatch[1] == "#"){
+ fn[fn.length] = 'n = byId(n, "'+tokenMatch[2]+'");';
+ }else{
+ fn[fn.length] = 'n = byTag(n, "'+tokenMatch[2]+'");';
+ }
+ path = path.replace(tokenMatch[0], "");
+ }
+ }
+ while(!(modeMatch = path.match(modeRe))){
+ matched = false;
+ for(j = 0; j < matchersLn; j++){
+ t = matchers[j];
+ m = path.match(t.re);
+ if(m){
+ fn[fn.length] = t.select.replace(tplRe, function(x, i){
+ return m[i];
+ });
+ path = path.replace(m[0], "");
+ matched = true;
+ break;
+ }
+ }
+ // prevent infinite loop on bad selector
+ if(!matched){
+ Ext.Error.raise({
+ sourceClass: 'Ext.DomQuery',
+ sourceMethod: 'compile',
+ msg: 'Error parsing selector. Parsing failed at "' + path + '"'
+ });
+ }
+ }
+ if(modeMatch[1]){
+ fn[fn.length] = 'mode="'+modeMatch[1].replace(trimRe, "")+'";';
+ path = path.replace(modeMatch[1], "");
+ }
+ }
+ // close fn out
+ fn[fn.length] = "return nodup(n);\n}";
+
+ // eval fn and return it
+ eval(fn.join(""));
+ return f;
+ },
+
+ /**
+ * Selects an array of DOM nodes using JavaScript-only implementation.
+ *
+ * Use {@link #select} to take advantage of browsers built-in support for CSS selectors.
+ * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
+ * @param {HTMLElement/String} [root=document] The start of the query.
+ * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are
+ * no matches, and empty Array is returned.
+ */
+ jsSelect: function(path, root, type){
+ // set root to doc if not specified.
+ root = root || document;
+
+ if(typeof root == "string"){
+ root = document.getElementById(root);
+ }
+ var paths = path.split(","),
+ results = [],
+ i, len, subPath, result;
+
+ // loop over each selector
+ for(i = 0, len = paths.length; i < len; i++){
+ subPath = paths[i].replace(trimRe, "");
+ // compile and place in cache
+ if(!cache[subPath]){
+ // When we compile, escaping is handled inside the compile method
+ cache[subPath] = Ext.DomQuery.compile(subPath, type);
+ if(!cache[subPath]){
+ Ext.Error.raise({
+ sourceClass: 'Ext.DomQuery',
+ sourceMethod: 'jsSelect',
+ msg: subPath + ' is not a valid selector'
+ });
+ }
+ } else {
+ // If we've already compiled, we still need to check if the
+ // selector has escaping and setup the appropriate flags
+ setupEscapes(subPath);
+ }
+ result = cache[subPath](root);
+ if(result && result != document){
+ results = results.concat(result);
+ }
+ }
+
+ // if there were multiple selectors, make sure dups
+ // are eliminated
+ if(paths.length > 1){
+ return nodup(results);
+ }
+ return results;
+ },
+
+ isXml: function(el) {
+ var docEl = (el ? el.ownerDocument || el : 0).documentElement;
+ return docEl ? docEl.nodeName !== "HTML" : false;
+ },
+
+ /**
+ * Selects an array of DOM nodes by CSS/XPath selector.
+ *
+ * Uses [document.querySelectorAll][0] if browser supports that, otherwise falls back to
+ * {@link Ext.dom.Query#jsSelect} to do the work.
+ *
+ * Aliased as {@link Ext#query}.
+ *
+ * [0]: https://developer.mozilla.org/en/DOM/document.querySelectorAll
+ *
+ * @param {String} path The selector/xpath query
+ * @param {HTMLElement} [root=document] The start of the query.
+ * @return {HTMLElement[]} An array of DOM elements (not a NodeList as returned by `querySelectorAll`).
+ * @param {String} [type="select"] Either "select" or "simple" for a simple selector match (only valid when
+ * used when the call is deferred to the jsSelect method)
+ * @method
+ */
+ select : document.querySelectorAll ? function(path, root, type) {
+ root = root || document;
+ if (!Ext.DomQuery.isXml(root)) {
+ try {
+ /*
+ * This checking here is to "fix" the behaviour of querySelectorAll
+ * for non root document queries. The way qsa works is intentional,
+ * however it's definitely not the expected way it should work.
+ * When descendant selectors are used, only the lowest selector must be inside the root!
+ * More info: http://ejohn.org/blog/thoughts-on-queryselectorall/
+ * So we create a descendant selector by prepending the root's ID, and query the parent node.
+ * UNLESS the root has no parent in which qsa will work perfectly.
+ *
+ * We only modify the path for single selectors (ie, no multiples),
+ * without a full parser it makes it difficult to do this correctly.
+ */
+ if (root.parentNode && (root.nodeType !== 9) && path.indexOf(',') === -1 && !startIdRe.test(path)) {
+ path = '#' + Ext.escapeId(Ext.id(root)) + ' ' + path;
+ root = root.parentNode;
+ }
+ return Ext.Array.toArray(root.querySelectorAll(path));
+ }
+ catch (e) {
+ }
+ }
+ return Ext.DomQuery.jsSelect.call(this, path, root, type);
+ } : function(path, root, type) {
+ return Ext.DomQuery.jsSelect.call(this, path, root, type);
+ },
+
+ /**
+ * Selects a single element.
+ * @param {String} selector The selector/xpath query
+ * @param {HTMLElement} [root=document] The start of the query.
+ * @return {HTMLElement} The DOM element which matched the selector.
+ */
+ selectNode : function(path, root){
+ return Ext.DomQuery.select(path, root)[0];
+ },
+
+ /**
+ * Selects the value of a node, optionally replacing null with the defaultValue.
+ * @param {String} selector The selector/xpath query
+ * @param {HTMLElement} [root=document] The start of the query.
+ * @param {String} [defaultValue] When specified, this is return as empty value.
+ * @return {String}
+ */
+ selectValue : function(path, root, defaultValue){
+ path = path.replace(trimRe, "");
+ if (!valueCache[path]) {
+ valueCache[path] = Ext.DomQuery.compile(path, "select");
+ } else {
+ setupEscapes(path);
+ }
+
+ var n = valueCache[path](root),
+ v;
+
+ n = n[0] ? n[0] : n;
+
+ // overcome a limitation of maximum textnode size
+ // Rumored to potentially crash IE6 but has not been confirmed.
+ // http://reference.sitepoint.com/javascript/Node/normalize
+ // https://developer.mozilla.org/En/DOM/Node.normalize
+ if (typeof n.normalize == 'function') {
+ n.normalize();
+ }
+
+ v = (n && n.firstChild ? n.firstChild.nodeValue : null);
+ return ((v === null||v === undefined||v==='') ? defaultValue : v);
+ },
+
+ /**
+ * Selects the value of a node, parsing integers and floats.
+ * Returns the defaultValue, or 0 if none is specified.
+ * @param {String} selector The selector/xpath query
+ * @param {HTMLElement} [root=document] The start of the query.
+ * @param {Number} [defaultValue] When specified, this is return as empty value.
+ * @return {Number}
+ */
+ selectNumber : function(path, root, defaultValue){
+ var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0);
+ return parseFloat(v);
+ },
+
+ /**
+ * Returns true if the passed element(s) match the passed simple selector
+ * (e.g. `div.some-class` or `span:first-child`)
+ * @param {String/HTMLElement/HTMLElement[]} el An element id, element or array of elements
+ * @param {String} selector The simple selector to test
+ * @return {Boolean}
+ */
+ is : function(el, ss){
+ if(typeof el == "string"){
+ el = document.getElementById(el);
+ }
+ var isArray = Ext.isArray(el),
+ result = Ext.DomQuery.filter(isArray ? el : [el], ss);
+ return isArray ? (result.length == el.length) : (result.length > 0);
+ },
+
+ /**
+ * Filters an array of elements to only include matches of a simple selector
+ * (e.g. `div.some-class` or `span:first-child`)
+ * @param {HTMLElement[]} el An array of elements to filter
+ * @param {String} selector The simple selector to test
+ * @param {Boolean} nonMatches If true, it returns the elements that DON'T match the selector instead of the
+ * ones that match
+ * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are no matches, and empty
+ * Array is returned.
+ */
+ filter : function(els, ss, nonMatches){
+ ss = ss.replace(trimRe, "");
+ if (!simpleCache[ss]) {
+ simpleCache[ss] = Ext.DomQuery.compile(ss, "simple");
+ } else {
+ setupEscapes(ss);
+ }
+
+ var result = simpleCache[ss](els);
+ return nonMatches ? quickDiff(result, els) : result;
+ },
+
+ /**
+ * Collection of matching regular expressions and code snippets.
+ * Each capture group within `()` will be replace the `{}` in the select
+ * statement as specified by their index.
+ */
+ matchers : [{
+ re: /^\.([\w\-\\]+)/,
+ select: 'n = byClassName(n, " {1} ");'
+ }, {
+ re: /^\:([\w\-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
+ select: 'n = byPseudo(n, "{1}", "{2}");'
+ },{
+ re: /^(?:([\[\{])(?:@)?([\w\-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
+ select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
+ }, {
+ re: /^#([\w\-\\]+)/,
+ select: 'n = byId(n, "{1}");'
+ },{
+ re: /^@([\w\-]+)/,
+ select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
+ }
+ ],
+
+ /**
+ * Collection of operator comparison functions.
+ * The default operators are `=`, `!=`, `^=`, `$=`, `*=`, `%=`, `|=` and `~=`.
+ * New operators can be added as long as the match the format *c*`=` where *c*
+ * is any character other than space, `>`, or `<`.
+ */
+ operators : {
+ "=" : function(a, v){
+ return a == v;
+ },
+ "!=" : function(a, v){
+ return a != v;
+ },
+ "^=" : function(a, v){
+ return a && a.substr(0, v.length) == v;
+ },
+ "$=" : function(a, v){
+ return a && a.substr(a.length-v.length) == v;
+ },
+ "*=" : function(a, v){
+ return a && a.indexOf(v) !== -1;
+ },
+ "%=" : function(a, v){
+ return (a % v) == 0;
+ },
+ "|=" : function(a, v){
+ return a && (a == v || a.substr(0, v.length+1) == v+'-');
+ },
+ "~=" : function(a, v){
+ return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
+ }
+ },
+
+ /**
+ * Object hash of "pseudo class" filter functions which are used when filtering selections.
+ * Each function is passed two parameters:
+ *
+ * - **c** : Array
+ * An Array of DOM elements to filter.
+ *
+ * - **v** : String
+ * The argument (if any) supplied in the selector.
+ *
+ * A filter function returns an Array of DOM elements which conform to the pseudo class.
+ * In addition to the provided pseudo classes listed above such as `first-child` and `nth-child`,
+ * developers may add additional, custom psuedo class filters to select elements according to application-specific requirements.
+ *
+ * For example, to filter `a` elements to only return links to __external__ resources:
+ *
+ * Ext.DomQuery.pseudos.external = function(c, v){
+ * var r = [], ri = -1;
+ * for(var i = 0, ci; ci = c[i]; i++){
+ * // Include in result set only if it's a link to an external resource
+ * if(ci.hostname != location.hostname){
+ * r[++ri] = ci;
+ * }
+ * }
+ * return r;
+ * };
+ *
+ * Then external links could be gathered with the following statement:
+ *
+ * var externalLinks = Ext.select("a:external");
+ */
+ pseudos : {
+ "first-child" : function(c){
+ var r = [], ri = -1, n,
+ i, ci;
+ for(i = 0; (ci = n = c[i]); i++){
+ while((n = n.previousSibling) && n.nodeType != 1);
+ if(!n){
+ r[++ri] = ci;
+ }
+ }
+ return r;
+ },
+
+ "last-child" : function(c){
+ var r = [], ri = -1, n,
+ i, ci;
+ for(i = 0; (ci = n = c[i]); i++){
+ while((n = n.nextSibling) && n.nodeType != 1);
+ if(!n){
+ r[++ri] = ci;
+ }
+ }
+ return r;
+ },
+
+ "nth-child" : function(c, a) {
+ var r = [], ri = -1,
+ m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a),
+ f = (m[1] || 1) - 0, l = m[2] - 0,
+ i, n, j, cn, pn;
+ for(i = 0; n = c[i]; i++){
+ pn = n.parentNode;
+ if (batch != pn._batch) {
+ j = 0;
+ for(cn = pn.firstChild; cn; cn = cn.nextSibling){
+ if(cn.nodeType == 1){
+ cn.nodeIndex = ++j;
+ }
+ }
+ pn._batch = batch;
+ }
+ if (f == 1) {
+ if (l == 0 || n.nodeIndex == l){
+ r[++ri] = n;
+ }
+ } else if ((n.nodeIndex + l) % f == 0){
+ r[++ri] = n;
+ }
+ }
+
+ return r;
+ },
+
+ "only-child" : function(c){
+ var r = [], ri = -1,
+ i, ci;
+ for(i = 0; ci = c[i]; i++){
+ if(!prev(ci) && !next(ci)){
+ r[++ri] = ci;
+ }
+ }
+ return r;
+ },
+
+ "empty" : function(c){
+ var r = [], ri = -1,
+ i, ci, cns, j, cn, empty;
+ for(i = 0, ci; ci = c[i]; i++){
+ cns = ci.childNodes;
+ j = 0;
+ empty = true;
+ while(cn = cns[j]){
+ ++j;
+ if(cn.nodeType == 1 || cn.nodeType == 3){
+ empty = false;
+ break;
+ }
+ }
+ if(empty){
+ r[++ri] = ci;
+ }
+ }
+ return r;
+ },
+
+ "contains" : function(c, v){
+ var r = [], ri = -1,
+ i, ci;
+ for(i = 0; ci = c[i]; i++){
+ if((ci.textContent||ci.innerText||ci.text||'').indexOf(v) != -1){
+ r[++ri] = ci;
+ }
+ }
+ return r;
+ },
+
+ "nodeValue" : function(c, v){
+ var r = [], ri = -1,
+ i, ci;
+ for(i = 0; ci = c[i]; i++){
+ if(ci.firstChild && ci.firstChild.nodeValue == v){
+ r[++ri] = ci;
+ }
+ }
+ return r;
+ },
+
+ "checked" : function(c){
+ var r = [], ri = -1,
+ i, ci;
+ for(i = 0; ci = c[i]; i++){
+ if(ci.checked == true){
+ r[++ri] = ci;
+ }
+ }
+ return r;
+ },
+
+ "not" : function(c, ss){
+ return Ext.DomQuery.filter(c, ss, true);
+ },
+
+ "any" : function(c, selectors){
+ var ss = selectors.split('|'),
+ r = [], ri = -1, s,
+ i, ci, j;
+ for(i = 0; ci = c[i]; i++){
+ for(j = 0; s = ss[j]; j++){
+ if(Ext.DomQuery.is(ci, s)){
+ r[++ri] = ci;
+ break;
+ }
+ }
+ }
+ return r;
+ },
+
+ "odd" : function(c){
+ return this["nth-child"](c, "odd");
+ },
+
+ "even" : function(c){
+ return this["nth-child"](c, "even");
+ },
+
+ "nth" : function(c, a){
+ return c[a-1] || [];
+ },
+
+ "first" : function(c){
+ return c[0] || [];
+ },
+
+ "last" : function(c){
+ return c[c.length-1] || [];
+ },
+
+ "has" : function(c, ss){
+ var s = Ext.DomQuery.select,
+ r = [], ri = -1,
+ i, ci;
+ for(i = 0; ci = c[i]; i++){
+ if(s(ss, ci).length > 0){
+ r[++ri] = ci;
+ }
+ }
+ return r;
+ },
+
+ "next" : function(c, ss){
+ var is = Ext.DomQuery.is,
+ r = [], ri = -1,
+ i, ci, n;
+ for(i = 0; ci = c[i]; i++){
+ n = next(ci);
+ if(n && is(n, ss)){
+ r[++ri] = ci;
+ }
+ }
+ return r;
+ },
+
+ "prev" : function(c, ss){
+ var is = Ext.DomQuery.is,
+ r = [], ri = -1,
+ i, ci, n;
+ for(i = 0; ci = c[i]; i++){
+ n = prev(ci);
+ if(n && is(n, ss)){
+ r[++ri] = ci;
+ }
+ }
+ return r;
+ }
+ }
+ };
+}());
+
+/**
+ * Shorthand of {@link Ext.dom.Query#select}
+ * @member Ext
+ * @method query
+ * @inheritdoc Ext.dom.Query#select
+ */
+Ext.query = Ext.DomQuery.select;
+
+
+//@tag dom,core
+//@require Query.js
+//@define Ext.dom.Element
+//@require Ext.dom.AbstractElement
+
+/**
+ * @class Ext.dom.Element
+ * @alternateClassName Ext.Element
+ * @alternateClassName Ext.core.Element
+ * @extend Ext.dom.AbstractElement
+ *
+ * Encapsulates a DOM element, adding simple DOM manipulation facilities, normalizing for browser differences.
+ *
+ * All instances of this class inherit the methods of {@link Ext.fx.Anim} making visual effects easily available to all
+ * DOM elements.
+ *
+ * Note that the events documented in this class are not Ext events, they encapsulate browser events. Some older browsers
+ * may not support the full range of events. Which events are supported is beyond the control of Ext JS.
+ *
+ * Usage:
+ *
+ * // by id
+ * var el = Ext.get("my-div");
+ *
+ * // by DOM element reference
+ * var el = Ext.get(myDivElement);
+ *
+ * # Animations
+ *
+ * When an element is manipulated, by default there is no animation.
+ *
+ * var el = Ext.get("my-div");
+ *
+ * // no animation
+ * el.setWidth(100);
+ *
+ * Many of the functions for manipulating an element have an optional "animate" parameter. This parameter can be
+ * specified as boolean (true) for default animation effects.
+ *
+ * // default animation
+ * el.setWidth(100, true);
+ *
+ * To configure the effects, an object literal with animation options to use as the Element animation configuration
+ * object can also be specified. Note that the supported Element animation configuration options are a subset of the
+ * {@link Ext.fx.Anim} animation options specific to Fx effects. The supported Element animation configuration options
+ * are:
+ *
+ * Option Default Description
+ * --------- -------- ---------------------------------------------
+ * {@link Ext.fx.Anim#duration duration} 350 The duration of the animation in milliseconds
+ * {@link Ext.fx.Anim#easing easing} easeOut The easing method
+ * {@link Ext.fx.Anim#callback callback} none A function to execute when the anim completes
+ * {@link Ext.fx.Anim#scope scope} this The scope (this) of the callback function
+ *
+ * Usage:
+ *
+ * // Element animation options object
+ * var opt = {
+ * {@link Ext.fx.Anim#duration duration}: 1000,
+ * {@link Ext.fx.Anim#easing easing}: 'elasticIn',
+ * {@link Ext.fx.Anim#callback callback}: this.foo,
+ * {@link Ext.fx.Anim#scope scope}: this
+ * };
+ * // animation with some options set
+ * el.setWidth(100, opt);
+ *
+ * The Element animation object being used for the animation will be set on the options object as "anim", which allows
+ * you to stop or manipulate the animation. Here is an example:
+ *
+ * // using the "anim" property to get the Anim object
+ * if(opt.anim.isAnimated()){
+ * opt.anim.stop();
+ * }
+ *
+ * # Composite (Collections of) Elements
+ *
+ * For working with collections of Elements, see {@link Ext.CompositeElement}
+ *
+ * @constructor
+ * Creates new Element directly.
+ * @param {String/HTMLElement} element
+ * @param {Boolean} [forceNew] By default the constructor checks to see if there is already an instance of this
+ * element in the cache and if there is it returns the same instance. This will skip that check (useful for extending
+ * this class).
+ * @return {Object}
+ */
+(function() {
+
+var HIDDEN = 'hidden',
+ DOC = document,
+ VISIBILITY = "visibility",
+ DISPLAY = "display",
+ NONE = "none",
+ XMASKED = Ext.baseCSSPrefix + "masked",
+ XMASKEDRELATIVE = Ext.baseCSSPrefix + "masked-relative",
+ EXTELMASKMSG = Ext.baseCSSPrefix + "mask-msg",
+ bodyRe = /^body/i,
+ visFly,
+
+ // speedy lookup for elements never to box adjust
+ noBoxAdjust = Ext.isStrict ? {
+ select: 1
+ }: {
+ input: 1,
+ select: 1,
+ textarea: 1
+ },
+
+ // Pseudo for use by cacheScrollValues
+ isScrolled = function(c) {
+ var r = [], ri = -1,
+ i, ci;
+ for (i = 0; ci = c[i]; i++) {
+ if (ci.scrollTop > 0 || ci.scrollLeft > 0) {
+ r[++ri] = ci;
+ }
+ }
+ return r;
+ },
+
+ Element = Ext.define('Ext.dom.Element', {
+
+ extend: 'Ext.dom.AbstractElement',
+
+ alternateClassName: ['Ext.Element', 'Ext.core.Element'],
+
+ addUnits: function() {
+ return this.self.addUnits.apply(this.self, arguments);
+ },
+
+ /**
+ * Tries to focus the element. Any exceptions are caught and ignored.
+ * @param {Number} [defer] Milliseconds to defer the focus
+ * @return {Ext.dom.Element} this
+ */
+ focus: function(defer, /* private */ dom) {
+ var me = this,
+ scrollTop,
+ body;
+
+ dom = dom || me.dom;
+ body = (dom.ownerDocument || DOC).body || DOC.body;
+ try {
+ if (Number(defer)) {
+ Ext.defer(me.focus, defer, me, [null, dom]);
+ } else {
+ // Focusing a large element, the browser attempts to scroll as much of it into view
+ // as possible. We need to override this behaviour.
+ if (dom.offsetHeight > Element.getViewHeight()) {
+ scrollTop = body.scrollTop;
+ }
+ dom.focus();
+ if (scrollTop !== undefined) {
+ body.scrollTop = scrollTop;
+ }
+ }
+ } catch(e) {
+ }
+ return me;
+ },
+
+ /**
+ * Tries to blur the element. Any exceptions are caught and ignored.
+ * @return {Ext.dom.Element} this
+ */
+ blur: function() {
+ try {
+ this.dom.blur();
+ } catch(e) {
+ }
+ return this;
+ },
+
+ /**
+ * Tests various css rules/browsers to determine if this element uses a border box
+ * @return {Boolean}
+ */
+ isBorderBox: function() {
+ var box = Ext.isBorderBox;
+ if (box) {
+ box = !((this.dom.tagName || "").toLowerCase() in noBoxAdjust);
+ }
+ return box;
+ },
+
+ /**
+ * Sets up event handlers to call the passed functions when the mouse is moved into and out of the Element.
+ * @param {Function} overFn The function to call when the mouse enters the Element.
+ * @param {Function} outFn The function to call when the mouse leaves the Element.
+ * @param {Object} [scope] The scope (`this` reference) in which the functions are executed. Defaults
+ * to the Element's DOM element.
+ * @param {Object} [options] Options for the listener. See {@link Ext.util.Observable#addListener the
+ * options parameter}.
+ * @return {Ext.dom.Element} this
+ */
+ hover: function(overFn, outFn, scope, options) {
+ var me = this;
+ me.on('mouseenter', overFn, scope || me.dom, options);
+ me.on('mouseleave', outFn, scope || me.dom, options);
+ return me;
+ },
+
+ /**
+ * Returns the value of a namespaced attribute from the element's underlying DOM node.
+ * @param {String} namespace The namespace in which to look for the attribute
+ * @param {String} name The attribute name
+ * @return {String} The attribute value
+ */
+ getAttributeNS: function(ns, name) {
+ return this.getAttribute(name, ns);
+ },
+
+ getAttribute: (Ext.isIE && !(Ext.isIE9 && DOC.documentMode === 9)) ?
+ function(name, ns) {
+ var d = this.dom,
+ type;
+ if (ns) {
+ type = typeof d[ns + ":" + name];
+ if (type != 'undefined' && type != 'unknown') {
+ return d[ns + ":" + name] || null;
+ }
+ return null;
+ }
+ if (name === "for") {
+ name = "htmlFor";
+ }
+ return d[name] || null;
+ } : function(name, ns) {
+ var d = this.dom;
+ if (ns) {
+ return d.getAttributeNS(ns, name) || d.getAttribute(ns + ":" + name);
+ }
+ return d.getAttribute(name) || d[name] || null;
+ },
+
+ /**
+ * When an element is moved around in the DOM, or is hidden using `display:none`, it loses layout, and therefore
+ * all scroll positions of all descendant elements are lost.
+ *
+ * This function caches them, and returns a function, which when run will restore the cached positions.
+ * In the following example, the Panel is moved from one Container to another which will cause it to lose all scroll positions:
+ *
+ * var restoreScroll = myPanel.el.cacheScrollValues();
+ * myOtherContainer.add(myPanel);
+ * restoreScroll();
+ *
+ * @return {Function} A function which will restore all descentant elements of this Element to their scroll
+ * positions recorded when this function was executed. Be aware that the returned function is a closure which has
+ * captured the scope of `cacheScrollValues`, so take care to derefence it as soon as not needed - if is it is a `var`
+ * it will drop out of scope, and the reference will be freed.
+ */
+ cacheScrollValues: function() {
+ var me = this,
+ scrolledDescendants,
+ el, i,
+ scrollValues = [],
+ result = function() {
+ for (i = 0; i < scrolledDescendants.length; i++) {
+ el = scrolledDescendants[i];
+ el.scrollLeft = scrollValues[i][0];
+ el.scrollTop = scrollValues[i][1];
+ }
+ };
+
+ if (!Ext.DomQuery.pseudos.isScrolled) {
+ Ext.DomQuery.pseudos.isScrolled = isScrolled;
+ }
+ scrolledDescendants = me.query(':isScrolled');
+ for (i = 0; i < scrolledDescendants.length; i++) {
+ el = scrolledDescendants[i];
+ scrollValues[i] = [el.scrollLeft, el.scrollTop];
+ }
+ return result;
+ },
+
+ /**
+ * @property {Boolean} autoBoxAdjust
+ * True to automatically adjust width and height settings for box-model issues.
+ */
+ autoBoxAdjust: true,
+
+ /**
+ * Checks whether the element is currently visible using both visibility and display properties.
+ * @param {Boolean} [deep=false] True to walk the dom and see if parent elements are hidden.
+ * If false, the function only checks the visibility of the element itself and it may return
+ * `true` even though a parent is not visible.
+ * @return {Boolean} `true` if the element is currently visible, else `false`
+ */
+ isVisible : function(deep) {
+ var me = this,
+ dom = me.dom,
+ stopNode = dom.ownerDocument.documentElement;
+
+ if (!visFly) {
+ visFly = new Element.Fly();
+ }
+
+ while (dom !== stopNode) {
+ // We're invisible if we hit a nonexistent parentNode or a document
+ // fragment or computed style visibility:hidden or display:none
+ if (!dom || dom.nodeType === 11 || (visFly.attach(dom)).isStyle(VISIBILITY, HIDDEN) || visFly.isStyle(DISPLAY, NONE)) {
+ return false;
+ }
+ // Quit now unless we are being asked to check parent nodes.
+ if (!deep) {
+ break;
+ }
+ dom = dom.parentNode;
+ }
+ return true;
+ },
+
+ /**
+ * Returns true if display is not "none"
+ * @return {Boolean}
+ */
+ isDisplayed : function() {
+ return !this.isStyle(DISPLAY, NONE);
+ },
+
+ /**
+ * Convenience method for setVisibilityMode(Element.DISPLAY)
+ * @param {String} [display] What to set display to when visible
+ * @return {Ext.dom.Element} this
+ */
+ enableDisplayMode : function(display) {
+ var me = this;
+
+ me.setVisibilityMode(Element.DISPLAY);
+
+ if (!Ext.isEmpty(display)) {
+ (me.$cache || me.getCache()).data.originalDisplay = display;
+ }
+
+ return me;
+ },
+
+ /**
+ * Puts a mask over this element to disable user interaction. Requires core.css.
+ * This method can only be applied to elements which accept child nodes.
+ * @param {String} [msg] A message to display in the mask
+ * @param {String} [msgCls] A css class to apply to the msg element
+ * @return {Ext.dom.Element} The mask element
+ */
+ mask : function(msg, msgCls /* private - passed by AbstractComponent.mask to avoid the need to interrogate the DOM to get the height*/, elHeight) {
+ var me = this,
+ dom = me.dom,
+ // In some cases, setExpression will exist but not be of a function type,
+ // so we check it explicitly here to stop IE throwing errors
+ setExpression = dom.style.setExpression,
+ data = (me.$cache || me.getCache()).data,
+ maskEl = data.maskEl,
+ maskMsg = data.maskMsg;
+
+ if (!(bodyRe.test(dom.tagName) && me.getStyle('position') == 'static')) {
+ me.addCls(XMASKEDRELATIVE);
+ }
+
+ // We always needs to recreate the mask since the DOM element may have been re-created
+ if (maskEl) {
+ maskEl.remove();
+ }
+
+ if (maskMsg) {
+ maskMsg.remove();
+ }
+
+ Ext.DomHelper.append(dom, [{
+ cls : Ext.baseCSSPrefix + "mask"
+ }, {
+ cls : msgCls ? EXTELMASKMSG + " " + msgCls : EXTELMASKMSG,
+ cn : {
+ tag: 'div',
+ html: msg || ''
+ }
+ }]);
+
+ maskMsg = Ext.get(dom.lastChild);
+ maskEl = Ext.get(maskMsg.dom.previousSibling);
+ data.maskMsg = maskMsg;
+ data.maskEl = maskEl;
+
+ me.addCls(XMASKED);
+ maskEl.setDisplayed(true);
+
+ if (typeof msg == 'string') {
+ maskMsg.setDisplayed(true);
+ maskMsg.center(me);
+ } else {
+ maskMsg.setDisplayed(false);
+ }
+ // NOTE: CSS expressions are resource intensive and to be used only as a last resort
+ // These expressions are removed as soon as they are no longer necessary - in the unmask method.
+ // In normal use cases an element will be masked for a limited period of time.
+ // Fix for https://sencha.jira.com/browse/EXTJSIV-19.
+ // IE6 strict mode and IE6-9 quirks mode takes off left+right padding when calculating width!
+ if (!Ext.supports.IncludePaddingInWidthCalculation && setExpression) {
+ // In an occasional case setExpression will throw an exception
+ try {
+ maskEl.dom.style.setExpression('width', 'this.parentNode.clientWidth + "px"');
+ } catch (e) {}
+ }
+
+ // Some versions and modes of IE subtract top+bottom padding when calculating height.
+ // Different versions from those which make the same error for width!
+ if (!Ext.supports.IncludePaddingInHeightCalculation && setExpression) {
+ // In an occasional case setExpression will throw an exception
+ try {
+ maskEl.dom.style.setExpression('height', 'this.parentNode.' + (dom == DOC.body ? 'scrollHeight' : 'offsetHeight') + ' + "px"');
+ } catch (e) {}
+ }
+ // ie will not expand full height automatically
+ else if (Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && me.getStyle('height') == 'auto') {
+ maskEl.setSize(undefined, elHeight || me.getHeight());
+ }
+ return maskEl;
+ },
+
+ /**
+ * Hides a previously applied mask.
+ */
+ unmask : function() {
+ var me = this,
+ data = (me.$cache || me.getCache()).data,
+ maskEl = data.maskEl,
+ maskMsg = data.maskMsg,
+ style;
+
+ if (maskEl) {
+ style = maskEl.dom.style;
+ // Remove resource-intensive CSS expressions as soon as they are not required.
+ if (style.clearExpression) {
+ style.clearExpression('width');
+ style.clearExpression('height');
+ }
+
+ if (maskEl) {
+ maskEl.remove();
+ delete data.maskEl;
+ }
+
+ if (maskMsg) {
+ maskMsg.remove();
+ delete data.maskMsg;
+ }
+
+ me.removeCls([XMASKED, XMASKEDRELATIVE]);
+ }
+ },
+
+ /**
+ * Returns true if this element is masked. Also re-centers any displayed message within the mask.
+ * @return {Boolean}
+ */
+ isMasked : function() {
+ var me = this,
+ data = (me.$cache || me.getCache()).data,
+ maskEl = data.maskEl,
+ maskMsg = data.maskMsg,
+ hasMask = false;
+
+ if (maskEl && maskEl.isVisible()) {
+ if (maskMsg) {
+ maskMsg.center(me);
+ }
+ hasMask = true;
+ }
+ return hasMask;
+ },
+
+ /**
+ * Creates an iframe shim for this element to keep selects and other windowed objects from
+ * showing through.
+ * @return {Ext.dom.Element} The new shim element
+ */
+ createShim : function() {
+ var el = DOC.createElement('iframe'),
+ shim;
+
+ el.frameBorder = '0';
+ el.className = Ext.baseCSSPrefix + 'shim';
+ el.src = Ext.SSL_SECURE_URL;
+ shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom));
+ shim.autoBoxAdjust = false;
+ return shim;
+ },
+
+ /**
+ * Convenience method for constructing a KeyMap
+ * @param {String/Number/Number[]/Object} key Either a string with the keys to listen for, the numeric key code,
+ * array of key codes or an object with the following options:
+ * @param {Number/Array} key.key
+ * @param {Boolean} key.shift
+ * @param {Boolean} key.ctrl
+ * @param {Boolean} key.alt
+ * @param {Function} fn The function to call
+ * @param {Object} [scope] The scope (`this` reference) in which the specified function is executed. Defaults to this Element.
+ * @return {Ext.util.KeyMap} The KeyMap created
+ */
+ addKeyListener : function(key, fn, scope){
+ var config;
+ if(typeof key != 'object' || Ext.isArray(key)){
+ config = {
+ target: this,
+ key: key,
+ fn: fn,
+ scope: scope
+ };
+ }else{
+ config = {
+ target: this,
+ key : key.key,
+ shift : key.shift,
+ ctrl : key.ctrl,
+ alt : key.alt,
+ fn: fn,
+ scope: scope
+ };
+ }
+ return new Ext.util.KeyMap(config);
+ },
+
+ /**
+ * Creates a KeyMap for this element
+ * @param {Object} config The KeyMap config. See {@link Ext.util.KeyMap} for more details
+ * @return {Ext.util.KeyMap} The KeyMap created
+ */
+ addKeyMap : function(config) {
+ return new Ext.util.KeyMap(Ext.apply({
+ target: this
+ }, config));
+ },
+
+ // Mouse events
+ /**
+ * @event click
+ * Fires when a mouse click is detected within the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event contextmenu
+ * Fires when a right click is detected within the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event dblclick
+ * Fires when a mouse double click is detected within the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event mousedown
+ * Fires when a mousedown is detected within the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event mouseup
+ * Fires when a mouseup is detected within the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event mouseover
+ * Fires when a mouseover is detected within the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event mousemove
+ * Fires when a mousemove is detected with the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event mouseout
+ * Fires when a mouseout is detected with the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event mouseenter
+ * Fires when the mouse enters the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event mouseleave
+ * Fires when the mouse leaves the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+
+ // Keyboard events
+ /**
+ * @event keypress
+ * Fires when a keypress is detected within the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event keydown
+ * Fires when a keydown is detected within the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event keyup
+ * Fires when a keyup is detected within the element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+
+ // HTML frame/object events
+ /**
+ * @event load
+ * Fires when the user agent finishes loading all content within the element. Only supported by window, frames,
+ * objects and images.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event unload
+ * Fires when the user agent removes all content from a window or frame. For elements, it fires when the target
+ * element or any of its content has been removed.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event abort
+ * Fires when an object/image is stopped from loading before completely loaded.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event error
+ * Fires when an object/image/frame cannot be loaded properly.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event resize
+ * Fires when a document view is resized.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event scroll
+ * Fires when a document view is scrolled.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+
+ // Form events
+ /**
+ * @event select
+ * Fires when a user selects some text in a text field, including input and textarea.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event change
+ * Fires when a control loses the input focus and its value has been modified since gaining focus.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event submit
+ * Fires when a form is submitted.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event reset
+ * Fires when a form is reset.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event focus
+ * Fires when an element receives focus either via the pointing device or by tab navigation.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event blur
+ * Fires when an element loses focus either via the pointing device or by tabbing navigation.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+
+ // User Interface events
+ /**
+ * @event DOMFocusIn
+ * Where supported. Similar to HTML focus event, but can be applied to any focusable element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event DOMFocusOut
+ * Where supported. Similar to HTML blur event, but can be applied to any focusable element.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event DOMActivate
+ * Where supported. Fires when an element is activated, for instance, through a mouse click or a keypress.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+
+ // DOM Mutation events
+ /**
+ * @event DOMSubtreeModified
+ * Where supported. Fires when the subtree is modified.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event DOMNodeInserted
+ * Where supported. Fires when a node has been added as a child of another node.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event DOMNodeRemoved
+ * Where supported. Fires when a descendant node of the element is removed.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event DOMNodeRemovedFromDocument
+ * Where supported. Fires when a node is being removed from a document.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event DOMNodeInsertedIntoDocument
+ * Where supported. Fires when a node is being inserted into a document.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event DOMAttrModified
+ * Where supported. Fires when an attribute has been modified.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+ /**
+ * @event DOMCharacterDataModified
+ * Where supported. Fires when the character data has been modified.
+ * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
+ * @param {HTMLElement} t The target of the event.
+ */
+
+ /**
+ * Appends an event handler to this element.
+ *
+ * @param {String} eventName The name of event to handle.
+ *
+ * @param {Function} fn The handler function the event invokes. This function is passed the following parameters:
+ *
+ * - **evt** : EventObject
+ *
+ * The {@link Ext.EventObject EventObject} describing the event.
+ *
+ * - **el** : HtmlElement
+ *
+ * The DOM element which was the target of the event. Note that this may be filtered by using the delegate option.
+ *
+ * - **o** : Object
+ *
+ * The options object from the call that setup the listener.
+ *
+ * @param {Object} scope (optional) The scope (**this** reference) in which the handler function is executed. **If
+ * omitted, defaults to this Element.**
+ *
+ * @param {Object} options (optional) An object containing handler configuration properties. This may contain any of
+ * the following properties:
+ *
+ * - **scope** Object :
+ *
+ * The scope (**this** reference) in which the handler function is executed. **If omitted, defaults to this
+ * Element.**
+ *
+ * - **delegate** String:
+ *
+ * A simple selector to filter the target or look for a descendant of the target. See below for additional details.
+ *
+ * - **stopEvent** Boolean:
+ *
+ * True to stop the event. That is stop propagation, and prevent the default action.
+ *
+ * - **preventDefault** Boolean:
+ *
+ * True to prevent the default action
+ *
+ * - **stopPropagation** Boolean:
+ *
+ * True to prevent event propagation
+ *
+ * - **normalized** Boolean:
+ *
+ * False to pass a browser event to the handler function instead of an Ext.EventObject
+ *
+ * - **target** Ext.dom.Element:
+ *
+ * Only call the handler if the event was fired on the target Element, _not_ if the event was bubbled up from a
+ * child node.
+ *
+ * - **delay** Number:
+ *
+ * The number of milliseconds to delay the invocation of the handler after the event fires.
+ *
+ * - **single** Boolean:
+ *
+ * True to add a handler to handle just the next firing of the event, and then remove itself.
+ *
+ * - **buffer** Number:
+ *
+ * Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed by the specified number of
+ * milliseconds. If the event fires again within that time, the original handler is _not_ invoked, but the new
+ * handler is scheduled in its place.
+ *
+ * **Combining Options**
+ *
+ * Using the options argument, it is possible to combine different types of listeners:
+ *
+ * A delayed, one-time listener that auto stops the event and adds a custom argument (forumId) to the options
+ * object. The options object is available as the third parameter in the handler function.
+ *
+ * Code:
+ *
+ * el.on('click', this.onClick, this, {
+ * single: true,
+ * delay: 100,
+ * stopEvent : true,
+ * forumId: 4
+ * });
+ *
+ * **Attaching multiple handlers in 1 call**
+ *
+ * The method also allows for a single argument to be passed which is a config object containing properties which
+ * specify multiple handlers.
+ *
+ * Code:
+ *
+ * el.on({
+ * 'click' : {
+ * fn: this.onClick,
+ * scope: this,
+ * delay: 100
+ * },
+ * 'mouseover' : {
+ * fn: this.onMouseOver,
+ * scope: this
+ * },
+ * 'mouseout' : {
+ * fn: this.onMouseOut,
+ * scope: this
+ * }
+ * });
+ *
+ * Or a shorthand syntax:
+ *
+ * Code:
+ *
+ * el.on({
+ * 'click' : this.onClick,
+ * 'mouseover' : this.onMouseOver,
+ * 'mouseout' : this.onMouseOut,
+ * scope: this
+ * });
+ *
+ * **delegate**
+ *
+ * This is a configuration option that you can pass along when registering a handler for an event to assist with
+ * event delegation. Event delegation is a technique that is used to reduce memory consumption and prevent exposure
+ * to memory-leaks. By registering an event for a container element as opposed to each element within a container.
+ * By setting this configuration option to a simple selector, the target element will be filtered to look for a
+ * descendant of the target. For example:
+ *
+ * // using this markup:
+ *
+ *
paragraph one
+ *
paragraph two
+ *
paragraph three
+ *
+ *
+ * // utilize event delegation to registering just one handler on the container element:
+ * el = Ext.get('elId');
+ * el.on(
+ * 'click',
+ * function(e,t) {
+ * // handle click
+ * console.info(t.id); // 'p2'
+ * },
+ * this,
+ * {
+ * // filter the target element to be a descendant with the class 'clickable'
+ * delegate: '.clickable'
+ * }
+ * );
+ *
+ * @return {Ext.dom.Element} this
+ */
+ on: function(eventName, fn, scope, options) {
+ Ext.EventManager.on(this, eventName, fn, scope || this, options);
+ return this;
+ },
+
+ /**
+ * Removes an event handler from this element.
+ *
+ * **Note**: if a *scope* was explicitly specified when {@link #on adding} the listener,
+ * the same scope must be specified here.
+ *
+ * Example:
+ *
+ * el.un('click', this.handlerFn);
+ * // or
+ * el.removeListener('click', this.handlerFn);
+ *
+ * @param {String} eventName The name of the event from which to remove the handler.
+ * @param {Function} fn The handler function to remove. **This must be a reference to the function passed into the
+ * {@link #on} call.**
+ * @param {Object} scope If a scope (**this** reference) was specified when the listener was added, then this must
+ * refer to the same object.
+ * @return {Ext.dom.Element} this
+ */
+ un: function(eventName, fn, scope) {
+ Ext.EventManager.un(this, eventName, fn, scope || this);
+ return this;
+ },
+
+ /**
+ * Removes all previous added listeners from this element
+ * @return {Ext.dom.Element} this
+ */
+ removeAllListeners: function() {
+ Ext.EventManager.removeAll(this);
+ return this;
+ },
+
+ /**
+ * Recursively removes all previous added listeners from this element and its children
+ * @return {Ext.dom.Element} this
+ */
+ purgeAllListeners: function() {
+ Ext.EventManager.purgeElement(this);
+ return this;
+ }
+
+}, function() {
+
+ var EC = Ext.cache,
+ El = this,
+ AbstractElement = Ext.dom.AbstractElement,
+ focusRe = /a|button|embed|iframe|img|input|object|select|textarea/i,
+ nonSpaceRe = /\S/,
+ scriptTagRe = /(?:
+ *
+ * When we inject the tag above, the browser makes a request to that url and includes the response as if it was any
+ * other type of JavaScript include. By passing a callback in the url above, we're telling domainB's server that we want
+ * to be notified when the result comes in and that it should call our callback function with the data it sends back. So
+ * long as the server formats the response to look like this, everything will work:
+ *
+ * someCallback({
+ * users: [
+ * {
+ * id: 1,
+ * name: "Ed Spencer",
+ * email: "ed@sencha.com"
+ * }
+ * ]
+ * });
+ *
+ * As soon as the script finishes loading, the 'someCallback' function that we passed in the url is called with the JSON
+ * object that the server returned.
+ *
+ * JsonP proxy takes care of all of this automatically. It formats the url you pass, adding the callback parameter
+ * automatically. It even creates a temporary callback function, waits for it to be called and then puts the data into
+ * the Proxy making it look just like you loaded it through a normal {@link Ext.data.proxy.Ajax AjaxProxy}. Here's how
+ * we might set that up:
+ *
+ * Ext.define('User', {
+ * extend: 'Ext.data.Model',
+ * fields: ['id', 'name', 'email']
+ * });
+ *
+ * var store = Ext.create('Ext.data.Store', {
+ * model: 'User',
+ * proxy: {
+ * type: 'jsonp',
+ * url : 'http://domainB.com/users'
+ * }
+ * });
+ *
+ * store.load();
+ *
+ * That's all we need to do - JsonP proxy takes care of the rest. In this case the Proxy will have injected a script tag
+ * like this:
+ *
+ *
+ *
+ * # Customization
+ *
+ * This script tag can be customized using the {@link #callbackKey} configuration. For example:
+ *
+ * var store = Ext.create('Ext.data.Store', {
+ * model: 'User',
+ * proxy: {
+ * type: 'jsonp',
+ * url : 'http://domainB.com/users',
+ * callbackKey: 'theCallbackFunction'
+ * }
+ * });
+ *
+ * store.load();
+ *
+ * Would inject a script tag like this:
+ *
+ *
+ *
+ * # Implementing on the server side
+ *
+ * The remote server side needs to be configured to return data in this format. Here are suggestions for how you might
+ * achieve this using Java, PHP and ASP.net:
+ *
+ * Java:
+ *
+ * boolean jsonP = false;
+ * String cb = request.getParameter("callback");
+ * if (cb != null) {
+ * jsonP = true;
+ * response.setContentType("text/javascript");
+ * } else {
+ * response.setContentType("application/x-json");
+ * }
+ * Writer out = response.getWriter();
+ * if (jsonP) {
+ * out.write(cb + "(");
+ * }
+ * out.print(dataBlock.toJsonString());
+ * if (jsonP) {
+ * out.write(");");
+ * }
+ *
+ * PHP:
+ *
+ * $callback = $_REQUEST['callback'];
+ *
+ * // Create the output object.
+ * $output = array('a' => 'Apple', 'b' => 'Banana');
+ *
+ * //start output
+ * if ($callback) {
+ * header('Content-Type: text/javascript');
+ * echo $callback . '(' . json_encode($output) . ');';
+ * } else {
+ * header('Content-Type: application/x-json');
+ * echo json_encode($output);
+ * }
+ *
+ * ASP.net:
+ *
+ * String jsonString = "{success: true}";
+ * String cb = Request.Params.Get("callback");
+ * String responseString = "";
+ * if (!String.IsNullOrEmpty(cb)) {
+ * responseString = cb + "(" + jsonString + ")";
+ * } else {
+ * responseString = jsonString;
+ * }
+ * Response.Write(responseString);
+ */
+Ext.define('Ext.data.proxy.JsonP', {
+ extend: 'Ext.data.proxy.Server',
+ alternateClassName: 'Ext.data.ScriptTagProxy',
+ alias: ['proxy.jsonp', 'proxy.scripttag'],
+ requires: ['Ext.data.JsonP'],
+
+ defaultWriterType: 'base',
+
+ /**
+ * @cfg {String} callbackKey
+ * See {@link Ext.data.JsonP#callbackKey}.
+ */
+ callbackKey : 'callback',
+
+ /**
+ * @cfg {String} recordParam
+ * The param name to use when passing records to the server (e.g. 'records=someEncodedRecordString'). Defaults to
+ * 'records'
+ */
+ recordParam: 'records',
+
+ /**
+ * @cfg {Boolean} autoAppendParams
+ * True to automatically append the request's params to the generated url. Defaults to true
+ */
+ autoAppendParams: true,
+
+ constructor: function(){
+ this.addEvents(
+ /**
+ * @event
+ * Fires when the server returns an exception
+ * @param {Ext.data.proxy.Proxy} this
+ * @param {Ext.data.Request} request The request that was sent
+ * @param {Ext.data.Operation} operation The operation that triggered the request
+ */
+ 'exception'
+ );
+ this.callParent(arguments);
+ },
+
+ /**
+ * @private
+ * Performs the read request to the remote domain. JsonP proxy does not actually create an Ajax request,
+ * instead we write out a `
+ *
+ * ## Configuration
+ *
+ * This component allows several options for configuring how the target Flash movie is embedded. The most
+ * important is the required {@link #url} which points to the location of the Flash movie to load. Other
+ * configurations include:
+ *
+ * - {@link #backgroundColor}
+ * - {@link #wmode}
+ * - {@link #flashVars}
+ * - {@link #flashParams}
+ * - {@link #flashAttributes}
+ *
+ * ## Example usage:
+ *
+ * var win = Ext.widget('window', {
+ * title: "It's a tiger!",
+ * layout: 'fit',
+ * width: 300,
+ * height: 300,
+ * x: 20,
+ * y: 20,
+ * resizable: true,
+ * items: {
+ * xtype: 'flash',
+ * url: 'tiger.swf'
+ * }
+ * });
+ * win.show();
+ *
+ * ## Express Install
+ *
+ * Adobe provides a tool called [Express Install](http://www.adobe.com/devnet/flashplayer/articles/express_install.html)
+ * that offers users an easy way to upgrade their Flash player. If you wish to make use of this, you should set
+ * the static EXPRESS\_INSTALL\_URL property to the location of your Express Install SWF file:
+ *
+ * Ext.flash.Component.EXPRESS_INSTALL_URL = 'path/to/local/expressInstall.swf';
+ *
+ * @docauthor Jason Johnston
+ */
+Ext.define('Ext.flash.Component', {
+ extend: 'Ext.Component',
+ alternateClassName: 'Ext.FlashComponent',
+ alias: 'widget.flash',
+
+ /**
+ * @cfg {String} [flashVersion="9.0.115"]
+ * Indicates the version the flash content was published for.
+ */
+ flashVersion : '9.0.115',
+
+ /**
+ * @cfg {String} [backgroundColor="#ffffff"]
+ * The background color of the SWF movie.
+ */
+ backgroundColor: '#ffffff',
+
+ /**
+ * @cfg {String} [wmode="opaque"]
+ * The wmode of the flash object. This can be used to control layering.
+ * Set to 'transparent' to ignore the {@link #backgroundColor} and make the background of the Flash
+ * movie transparent.
+ */
+ wmode: 'opaque',
+
+ /**
+ * @cfg {Object} flashVars
+ * A set of key value pairs to be passed to the flash object as flash variables.
+ */
+
+ /**
+ * @cfg {Object} flashParams
+ * A set of key value pairs to be passed to the flash object as parameters. Possible parameters can be found here:
+ * http://kb2.adobe.com/cps/127/tn_12701.html
+ */
+
+ /**
+ * @cfg {Object} flashAttributes
+ * A set of key value pairs to be passed to the flash object as attributes.
+ */
+
+ /**
+ * @cfg {String} url (required)
+ * The URL of the SWF file to include.
+ */
+
+ /**
+ * @cfg {String/Number} [swfWidth="100%"]
+ * The width of the embedded SWF movie inside the component.
+ *
+ * Defaults to "100%" so that the movie matches the width of the component.
+ */
+ swfWidth: '100%',
+
+ /**
+ * @cfg {String/Number} [swfHeight="100%"]
+ * The height of the embedded SWF movie inside the component.
+ *
+ * Defaults to "100%" so that the movie matches the height of the component.
+ */
+ swfHeight: '100%',
+
+ /**
+ * @cfg {Boolean} [expressInstall=false]
+ * True to prompt the user to install flash if not installed. Note that this uses
+ * Ext.FlashComponent.EXPRESS_INSTALL_URL, which should be set to the local resource.
+ */
+ expressInstall: false,
+
+ /**
+ * @property {Ext.Element} swf
+ * A reference to the object or embed element into which the SWF file is loaded. Only
+ * populated after the component is rendered and the SWF has been successfully embedded.
+ */
+
+ // Have to create a placeholder div with the swfId, which SWFObject will replace with the object/embed element.
+ renderTpl: ['
'],
+
+ initComponent: function() {
+ if (!('swfobject' in window)) {
+ Ext.Error.raise('The SWFObject library is not loaded. Ext.flash.Component requires SWFObject version 2.2 or later: http://code.google.com/p/swfobject/');
+ }
+ if (!this.url) {
+ Ext.Error.raise('The "url" config is required for Ext.flash.Component');
+ }
+
+ this.callParent();
+ this.addEvents(
+ /**
+ * @event success
+ * Fired when the Flash movie has been successfully embedded
+ * @param {Ext.flash.Component} this
+ */
+ 'success',
+
+ /**
+ * @event failure
+ * Fired when the Flash movie embedding fails
+ * @param {Ext.flash.Component} this
+ */
+ 'failure'
+ );
+ },
+
+ beforeRender: function(){
+ this.callParent();
+
+ Ext.applyIf(this.renderData, {
+ swfId: this.getSwfId()
+ });
+ },
+
+ afterRender: function() {
+ var me = this,
+ flashParams = Ext.apply({}, me.flashParams),
+ flashVars = Ext.apply({}, me.flashVars);
+
+ me.callParent();
+
+ flashParams = Ext.apply({
+ allowScriptAccess: 'always',
+ bgcolor: me.backgroundColor,
+ wmode: me.wmode
+ }, flashParams);
+
+ flashVars = Ext.apply({
+ allowedDomain: document.location.hostname
+ }, flashVars);
+
+ new swfobject.embedSWF(
+ me.url,
+ me.getSwfId(),
+ me.swfWidth,
+ me.swfHeight,
+ me.flashVersion,
+ me.expressInstall ? me.statics.EXPRESS_INSTALL_URL : undefined,
+ flashVars,
+ flashParams,
+ me.flashAttributes,
+ Ext.bind(me.swfCallback, me)
+ );
+ },
+
+ /**
+ * @private
+ * The callback method for handling an embedding success or failure by SWFObject
+ * @param {Object} e The event object passed by SWFObject - see http://code.google.com/p/swfobject/wiki/api
+ */
+ swfCallback: function(e) {
+ var me = this;
+ if (e.success) {
+ me.swf = Ext.get(e.ref);
+ me.onSuccess();
+ me.fireEvent('success', me);
+ } else {
+ me.onFailure();
+ me.fireEvent('failure', me);
+ }
+ },
+
+ /**
+ * Retrieves the id of the SWF object/embed element.
+ */
+ getSwfId: function() {
+ return this.swfId || (this.swfId = "extswf" + this.getAutoId());
+ },
+
+ onSuccess: function() {
+ // swfobject forces visiblity:visible on the swf element, which prevents it
+ // from getting hidden when an ancestor is given visibility:hidden.
+ this.swf.setStyle('visibility', 'inherit');
+ },
+
+ onFailure: Ext.emptyFn,
+
+ beforeDestroy: function() {
+ var me = this,
+ swf = me.swf;
+ if (swf) {
+ swfobject.removeSWF(me.getSwfId());
+ Ext.destroy(swf);
+ delete me.swf;
+ }
+ me.callParent();
+ },
+
+ statics: {
+ /**
+ * @property {String}
+ * The url for installing flash if it doesn't exist. This should be set to a local resource.
+ * See http://www.adobe.com/devnet/flashplayer/articles/express_install.html for details.
+ * @static
+ */
+ EXPRESS_INSTALL_URL: 'http:/' + '/swfobject.googlecode.com/svn/trunk/swfobject/expressInstall.swf'
+ }
+});
+
+/**
+ * The subclasses of this class provide actions to perform upon {@link Ext.form.Basic Form}s.
+ *
+ * Instances of this class are only created by a {@link Ext.form.Basic Form} when the Form needs to perform an action
+ * such as submit or load. The Configuration options listed for this class are set through the Form's action methods:
+ * {@link Ext.form.Basic#submit submit}, {@link Ext.form.Basic#load load} and {@link Ext.form.Basic#doAction doAction}
+ *
+ * The instance of Action which performed the action is passed to the success and failure callbacks of the Form's action
+ * methods ({@link Ext.form.Basic#submit submit}, {@link Ext.form.Basic#load load} and
+ * {@link Ext.form.Basic#doAction doAction}), and to the {@link Ext.form.Basic#actioncomplete actioncomplete} and
+ * {@link Ext.form.Basic#actionfailed actionfailed} event handlers.
+ */
+Ext.define('Ext.form.action.Action', {
+ alternateClassName: 'Ext.form.Action',
+
+ /**
+ * @cfg {Ext.form.Basic} form
+ * The {@link Ext.form.Basic BasicForm} instance that is invoking this Action. Required.
+ */
+
+ /**
+ * @cfg {String} url
+ * The URL that the Action is to invoke. Will default to the {@link Ext.form.Basic#url url} configured on the
+ * {@link #form}.
+ */
+
+ /**
+ * @cfg {Boolean} reset
+ * When set to **true**, causes the Form to be {@link Ext.form.Basic#reset reset} on Action success. If specified,
+ * this happens before the {@link #success} callback is called and before the Form's
+ * {@link Ext.form.Basic#actioncomplete actioncomplete} event fires.
+ */
+
+ /**
+ * @cfg {String} method
+ * The HTTP method to use to access the requested URL.
+ * Defaults to the {@link Ext.form.Basic#method BasicForm's method}, or 'POST' if not specified.
+ */
+
+ /**
+ * @cfg {Object/String} params
+ * Extra parameter values to pass. These are added to the Form's {@link Ext.form.Basic#baseParams} and passed to the
+ * specified URL along with the Form's input fields.
+ *
+ * Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode Ext.Object.toQueryString}.
+ */
+
+ /**
+ * @cfg {Object} headers
+ * Extra headers to be sent in the AJAX request for submit and load actions.
+ * See {@link Ext.data.proxy.Ajax#headers}.
+ */
+
+ /**
+ * @cfg {Number} timeout
+ * The number of seconds to wait for a server response before failing with the {@link #failureType} as
+ * {@link Ext.form.action.Action#CONNECT_FAILURE}. If not specified, defaults to the configured
+ * {@link Ext.form.Basic#timeout timeout} of the {@link #form}.
+ */
+
+ /**
+ * @cfg {Function} success
+ * The function to call when a valid success return packet is received.
+ * @cfg {Ext.form.Basic} success.form The form that requested the action
+ * @cfg {Ext.form.action.Action} success.action The Action class. The {@link #result} property of this object may
+ * be examined to perform custom postprocessing.
+ */
+
+ /**
+ * @cfg {Function} failure
+ * The function to call when a failure packet was received, or when an error ocurred in the Ajax communication.
+ * @cfg {Ext.form.Basic} failure.form The form that requested the action
+ * @cfg {Ext.form.action.Action} failure.action The Action class. If an Ajax error ocurred, the failure type will
+ * be in {@link #failureType}. The {@link #result} property of this object may be examined to perform custom
+ * postprocessing.
+ */
+
+ /**
+ * @cfg {Object} scope
+ * The scope in which to call the configured #success and #failure callback functions
+ * (the `this` reference for the callback functions).
+ */
+
+ /**
+ * @cfg {String} waitMsg
+ * The message to be displayed by a call to {@link Ext.window.MessageBox#wait} during the time the action is being
+ * processed.
+ */
+
+ /**
+ * @cfg {String} waitTitle
+ * The title to be displayed by a call to {@link Ext.window.MessageBox#wait} during the time the action is being
+ * processed.
+ */
+
+ /**
+ * @cfg {Boolean} submitEmptyText
+ * If set to true, the emptyText value will be sent with the form when it is submitted.
+ */
+ submitEmptyText : true,
+
+ /**
+ * @property {String} type
+ * The type of action this Action instance performs. Currently only "submit" and "load" are supported.
+ */
+
+ /**
+ * @property {String} failureType
+ * The type of failure detected will be one of these:
+ * {@link #CLIENT_INVALID}, {@link #SERVER_INVALID}, {@link #CONNECT_FAILURE}, or {@link #LOAD_FAILURE}.
+ *
+ * Usage:
+ *
+ * var fp = new Ext.form.Panel({
+ * ...
+ * buttons: [{
+ * text: 'Save',
+ * formBind: true,
+ * handler: function(){
+ * if(fp.getForm().isValid()){
+ * fp.getForm().submit({
+ * url: 'form-submit.php',
+ * waitMsg: 'Submitting your data...',
+ * success: function(form, action){
+ * // server responded with success = true
+ * var result = action.{@link #result};
+ * },
+ * failure: function(form, action){
+ * if (action.{@link #failureType} === Ext.form.action.Action.CONNECT_FAILURE) {
+ * Ext.Msg.alert('Error',
+ * 'Status:'+action.{@link #response}.status+': '+
+ * action.{@link #response}.statusText);
+ * }
+ * if (action.failureType === Ext.form.action.Action.SERVER_INVALID){
+ * // server responded with success = false
+ * Ext.Msg.alert('Invalid', action.{@link #result}.errormsg);
+ * }
+ * }
+ * });
+ * }
+ * }
+ * },{
+ * text: 'Reset',
+ * handler: function(){
+ * fp.getForm().reset();
+ * }
+ * }]
+ */
+
+ /**
+ * @property {Object} response
+ * The raw XMLHttpRequest object used to perform the action.
+ */
+
+ /**
+ * @property {Object} result
+ * The decoded response object containing a boolean `success` property and other, action-specific properties.
+ */
+
+ /**
+ * Creates new Action.
+ * @param {Object} [config] Config object.
+ */
+ constructor: function(config) {
+ if (config) {
+ Ext.apply(this, config);
+ }
+
+ // Normalize the params option to an Object
+ var params = config.params;
+ if (Ext.isString(params)) {
+ this.params = Ext.Object.fromQueryString(params);
+ }
+ },
+
+ /**
+ * @method
+ * Invokes this action using the current configuration.
+ */
+ run: Ext.emptyFn,
+
+ /**
+ * @private
+ * @method onSuccess
+ * Callback method that gets invoked when the action completes successfully. Must be implemented by subclasses.
+ * @param {Object} response
+ */
+
+ /**
+ * @private
+ * @method handleResponse
+ * Handles the raw response and builds a result object from it. Must be implemented by subclasses.
+ * @param {Object} response
+ */
+
+ /**
+ * @private
+ * Handles a failure response.
+ * @param {Object} response
+ */
+ onFailure : function(response){
+ this.response = response;
+ this.failureType = Ext.form.action.Action.CONNECT_FAILURE;
+ this.form.afterAction(this, false);
+ },
+
+ /**
+ * @private
+ * Validates that a response contains either responseText or responseXML and invokes
+ * {@link #handleResponse} to build the result object.
+ * @param {Object} response The raw response object.
+ * @return {Object/Boolean} The result object as built by handleResponse, or `true` if
+ * the response had empty responseText and responseXML.
+ */
+ processResponse : function(response){
+ this.response = response;
+ if (!response.responseText && !response.responseXML) {
+ return true;
+ }
+ return (this.result = this.handleResponse(response));
+ },
+
+ /**
+ * @private
+ * Build the URL for the AJAX request. Used by the standard AJAX submit and load actions.
+ * @return {String} The URL.
+ */
+ getUrl: function() {
+ return this.url || this.form.url;
+ },
+
+ /**
+ * @private
+ * Determine the HTTP method to be used for the request.
+ * @return {String} The HTTP method
+ */
+ getMethod: function() {
+ return (this.method || this.form.method || 'POST').toUpperCase();
+ },
+
+ /**
+ * @private
+ * Get the set of parameters specified in the BasicForm's baseParams and/or the params option.
+ * Items in params override items of the same name in baseParams.
+ * @return {Object} the full set of parameters
+ */
+ getParams: function() {
+ return Ext.apply({}, this.params, this.form.baseParams);
+ },
+
+ /**
+ * @private
+ * Creates a callback object.
+ */
+ createCallback: function() {
+ var me = this,
+ undef,
+ form = me.form;
+ return {
+ success: me.onSuccess,
+ failure: me.onFailure,
+ scope: me,
+ timeout: (this.timeout * 1000) || (form.timeout * 1000),
+ upload: form.fileUpload ? me.onSuccess : undef
+ };
+ },
+
+ statics: {
+ /**
+ * @property
+ * Failure type returned when client side validation of the Form fails thus aborting a submit action. Client
+ * side validation is performed unless {@link Ext.form.action.Submit#clientValidation} is explicitly set to
+ * false.
+ * @static
+ */
+ CLIENT_INVALID: 'client',
+
+ /**
+ * @property
+ * Failure type returned when server side processing fails and the {@link #result}'s `success` property is set to
+ * false.
+ *
+ * In the case of a form submission, field-specific error messages may be returned in the {@link #result}'s
+ * errors property.
+ * @static
+ */
+ SERVER_INVALID: 'server',
+
+ /**
+ * @property
+ * Failure type returned when a communication error happens when attempting to send a request to the remote
+ * server. The {@link #response} may be examined to provide further information.
+ * @static
+ */
+ CONNECT_FAILURE: 'connect',
+
+ /**
+ * @property
+ * Failure type returned when the response's `success` property is set to false, or no field values are returned
+ * in the response's data property.
+ * @static
+ */
+ LOAD_FAILURE: 'load'
+
+
+ }
+});
+
+/**
+ * A class which handles loading of data from a server into the Fields of an {@link Ext.form.Basic}.
+ *
+ * Instances of this class are only created by a {@link Ext.form.Basic Form} when {@link Ext.form.Basic#load load}ing.
+ *
+ * ## Response Packet Criteria
+ *
+ * A response packet **must** contain:
+ *
+ * - **`success`** property : Boolean
+ * - **`data`** property : Object
+ *
+ * The `data` property contains the values of Fields to load. The individual value object for each Field is passed to
+ * the Field's {@link Ext.form.field.Field#setValue setValue} method.
+ *
+ * ## JSON Packets
+ *
+ * By default, response packets are assumed to be JSON, so for the following form load call:
+ *
+ * var myFormPanel = new Ext.form.Panel({
+ * title: 'Client and routing info',
+ * renderTo: Ext.getBody(),
+ * defaults: {
+ * xtype: 'textfield'
+ * },
+ * items: [{
+ * fieldLabel: 'Client',
+ * name: 'clientName'
+ * }, {
+ * fieldLabel: 'Port of loading',
+ * name: 'portOfLoading'
+ * }, {
+ * fieldLabel: 'Port of discharge',
+ * name: 'portOfDischarge'
+ * }]
+ * });
+ * myFormPanel.{@link Ext.form.Panel#getForm getForm}().{@link Ext.form.Basic#load load}({
+ * url: '/getRoutingInfo.php',
+ * params: {
+ * consignmentRef: myConsignmentRef
+ * },
+ * failure: function(form, action) {
+ * Ext.Msg.alert("Load failed", action.result.errorMessage);
+ * }
+ * });
+ *
+ * a **success response** packet may look like this:
+ *
+ * {
+ * success: true,
+ * data: {
+ * clientName: "Fred. Olsen Lines",
+ * portOfLoading: "FXT",
+ * portOfDischarge: "OSL"
+ * }
+ * }
+ *
+ * while a **failure response** packet may look like this:
+ *
+ * {
+ * success: false,
+ * errorMessage: "Consignment reference not found"
+ * }
+ *
+ * Other data may be placed into the response for processing the {@link Ext.form.Basic Form}'s callback or event handler
+ * methods. The object decoded from this JSON is available in the {@link Ext.form.action.Action#result result} property.
+ */
+Ext.define('Ext.form.action.Load', {
+ extend:'Ext.form.action.Action',
+ requires: ['Ext.data.Connection'],
+ alternateClassName: 'Ext.form.Action.Load',
+ alias: 'formaction.load',
+
+ type: 'load',
+
+ /**
+ * @private
+ */
+ run: function() {
+ Ext.Ajax.request(Ext.apply(
+ this.createCallback(),
+ {
+ method: this.getMethod(),
+ url: this.getUrl(),
+ headers: this.headers,
+ params: this.getParams()
+ }
+ ));
+ },
+
+ /**
+ * @private
+ */
+ onSuccess: function(response){
+ var result = this.processResponse(response),
+ form = this.form;
+ if (result === true || !result.success || !result.data) {
+ this.failureType = Ext.form.action.Action.LOAD_FAILURE;
+ form.afterAction(this, false);
+ return;
+ }
+ form.clearInvalid();
+ form.setValues(result.data);
+ form.afterAction(this, true);
+ },
+
+ /**
+ * @private
+ */
+ handleResponse: function(response) {
+ var reader = this.form.reader,
+ rs, data;
+ if (reader) {
+ rs = reader.read(response);
+ data = rs.records && rs.records[0] ? rs.records[0].data : null;
+ return {
+ success : rs.success,
+ data : data
+ };
+ }
+ return Ext.decode(response.responseText);
+ }
+});
+
+
+/**
+ * A class which handles submission of data from {@link Ext.form.Basic Form}s and processes the returned response.
+ *
+ * Instances of this class are only created by a {@link Ext.form.Basic Form} when
+ * {@link Ext.form.Basic#submit submit}ting.
+ *
+ * # Response Packet Criteria
+ *
+ * A response packet may contain:
+ *
+ * - **`success`** property : Boolean - required.
+ *
+ * - **`errors`** property : Object - optional, contains error messages for invalid fields.
+ *
+ * # JSON Packets
+ *
+ * By default, response packets are assumed to be JSON, so a typical response packet may look like this:
+ *
+ * {
+ * success: false,
+ * errors: {
+ * clientCode: "Client not found",
+ * portOfLoading: "This field must not be null"
+ * }
+ * }
+ *
+ * Other data may be placed into the response for processing by the {@link Ext.form.Basic}'s callback or event handler
+ * methods. The object decoded from this JSON is available in the {@link Ext.form.action.Action#result result} property.
+ *
+ * Alternatively, if an {@link Ext.form.Basic#errorReader errorReader} is specified as an
+ * {@link Ext.data.reader.Xml XmlReader}:
+ *
+ * errorReader: new Ext.data.reader.Xml({
+ * record : 'field',
+ * success: '@success'
+ * }, [
+ * 'id', 'msg'
+ * ]
+ * )
+ *
+ * then the results may be sent back in XML format:
+ *
+ *
+ *
+ *
+ *
+ * clientCode
+ * This is a test validation message from the server ]]>
+ *
+ *
+ * portOfLoading
+ * This is a test validation message from the server ]]>
+ *
+ *
+ *
+ *
+ * Other elements may be placed into the response XML for processing by the {@link Ext.form.Basic}'s callback or event
+ * handler methods. The XML document is available in the {@link Ext.form.Basic#errorReader errorReader}'s
+ * {@link Ext.data.reader.Xml#xmlData xmlData} property.
+ */
+Ext.define('Ext.form.action.Submit', {
+ extend:'Ext.form.action.Action',
+ alternateClassName: 'Ext.form.Action.Submit',
+ alias: 'formaction.submit',
+
+ type: 'submit',
+
+ /**
+ * @cfg {Boolean} [clientValidation=true]
+ * Determines whether a Form's fields are validated in a final call to {@link Ext.form.Basic#isValid isValid} prior
+ * to submission. Pass false in the Form's submit options to prevent this.
+ */
+
+ // inherit docs
+ run : function(){
+ var form = this.form;
+ if (this.clientValidation === false || form.isValid()) {
+ this.doSubmit();
+ } else {
+ // client validation failed
+ this.failureType = Ext.form.action.Action.CLIENT_INVALID;
+ form.afterAction(this, false);
+ }
+ },
+
+ /**
+ * @private
+ * Performs the submit of the form data.
+ */
+ doSubmit: function() {
+ var formEl,
+ ajaxOptions = Ext.apply(this.createCallback(), {
+ url: this.getUrl(),
+ method: this.getMethod(),
+ headers: this.headers
+ });
+
+ // For uploads we need to create an actual form that contains the file upload fields,
+ // and pass that to the ajax call so it can do its iframe-based submit method.
+ if (this.form.hasUpload()) {
+ formEl = ajaxOptions.form = this.buildForm();
+ ajaxOptions.isUpload = true;
+ } else {
+ ajaxOptions.params = this.getParams();
+ }
+
+ Ext.Ajax.request(ajaxOptions);
+
+ if (formEl) {
+ Ext.removeNode(formEl);
+ }
+ },
+
+ /**
+ * @private
+ * Builds the full set of parameters from the field values plus any additional configured params.
+ */
+ getParams: function() {
+ var nope = false,
+ configParams = this.callParent(),
+ fieldParams = this.form.getValues(nope, nope, this.submitEmptyText !== nope);
+ return Ext.apply({}, fieldParams, configParams);
+ },
+
+ /**
+ * @private
+ * Builds a form element containing fields corresponding to all the parameters to be
+ * submitted (everything returned by {@link #getParams}.
+ *
+ * NOTE: the form element is automatically added to the DOM, so any code that uses
+ * it must remove it from the DOM after finishing with it.
+ *
+ * @return {HTMLElement}
+ */
+ buildForm: function() {
+ var fieldsSpec = [],
+ formSpec,
+ formEl,
+ basicForm = this.form,
+ params = this.getParams(),
+ uploadFields = [],
+ fields = basicForm.getFields().items,
+ f,
+ fLen = fields.length,
+ field, key, value, v, vLen,
+ u, uLen;
+
+ for (f = 0; f < fLen; f++) {
+ field = fields[f];
+
+ if (field.isFileUpload()) {
+ uploadFields.push(field);
+ }
+ }
+
+ function addField(name, val) {
+ fieldsSpec.push({
+ tag: 'input',
+ type: 'hidden',
+ name: name,
+ value: Ext.String.htmlEncode(val)
+ });
+ }
+
+ for (key in params) {
+ if (params.hasOwnProperty(key)) {
+ value = params[key];
+
+ if (Ext.isArray(value)) {
+ vLen = value.length;
+ for (v = 0; v < vLen; v++) {
+ addField(key, value[v]);
+ }
+ } else {
+ addField(key, value);
+ }
+ }
+ }
+
+ formSpec = {
+ tag: 'form',
+ action: this.getUrl(),
+ method: this.getMethod(),
+ target: this.target || '_self',
+ style: 'display:none',
+ cn: fieldsSpec
+ };
+
+ // Set the proper encoding for file uploads
+ if (uploadFields.length) {
+ formSpec.encoding = formSpec.enctype = 'multipart/form-data';
+ }
+
+ // Create the form
+ formEl = Ext.DomHelper.append(Ext.getBody(), formSpec);
+
+ // Special handling for file upload fields: since browser security measures prevent setting
+ // their values programatically, and prevent carrying their selected values over when cloning,
+ // we have to move the actual field instances out of their components and into the form.
+ uLen = uploadFields.length;
+
+ for (u = 0; u < uLen; u++) {
+ field = uploadFields[u];
+ if (field.rendered) { // can only have a selected file value after being rendered
+ formEl.appendChild(field.extractFileInput());
+ }
+ }
+
+ return formEl;
+ },
+
+
+
+ /**
+ * @private
+ */
+ onSuccess: function(response) {
+ var form = this.form,
+ success = true,
+ result = this.processResponse(response);
+ if (result !== true && !result.success) {
+ if (result.errors) {
+ form.markInvalid(result.errors);
+ }
+ this.failureType = Ext.form.action.Action.SERVER_INVALID;
+ success = false;
+ }
+ form.afterAction(this, success);
+ },
+
+ /**
+ * @private
+ */
+ handleResponse: function(response) {
+ var form = this.form,
+ errorReader = form.errorReader,
+ rs, errors, i, len, records;
+ if (errorReader) {
+ rs = errorReader.read(response);
+ records = rs.records;
+ errors = [];
+ if (records) {
+ for(i = 0, len = records.length; i < len; i++) {
+ errors[i] = records[i].data;
+ }
+ }
+ if (errors.length < 1) {
+ errors = null;
+ }
+ return {
+ success : rs.success,
+ errors : errors
+ };
+ }
+ return Ext.decode(response.responseText);
+ }
+});
+
+/**
+ * A subclass of Ext.dd.DragTracker which handles dragging any Component.
+ *
+ * This is configured with a Component to be made draggable, and a config object for the {@link Ext.dd.DragTracker}
+ * class.
+ *
+ * A {@link #delegate} may be provided which may be either the element to use as the mousedown target or a {@link
+ * Ext.DomQuery} selector to activate multiple mousedown targets.
+ *
+ * When the Component begins to be dragged, its `beginDrag` method will be called if implemented.
+ *
+ * When the drag ends, its `endDrag` method will be called if implemented.
+ */
+Ext.define('Ext.util.ComponentDragger', {
+ extend: 'Ext.dd.DragTracker',
+
+ /**
+ * @cfg {Boolean} constrain
+ * Specify as `true` to constrain the Component to within the bounds of the {@link #constrainTo} region.
+ */
+
+ /**
+ * @cfg {String/Ext.Element} delegate
+ * A {@link Ext.DomQuery DomQuery} selector which identifies child elements within the Component's encapsulating
+ * Element which are the drag handles. This limits dragging to only begin when the matching elements are
+ * mousedowned.
+ *
+ * This may also be a specific child element within the Component's encapsulating element to use as the drag handle.
+ */
+
+ /**
+ * @cfg {Boolean} constrainDelegate
+ * Specify as `true` to constrain the drag handles within the {@link #constrainTo} region.
+ */
+
+ autoStart: 500,
+
+ /**
+ * Creates new ComponentDragger.
+ * @param {Object} comp The Component to provide dragging for.
+ * @param {Object} [config] Config object
+ */
+ constructor: function(comp, config) {
+ this.comp = comp;
+ this.initialConstrainTo = config.constrainTo;
+ this.callParent([ config ]);
+ },
+
+ onStart: function(e) {
+ var me = this,
+ comp = me.comp;
+
+ // Cache the start [X, Y] array
+ this.startPosition = comp.el.getXY();
+
+ // If client Component has a ghost method to show a lightweight version of itself
+ // then use that as a drag proxy unless configured to liveDrag.
+ if (comp.ghost && !comp.liveDrag) {
+ me.proxy = comp.ghost();
+ me.dragTarget = me.proxy.header.el;
+ }
+
+ // Set the constrainTo Region before we start dragging.
+ if (me.constrain || me.constrainDelegate) {
+ me.constrainTo = me.calculateConstrainRegion();
+ }
+
+ if (comp.beginDrag) {
+ comp.beginDrag();
+ }
+ },
+
+ calculateConstrainRegion: function() {
+ var me = this,
+ comp = me.comp,
+ c = me.initialConstrainTo,
+ delegateRegion,
+ elRegion,
+ dragEl = me.proxy ? me.proxy.el : comp.el,
+ shadowSize = (!me.constrainDelegate && dragEl.shadow && !dragEl.shadowDisabled) ? dragEl.shadow.getShadowSize() : 0;
+
+ // The configured constrainTo might be a Region or an element
+ if (!(c instanceof Ext.util.Region)) {
+ c = Ext.fly(c).getViewRegion();
+ }
+
+ // Reduce the constrain region to allow for shadow
+ if (shadowSize) {
+ c.adjust(shadowSize[0], -shadowSize[1], -shadowSize[2], shadowSize[3]);
+ }
+
+ // If they only want to constrain the *delegate* to within the constrain region,
+ // adjust the region to be larger based on the insets of the delegate from the outer
+ // edges of the Component.
+ if (!me.constrainDelegate) {
+ delegateRegion = Ext.fly(me.dragTarget).getRegion();
+ elRegion = dragEl.getRegion();
+
+ c.adjust(
+ delegateRegion.top - elRegion.top,
+ delegateRegion.right - elRegion.right,
+ delegateRegion.bottom - elRegion.bottom,
+ delegateRegion.left - elRegion.left
+ );
+ }
+ return c;
+ },
+
+ // Move either the ghost Component or the target Component to its new position on drag
+ onDrag: function(e) {
+ var me = this,
+ comp = (me.proxy && !me.comp.liveDrag) ? me.proxy : me.comp,
+ offset = me.getOffset(me.constrain || me.constrainDelegate ? 'dragTarget' : null);
+
+ comp.setPagePosition(me.startPosition[0] + offset[0], me.startPosition[1] + offset[1]);
+ },
+
+ onEnd: function(e) {
+ var comp = this.comp;
+ if (this.proxy && !comp.liveDrag) {
+ comp.unghost();
+ }
+ if (comp.endDrag) {
+ comp.endDrag();
+ }
+ }
+});
+
+/**
+ * A specialized panel intended for use as an application window. Windows are floated, {@link #resizable}, and
+ * {@link #cfg-draggable} by default. Windows can be {@link #maximizable maximized} to fill the viewport, restored to
+ * their prior size, and can be {@link #method-minimize}d.
+ *
+ * Windows can also be linked to a {@link Ext.ZIndexManager} or managed by the {@link Ext.WindowManager} to provide
+ * grouping, activation, to front, to back and other application-specific behavior.
+ *
+ * By default, Windows will be rendered to document.body. To {@link #constrain} a Window to another element specify
+ * {@link Ext.Component#renderTo renderTo}.
+ *
+ * **As with all {@link Ext.container.Container Container}s, it is important to consider how you want the Window to size
+ * and arrange any child Components. Choose an appropriate {@link #layout} configuration which lays out child Components
+ * in the required manner.**
+ *
+ * @example
+ * Ext.create('Ext.window.Window', {
+ * title: 'Hello',
+ * height: 200,
+ * width: 400,
+ * layout: 'fit',
+ * items: { // Let's put an empty grid in just to illustrate fit layout
+ * xtype: 'grid',
+ * border: false,
+ * columns: [{header: 'World'}], // One header just for show. There's no data,
+ * store: Ext.create('Ext.data.ArrayStore', {}) // A dummy empty data store
+ * }
+ * }).show();
+ */
+Ext.define('Ext.window.Window', {
+ extend: 'Ext.panel.Panel',
+
+ alternateClassName: 'Ext.Window',
+
+ requires: ['Ext.util.ComponentDragger', 'Ext.util.Region', 'Ext.EventManager'],
+
+ alias: 'widget.window',
+
+ /**
+ * @cfg {Number} x
+ * The X position of the left edge of the window on initial showing. Defaults to centering the Window within the
+ * width of the Window's container {@link Ext.Element Element} (The Element that the Window is rendered to).
+ */
+
+ /**
+ * @cfg {Number} y
+ * The Y position of the top edge of the window on initial showing. Defaults to centering the Window within the
+ * height of the Window's container {@link Ext.Element Element} (The Element that the Window is rendered to).
+ */
+
+ /**
+ * @cfg {Boolean} [modal=false]
+ * True to make the window modal and mask everything behind it when displayed, false to display it without
+ * restricting access to other UI elements.
+ */
+
+ /**
+ * @cfg {String/Ext.Element} [animateTarget=null]
+ * Id or element from which the window should animate while opening.
+ */
+
+ /**
+ * @cfg {String/Number/Ext.Component} defaultFocus
+ * Specifies a Component to receive focus when this Window is focused.
+ *
+ * This may be one of:
+ *
+ * - The index of a footer Button.
+ * - The id or {@link Ext.AbstractComponent#itemId} of a descendant Component.
+ * - A Component.
+ */
+
+ /**
+ * @cfg {Function} onEsc
+ * Allows override of the built-in processing for the escape key. Default action is to close the Window (performing
+ * whatever action is specified in {@link #closeAction}. To prevent the Window closing when the escape key is
+ * pressed, specify this as {@link Ext#emptyFn Ext.emptyFn}.
+ */
+
+ /**
+ * @cfg {Boolean} [collapsed=false]
+ * True to render the window collapsed, false to render it expanded. Note that if {@link #expandOnShow}
+ * is true (the default) it will override the `collapsed` config and the window will always be
+ * expanded when shown.
+ */
+
+ /**
+ * @cfg {Boolean} [maximized=false]
+ * True to initially display the window in a maximized state.
+ */
+
+ /**
+ * @cfg {String} [baseCls='x-window']
+ * The base CSS class to apply to this panel's element.
+ */
+ baseCls: Ext.baseCSSPrefix + 'window',
+
+ /**
+ * @cfg {Boolean/Object} resizable
+ * Specify as `true` to allow user resizing at each edge and corner of the window, false to disable resizing.
+ *
+ * This may also be specified as a config object to Ext.resizer.Resizer
+ */
+ resizable: true,
+
+ /**
+ * @cfg {Boolean} draggable
+ * True to allow the window to be dragged by the header bar, false to disable dragging. Note that
+ * by default the window will be centered in the viewport, so if dragging is disabled the window may need to be
+ * positioned programmatically after render (e.g., myWindow.setPosition(100, 100);).
+ */
+ draggable: true,
+
+ /**
+ * @cfg {Boolean} constrain
+ * True to constrain the window within its containing element, false to allow it to fall outside of its containing
+ * element. By default the window will be rendered to document.body. To render and constrain the window within
+ * another element specify {@link #renderTo}. Optionally the header only can be constrained
+ * using {@link #constrainHeader}.
+ */
+ constrain: false,
+
+ /**
+ * @cfg {Boolean} constrainHeader
+ * True to constrain the window header within its containing element (allowing the window body to fall outside of
+ * its containing element) or false to allow the header to fall outside its containing element.
+ * Optionally the entire window can be constrained using {@link #constrain}.
+ */
+ constrainHeader: false,
+
+ /**
+ * @cfg {Ext.util.Region/Ext.Element} constrainTo
+ * A {@link Ext.util.Region Region} (or an element from which a Region measurement will be read) which is used
+ * to constrain the window.
+ */
+
+ /**
+ * @cfg {Boolean} plain
+ * True to render the window body with a transparent background so that it will blend into the framing elements,
+ * false to add a lighter background color to visually highlight the body element and separate it more distinctly
+ * from the surrounding frame.
+ */
+ plain: false,
+
+ /**
+ * @cfg {Boolean} minimizable
+ * True to display the 'minimize' tool button and allow the user to minimize the window, false to hide the button
+ * and disallow minimizing the window. Note that this button provides no implementation -- the
+ * behavior of minimizing a window is implementation-specific, so the minimize event must be handled and a custom
+ * minimize behavior implemented for this option to be useful.
+ */
+ minimizable: false,
+
+ /**
+ * @cfg {Boolean} maximizable
+ * True to display the 'maximize' tool button and allow the user to maximize the window, false to hide the button
+ * and disallow maximizing the window. Note that when a window is maximized, the tool button
+ * will automatically change to a 'restore' button with the appropriate behavior already built-in that will restore
+ * the window to its previous size.
+ */
+ maximizable: false,
+
+ // inherit docs
+ minHeight: 50,
+
+ // inherit docs
+ minWidth: 50,
+
+ /**
+ * @cfg {Boolean} expandOnShow
+ * True to always expand the window when it is displayed, false to keep it in its current state (which may be
+ * {@link #collapsed}) when displayed.
+ */
+ expandOnShow: true,
+
+ // inherited docs, same default
+ collapsible: false,
+
+ /**
+ * @cfg {Boolean} closable
+ * True to display the 'close' tool button and allow the user to close the window, false to hide the button and
+ * disallow closing the window.
+ *
+ * By default, when close is requested by either clicking the close button in the header or pressing ESC when the
+ * Window has focus, the {@link #method-close} method will be called. This will _{@link Ext.Component#method-destroy destroy}_ the
+ * Window and its content meaning that it may not be reused.
+ *
+ * To make closing a Window _hide_ the Window so that it may be reused, set {@link #closeAction} to 'hide'.
+ */
+ closable: true,
+
+ /**
+ * @cfg {Boolean} hidden
+ * Render this Window hidden. If `true`, the {@link #method-hide} method will be called internally.
+ */
+ hidden: true,
+
+ /**
+ * @cfg
+ * @inheritdoc
+ * Windows render to the body on first show.
+ */
+ autoRender: true,
+
+ /**
+ * @cfg
+ * @inheritdoc
+ * Windows hide using offsets in order to preserve the scroll positions of their descendants.
+ */
+ hideMode: 'offsets',
+
+ /**
+ * @cfg
+ * @private
+ */
+ floating: true,
+
+ ariaRole: 'alertdialog',
+
+ itemCls: Ext.baseCSSPrefix + 'window-item',
+
+ initialAlphaNum: /^[a-z0-9]/,
+
+ overlapHeader: true,
+
+ ignoreHeaderBorderManagement: true,
+
+ // Flag to Renderable to always look up the framing styles for this Component
+ alwaysFramed: true,
+
+ /**
+ * @property {Boolean} isWindow
+ * `true` in this class to identify an object as an instantiated Window, or subclass thereof.
+ */
+ isWindow: true,
+
+ // private
+ initComponent: function() {
+ var me = this;
+ // Explicitly set frame to false, since alwaysFramed is
+ // true, we only want to lookup framing in a specific instance
+ me.frame = false;
+ me.callParent();
+ me.addEvents(
+ /**
+ * @event activate
+ * Fires after the window has been visually activated via {@link #setActive}.
+ * @param {Ext.window.Window} this
+ */
+
+ /**
+ * @event deactivate
+ * Fires after the window has been visually deactivated via {@link #setActive}.
+ * @param {Ext.window.Window} this
+ */
+
+ /**
+ * @event resize
+ * Fires after the window has been resized.
+ * @param {Ext.window.Window} this
+ * @param {Number} width The window's new width
+ * @param {Number} height The window's new height
+ */
+ 'resize',
+
+ /**
+ * @event maximize
+ * Fires after the window has been maximized.
+ * @param {Ext.window.Window} this
+ */
+ 'maximize',
+
+ /**
+ * @event minimize
+ * Fires after the window has been minimized.
+ * @param {Ext.window.Window} this
+ */
+ 'minimize',
+
+ /**
+ * @event restore
+ * Fires after the window has been restored to its original size after being maximized.
+ * @param {Ext.window.Window} this
+ */
+ 'restore'
+ );
+
+ if (me.plain) {
+ me.addClsWithUI('plain');
+ }
+
+ if (me.modal) {
+ me.ariaRole = 'dialog';
+ }
+
+ // clickToRaise
+ if (me.floating) {
+ me.on({
+ element: 'el',
+ mousedown: me.onMouseDown,
+ scope: me
+ });
+ }
+
+ me.addStateEvents(['maximize', 'restore', 'resize', 'dragend']);
+ },
+
+ getElConfig: function () {
+ var me = this,
+ elConfig;
+
+ elConfig = me.callParent();
+ elConfig.tabIndex = -1;
+ return elConfig;
+ },
+
+ // State Management
+ // private
+
+ getState: function() {
+ var me = this,
+ state = me.callParent() || {},
+ maximized = !!me.maximized;
+
+ state.maximized = maximized;
+ Ext.apply(state, {
+ size: maximized ? me.restoreSize : me.getSize(),
+ pos: maximized ? me.restorePos : me.getPosition()
+ });
+ return state;
+ },
+
+ applyState: function(state){
+ var me = this;
+
+ if (state) {
+ me.maximized = state.maximized;
+ if (me.maximized) {
+ me.hasSavedRestore = true;
+ me.restoreSize = state.size;
+ me.restorePos = state.pos;
+ } else {
+ Ext.apply(me, {
+ width: state.size.width,
+ height: state.size.height,
+ x: state.pos[0],
+ y: state.pos[1]
+ });
+ }
+ }
+ },
+
+ // private
+ onMouseDown: function (e) {
+ var preventFocus;
+
+ if (this.floating) {
+ if (Ext.fly(e.getTarget()).focusable()) {
+ preventFocus = true;
+ }
+ this.toFront(preventFocus);
+ }
+ },
+
+ // private
+ onRender: function(ct, position) {
+ var me = this;
+ me.callParent(arguments);
+ me.focusEl = me.el;
+
+ // Double clicking a header will toggleMaximize
+ if (me.maximizable) {
+ me.header.on({
+ scope: me,
+ dblclick: me.toggleMaximize
+ });
+ }
+ },
+
+ // private
+ afterRender: function() {
+ var me = this,
+ keyMap;
+
+ me.callParent();
+
+ // Initialize
+ if (me.maximized) {
+ me.maximized = false;
+ me.maximize();
+ }
+
+ if (me.closable) {
+ keyMap = me.getKeyMap();
+ keyMap.on(27, me.onEsc, me);
+ } else {
+ keyMap = me.keyMap;
+ }
+ if (keyMap && me.hidden) {
+ keyMap.disable();
+ }
+ },
+
+ /**
+ * @private
+ * Override Component.initDraggable.
+ * Window uses the header element as the delegate.
+ */
+ initDraggable: function() {
+ var me = this,
+ ddConfig;
+
+ if (!me.header) {
+ me.updateHeader(true);
+ }
+
+ /*
+ * Check the header here again. If for whatever reason it wasn't created in
+ * updateHeader (we were configured with header: false) then we'll just ignore the rest since the
+ * header acts as the drag handle.
+ */
+ if (me.header) {
+ ddConfig = Ext.applyIf({
+ el: me.el,
+ delegate: '#' + Ext.escapeId(me.header.id)
+ }, me.draggable);
+
+ // Add extra configs if Window is specified to be constrained
+ if (me.constrain || me.constrainHeader) {
+ ddConfig.constrain = me.constrain;
+ ddConfig.constrainDelegate = me.constrainHeader;
+ ddConfig.constrainTo = me.constrainTo || me.container;
+ }
+
+ /**
+ * @property {Ext.util.ComponentDragger} dd
+ * If this Window is configured {@link #cfg-draggable}, this property will contain an instance of
+ * {@link Ext.util.ComponentDragger} (A subclass of {@link Ext.dd.DragTracker DragTracker}) which handles dragging
+ * the Window's DOM Element, and constraining according to the {@link #constrain} and {@link #constrainHeader} .
+ *
+ * This has implementations of `onBeforeStart`, `onDrag` and `onEnd` which perform the dragging action. If
+ * extra logic is needed at these points, use {@link Ext.Function#createInterceptor createInterceptor} or
+ * {@link Ext.Function#createSequence createSequence} to augment the existing implementations.
+ */
+ me.dd = new Ext.util.ComponentDragger(this, ddConfig);
+ me.relayEvents(me.dd, ['dragstart', 'drag', 'dragend']);
+ }
+ },
+
+ // private
+ onEsc: function(k, e) {
+ // Only process ESC if the FocusManager is not doing it
+ if (!Ext.FocusManager || !Ext.FocusManager.enabled || Ext.FocusManager.focusedCmp === this) {
+ e.stopEvent();
+ this.close();
+ }
+ },
+
+ // private
+ beforeDestroy: function() {
+ var me = this;
+ if (me.rendered) {
+ delete this.animateTarget;
+ me.hide();
+ Ext.destroy(
+ me.keyMap
+ );
+ }
+ me.callParent();
+ },
+
+ /**
+ * @private
+ * Contribute class-specific tools to the header.
+ * Called by Panel's initTools.
+ */
+ addTools: function() {
+ var me = this;
+
+ // Call Panel's initTools
+ me.callParent();
+
+ if (me.minimizable) {
+ me.addTool({
+ type: 'minimize',
+ handler: Ext.Function.bind(me.minimize, me, [])
+ });
+ }
+ if (me.maximizable) {
+ me.addTool({
+ type: 'maximize',
+ handler: Ext.Function.bind(me.maximize, me, [])
+ });
+ me.addTool({
+ type: 'restore',
+ handler: Ext.Function.bind(me.restore, me, []),
+ hidden: true
+ });
+ }
+ },
+
+ /**
+ * @private
+ * Returns the focus holder element associated with this Window. By default, this is the Window's element.
+ * @returns {Ext.Element/Ext.Component} the focus holding element or Component.
+ */
+ getFocusEl: function() {
+ return this.getDefaultFocus();
+ },
+
+ /**
+ * Gets the configured default focus item. If a {@link #defaultFocus} is set, it will
+ * receive focus when the Window's focus method is called, otherwise the
+ * Window itself will receive focus.
+ */
+ getDefaultFocus: function() {
+ var me = this,
+ result,
+ defaultComp = me.defaultButton || me.defaultFocus,
+ selector;
+
+ if (defaultComp !== undefined) {
+ // Number is index of Button
+ if (Ext.isNumber(defaultComp)) {
+ result = me.query('button')[defaultComp];
+ }
+ // String is ID or CQ selector
+ else if (Ext.isString(defaultComp)) {
+ selector = defaultComp;
+
+ // Try id/itemId match if selector begins with alphanumeric
+ if (selector.match(me.initialAlphaNum)) {
+ result = me.down('#' + selector);
+ }
+ // If not found, use as selector
+ if (!result) {
+ result = me.down(selector);
+ }
+ }
+ // Otherwise, if it's got a focus method, use it
+ else if (defaultComp.focus) {
+ result = defaultComp;
+ }
+ }
+ return result || me.el;
+ },
+
+ /**
+ * @private
+ * Called when a Component's focusEl receives focus.
+ * If there is a valid default focus Component to jump to, focus that,
+ * otherwise continue as usual, focus this Component.
+ */
+ onFocus: function() {
+ var me = this,
+ focusDescendant;
+
+ // If the FocusManager is enabled, then we must noy jumpt to focus the default focus. We must focus the Window
+ if ((Ext.FocusManager && Ext.FocusManager.enabled) || ((focusDescendant = me.getDefaultFocus()) === me)) {
+ me.callParent(arguments);
+ } else {
+ focusDescendant.focus();
+ }
+ },
+
+ beforeLayout: function () {
+ var shadow = this.el.shadow;
+
+ this.callParent();
+ if (shadow) {
+ shadow.hide();
+ }
+ },
+
+ onShow: function() {
+ var me = this;
+
+ me.callParent(arguments);
+ if (me.expandOnShow) {
+ me.expand(false);
+ }
+ me.syncMonitorWindowResize();
+
+ if (me.keyMap) {
+ me.keyMap.enable();
+ }
+ },
+
+ // private
+ doClose: function() {
+ var me = this;
+
+ // Being called as callback after going through the hide call below
+ if (me.hidden) {
+ me.fireEvent('close', me);
+ if (me.closeAction == 'destroy') {
+ this.destroy();
+ }
+ } else {
+ // close after hiding
+ me.hide(me.animateTarget, me.doClose, me);
+ }
+ },
+
+ // private
+ afterHide: function() {
+ var me = this;
+
+ // No longer subscribe to resizing now that we're hidden
+ me.syncMonitorWindowResize();
+
+ // Turn off keyboard handling once window is hidden
+ if (me.keyMap) {
+ me.keyMap.disable();
+ }
+
+ // Perform superclass's afterHide tasks.
+ me.callParent(arguments);
+ },
+
+ // private
+ onWindowResize: function() {
+ var me = this,
+ sizeModel;
+
+ if (me.maximized) {
+ me.fitContainer();
+ } else {
+ sizeModel = me.getSizeModel();
+ if (sizeModel.width.natural || sizeModel.height.natural) {
+ me.updateLayout();
+ }
+ }
+
+ me.doConstrain();
+ },
+
+ /**
+ * Placeholder method for minimizing the window. By default, this method simply fires the {@link #event-minimize} event
+ * since the behavior of minimizing a window is application-specific. To implement custom minimize behavior, either
+ * the minimize event can be handled or this method can be overridden.
+ * @return {Ext.window.Window} this
+ */
+ minimize: function() {
+ this.fireEvent('minimize', this);
+ return this;
+ },
+
+ afterCollapse: function() {
+ var me = this;
+
+ if (me.maximizable) {
+ me.tools.maximize.hide();
+ me.tools.restore.hide();
+ }
+ if (me.resizer) {
+ me.resizer.disable();
+ }
+ me.callParent(arguments);
+ },
+
+ afterExpand: function() {
+ var me = this;
+
+ if (me.maximized) {
+ me.tools.restore.show();
+ } else if (me.maximizable) {
+ me.tools.maximize.show();
+ }
+ if (me.resizer) {
+ me.resizer.enable();
+ }
+ me.callParent(arguments);
+ },
+
+ /**
+ * Fits the window within its current container and automatically replaces the {@link #maximizable 'maximize' tool
+ * button} with the 'restore' tool button. Also see {@link #toggleMaximize}.
+ * @return {Ext.window.Window} this
+ */
+ maximize: function() {
+ var me = this;
+
+ if (!me.maximized) {
+ me.expand(false);
+ if (!me.hasSavedRestore) {
+ me.restoreSize = me.getSize();
+ me.restorePos = me.getPosition(true);
+ }
+ if (me.maximizable) {
+ me.tools.maximize.hide();
+ me.tools.restore.show();
+ }
+ me.maximized = true;
+ me.el.disableShadow();
+
+ if (me.dd) {
+ me.dd.disable();
+ }
+ if (me.resizer) {
+ me.resizer.disable();
+ }
+ if (me.collapseTool) {
+ me.collapseTool.hide();
+ }
+ me.el.addCls(Ext.baseCSSPrefix + 'window-maximized');
+ me.container.addCls(Ext.baseCSSPrefix + 'window-maximized-ct');
+
+ me.syncMonitorWindowResize();
+ me.fitContainer();
+ me.fireEvent('maximize', me);
+ }
+ return me;
+ },
+
+ /**
+ * Restores a {@link #maximizable maximized} window back to its original size and position prior to being maximized
+ * and also replaces the 'restore' tool button with the 'maximize' tool button. Also see {@link #toggleMaximize}.
+ * @return {Ext.window.Window} this
+ */
+ restore: function() {
+ var me = this,
+ tools = me.tools;
+
+ if (me.maximized) {
+ delete me.hasSavedRestore;
+ me.removeCls(Ext.baseCSSPrefix + 'window-maximized');
+
+ // Toggle tool visibility
+ if (tools.restore) {
+ tools.restore.hide();
+ }
+ if (tools.maximize) {
+ tools.maximize.show();
+ }
+ if (me.collapseTool) {
+ me.collapseTool.show();
+ }
+
+ me.maximized = false;
+
+ // Restore the position/sizing
+ me.setPosition(me.restorePos);
+ me.setSize(me.restoreSize);
+
+ // Unset old position/sizing
+ delete me.restorePos;
+ delete me.restoreSize;
+
+ me.el.enableShadow(true);
+
+ // Allow users to drag and drop again
+ if (me.dd) {
+ me.dd.enable();
+ }
+
+ if (me.resizer) {
+ me.resizer.enable();
+ }
+
+ me.container.removeCls(Ext.baseCSSPrefix + 'window-maximized-ct');
+
+ me.syncMonitorWindowResize();
+ me.doConstrain();
+ me.fireEvent('restore', me);
+ }
+ return me;
+ },
+
+ /**
+ * Synchronizes the presence of our listener for window resize events. This method
+ * should be called whenever this status might change.
+ * @private
+ */
+ syncMonitorWindowResize: function () {
+ var me = this,
+ currentlyMonitoring = me._monitoringResize,
+ // all the states where we should be listening to window resize:
+ yes = me.monitorResize || me.constrain || me.constrainHeader || me.maximized,
+ // all the states where we veto this:
+ veto = me.hidden || me.destroying || me.isDestroyed;
+
+ if (yes && !veto) {
+ // we should be listening...
+ if (!currentlyMonitoring) {
+ // but we aren't, so set it up
+ Ext.EventManager.onWindowResize(me.onWindowResize, me);
+ me._monitoringResize = true;
+ }
+ } else if (currentlyMonitoring) {
+ // we should not be listening, but we are, so tear it down
+ Ext.EventManager.removeResizeListener(me.onWindowResize, me);
+ me._monitoringResize = false;
+ }
+ },
+
+ /**
+ * A shortcut method for toggling between {@link #method-maximize} and {@link #method-restore} based on the current maximized
+ * state of the window.
+ * @return {Ext.window.Window} this
+ */
+ toggleMaximize: function() {
+ return this[this.maximized ? 'restore': 'maximize']();
+ }
+
+});
+
+/**
+ * Layout class for components with {@link Ext.form.Labelable field labeling}, handling the sizing and alignment of
+ * the form control, label, and error message treatment.
+ * @private
+ */
+Ext.define('Ext.layout.component.field.Field', {
+
+ /* Begin Definitions */
+
+ extend: 'Ext.layout.component.Auto',
+
+ alias: 'layout.field',
+
+ uses: ['Ext.tip.QuickTip', 'Ext.util.TextMetrics', 'Ext.util.CSS'],
+
+ /* End Definitions */
+
+ type: 'field',
+
+ naturalSizingProp: 'size',
+
+ beginLayout: function(ownerContext) {
+ var me = this,
+ owner = me.owner,
+ widthModel = ownerContext.widthModel,
+ ownerNaturalSize = owner[me.naturalSizingProp],
+ width;
+
+ me.callParent(arguments);
+
+ ownerContext.labelStrategy = me.getLabelStrategy();
+ ownerContext.errorStrategy = me.getErrorStrategy();
+
+ ownerContext.labelContext = ownerContext.getEl('labelEl');
+ ownerContext.bodyCellContext = ownerContext.getEl('bodyEl');
+ ownerContext.inputContext = ownerContext.getEl('inputEl');
+ ownerContext.errorContext = ownerContext.getEl('errorEl');
+
+ // width:100% on an element inside a table in IE6/7 "strict" sizes the content box.
+ // store the input element's border and padding info so that subclasses can take it into consideration if needed
+ if ((Ext.isIE6 || Ext.isIE7) && Ext.isStrict && ownerContext.inputContext) {
+ me.ieInputWidthAdjustment = ownerContext.inputContext.getPaddingInfo().width + ownerContext.inputContext.getBorderInfo().width;
+ }
+
+ // perform preparation on the label and error (setting css classes, qtips, etc.)
+ ownerContext.labelStrategy.prepare(ownerContext, owner);
+ ownerContext.errorStrategy.prepare(ownerContext, owner);
+
+ // Body cell must stretch to use up available width unless the field is auto width
+ if (widthModel.shrinkWrap) {
+ // When the width needs to be auto, table-layout cannot be fixed
+ me.beginLayoutShrinkWrap(ownerContext);
+ } else if (widthModel.natural) {
+
+ // When a size specified, natural becomes fixed width unless the inpiutWidth is specified - we shrinkwrap that
+ if (typeof ownerNaturalSize == 'number' && !owner.inputWidth) {
+ me.beginLayoutFixed(ownerContext, (width = ownerNaturalSize * 6.5 + 20), 'px');
+ }
+
+ // Otherwise it is the same as shrinkWrap
+ else {
+ me.beginLayoutShrinkWrap(ownerContext);
+ }
+ ownerContext.setWidth(width, false);
+ } else {
+ me.beginLayoutFixed(ownerContext, '100', '%');
+ }
+ },
+
+ beginLayoutFixed: function (ownerContext, width, suffix) {
+ var owner = ownerContext.target,
+ inputEl = owner.inputEl,
+ inputWidth = owner.inputWidth;
+
+ owner.el.setStyle('table-layout', 'fixed');
+ owner.bodyEl.setStyle('width', width + suffix);
+ if (inputEl && inputWidth) {
+ inputEl.setStyle('width', inputWidth + 'px');
+ }
+ ownerContext.isFixed = true;
+ },
+
+ beginLayoutShrinkWrap: function (ownerContext) {
+ var owner = ownerContext.target,
+ inputEl = owner.inputEl,
+ inputWidth = owner.inputWidth;
+
+ if (inputEl && inputEl.dom) {
+ inputEl.dom.removeAttribute('size');
+ if (inputWidth) {
+ inputEl.setStyle('width', inputWidth + 'px');
+ }
+ }
+ owner.el.setStyle('table-layout', 'auto');
+ owner.bodyEl.setStyle('width', '');
+ },
+
+ finishedLayout: function(ownerContext){
+ var owner = this.owner;
+
+ this.callParent(arguments);
+ ownerContext.labelStrategy.finishedLayout(ownerContext, owner);
+ ownerContext.errorStrategy.finishedLayout(ownerContext, owner);
+ },
+
+ calculateOwnerHeightFromContentHeight: function(ownerContext, contentHeight) {
+ return contentHeight;
+ },
+
+ measureContentHeight: function (ownerContext) {
+ return ownerContext.el.getHeight();
+ },
+
+ measureContentWidth: function (ownerContext) {
+ return ownerContext.el.getWidth();
+ },
+
+ measureLabelErrorHeight: function (ownerContext) {
+ return ownerContext.labelStrategy.getHeight(ownerContext) +
+ ownerContext.errorStrategy.getHeight(ownerContext);
+ },
+
+ onFocus: function() {
+ this.getErrorStrategy().onFocus(this.owner);
+ },
+
+ /**
+ * Return the set of strategy functions from the {@link #labelStrategies labelStrategies collection}
+ * that is appropriate for the field's {@link Ext.form.Labelable#labelAlign labelAlign} config.
+ */
+ getLabelStrategy: function() {
+ var me = this,
+ strategies = me.labelStrategies,
+ labelAlign = me.owner.labelAlign;
+ return strategies[labelAlign] || strategies.base;
+ },
+
+ /**
+ * Return the set of strategy functions from the {@link #errorStrategies errorStrategies collection}
+ * that is appropriate for the field's {@link Ext.form.Labelable#msgTarget msgTarget} config.
+ */
+ getErrorStrategy: function() {
+ var me = this,
+ owner = me.owner,
+ strategies = me.errorStrategies,
+ msgTarget = owner.msgTarget;
+ return !owner.preventMark && Ext.isString(msgTarget) ?
+ (strategies[msgTarget] || strategies.elementId) :
+ strategies.none;
+ },
+
+ /**
+ * Collection of named strategies for laying out and adjusting labels to accommodate error messages.
+ * An appropriate one will be chosen based on the owner field's {@link Ext.form.Labelable#labelAlign} config.
+ */
+ labelStrategies: (function() {
+ var base = {
+ prepare: function(ownerContext, owner) {
+ var cls = owner.labelCls + '-' + owner.labelAlign,
+ labelEl = owner.labelEl;
+
+ if (labelEl) {
+ labelEl.addCls(cls);
+ }
+ },
+
+ getHeight: function () {
+ return 0;
+ },
+
+ finishedLayout: Ext.emptyFn
+ };
+
+ return {
+ base: base,
+
+ /**
+ * Label displayed above the bodyEl
+ */
+ top: Ext.applyIf({
+
+ getHeight: function (ownerContext) {
+ var labelContext = ownerContext.labelContext,
+ props = labelContext.props,
+ height = props.height;
+
+ if (height === undefined) {
+ props.height = height = labelContext.el.getHeight();
+ }
+
+ return height;
+ }
+ }, base),
+
+ /**
+ * Label displayed to the left of the bodyEl
+ */
+ left: base,
+
+ /**
+ * Same as left, only difference is text-align in CSS
+ */
+ right: base
+ };
+ }()),
+
+ /**
+ * Collection of named strategies for laying out and adjusting insets to accommodate error messages.
+ * An appropriate one will be chosen based on the owner field's {@link Ext.form.Labelable#msgTarget} config.
+ */
+ errorStrategies: (function() {
+ function showTip(owner) {
+ var tip = Ext.layout.component.field.Field.tip,
+ target;
+
+ if (tip && tip.isVisible()) {
+ target = tip.activeTarget;
+ if (target && target.el === owner.getActionEl().dom) {
+ tip.toFront(true);
+ }
+ }
+ }
+
+ var applyIf = Ext.applyIf,
+ emptyFn = Ext.emptyFn,
+ iconCls = Ext.baseCSSPrefix + 'form-invalid-icon',
+ iconWidth,
+ base = {
+ prepare: function(ownerContext, owner) {
+ var el = owner.errorEl;
+ if (el) {
+ el.setDisplayed(false);
+ }
+ },
+ getHeight: function () {
+ return 0;
+ },
+ onFocus: emptyFn,
+ finishedLayout: emptyFn
+ };
+
+ return {
+ none: base,
+
+ /**
+ * Error displayed as icon (with QuickTip on hover) to right of the bodyEl
+ */
+ side: applyIf({
+ prepare: function(ownerContext, owner) {
+ var errorEl = owner.errorEl,
+ sideErrorCell = owner.sideErrorCell,
+ displayError = owner.hasActiveError(),
+ tempEl;
+
+ // Capture error icon width once
+ if (!iconWidth) {
+ iconWidth = (tempEl = Ext.getBody().createChild({style: 'position:absolute', cls: iconCls})).getWidth();
+ tempEl.remove();
+ }
+
+ errorEl.addCls(iconCls);
+ errorEl.set({'data-errorqtip': owner.getActiveError() || ''});
+ if (owner.autoFitErrors) {
+ errorEl.setDisplayed(displayError);
+ }
+ // Not autofitting, the space must still be allocated.
+ else {
+ errorEl.setVisible(displayError);
+ }
+
+ // If we are auto fitting, then hide and show the entire cell
+ if (sideErrorCell && owner.autoFitErrors) {
+ sideErrorCell.setDisplayed(displayError);
+ }
+ owner.bodyEl.dom.colSpan = owner.getBodyColspan();
+
+ // TODO: defer the tip call until after the layout to avoid immediate DOM reads now
+ Ext.layout.component.field.Field.initTip();
+ },
+ onFocus: showTip
+ }, base),
+
+ /**
+ * Error message displayed underneath the bodyEl
+ */
+ under: applyIf({
+ prepare: function(ownerContext, owner) {
+ var errorEl = owner.errorEl,
+ cls = Ext.baseCSSPrefix + 'form-invalid-under';
+
+ errorEl.addCls(cls);
+ errorEl.setDisplayed(owner.hasActiveError());
+ },
+ getHeight: function (ownerContext) {
+ var height = 0,
+ errorContext, props;
+
+ if (ownerContext.target.hasActiveError()) {
+ errorContext = ownerContext.errorContext;
+ props = errorContext.props;
+ height = props.height;
+
+ if (height === undefined) {
+ props.height = height = errorContext.el.getHeight();
+ }
+ }
+
+ return height;
+ }
+ }, base),
+
+ /**
+ * Error displayed as QuickTip on hover of the field container
+ */
+ qtip: applyIf({
+ prepare: function(ownerContext, owner) {
+ Ext.layout.component.field.Field.initTip();
+ owner.getActionEl().set({'data-errorqtip': owner.getActiveError() || ''});
+ },
+ onFocus: showTip
+ }, base),
+
+ /**
+ * Error displayed as title tip on hover of the field container
+ */
+ title: applyIf({
+ prepare: function(ownerContext, owner) {
+ owner.el.set({'title': owner.getActiveError() || ''});
+ }
+ }, base),
+
+ /**
+ * Error message displayed as content of an element with a given id elsewhere in the app
+ */
+ elementId: applyIf({
+ prepare: function(ownerContext, owner) {
+ var targetEl = Ext.fly(owner.msgTarget);
+ if (targetEl) {
+ targetEl.dom.innerHTML = owner.getActiveError() || '';
+ targetEl.setDisplayed(owner.hasActiveError());
+ }
+ }
+ }, base)
+ };
+ }()),
+
+ statics: {
+ /**
+ * Use a custom QuickTip instance separate from the main QuickTips singleton, so that we
+ * can give it a custom frame style. Responds to errorqtip rather than the qtip property.
+ * @static
+ */
+ initTip: function() {
+ var tip = this.tip;
+ if (!tip) {
+ tip = this.tip = Ext.create('Ext.tip.QuickTip', {
+ baseCls: Ext.baseCSSPrefix + 'form-invalid-tip'
+ });
+ tip.tagConfig = Ext.apply({}, {attribute: 'errorqtip'}, tip.tagConfig);
+ }
+ },
+
+ /**
+ * Destroy the error tip instance.
+ * @static
+ */
+ destroyTip: function() {
+ var tip = this.tip;
+ if (tip) {
+ tip.destroy();
+ delete this.tip;
+ }
+ }
+ }
+});
+
+/**
+ * Layout class for {@link Ext.form.field.Text} fields. Handles sizing the input field.
+ * @private
+ */
+Ext.define('Ext.layout.component.field.Text', {
+ extend: 'Ext.layout.component.field.Field',
+ alias: 'layout.textfield',
+ requires: ['Ext.util.TextMetrics'],
+
+ type: 'textfield',
+
+ canGrowWidth: true,
+
+ beginLayoutCycle: function(ownerContext) {
+ var me = this;
+
+ me.callParent(arguments);
+
+ // Clear height, in case a previous layout cycle stretched it.
+ if (ownerContext.shrinkWrap) {
+ ownerContext.inputContext.el.setStyle('height', '');
+ }
+ },
+
+ measureContentWidth: function (ownerContext) {
+ var me = this,
+ owner = me.owner,
+ width = me.callParent(arguments),
+ inputContext = ownerContext.inputContext,
+ inputEl, value, calcWidth, max, min;
+
+ if (owner.grow && me.canGrowWidth && !ownerContext.state.growHandled) {
+ inputEl = owner.inputEl;
+
+ // Find the width that contains the whole text value
+ value = Ext.util.Format.htmlEncode(inputEl.dom.value || (owner.hasFocus ? '' : owner.emptyText) || '');
+ value += owner.growAppend;
+ calcWidth = inputEl.getTextWidth(value) + inputContext.getFrameInfo().width;
+
+ max = owner.growMax;
+ min = Math.min(max, width);
+ max = Math.max(owner.growMin, max, min);
+
+ // Constrain
+ calcWidth = Ext.Number.constrain(calcWidth, owner.growMin, max);
+ inputContext.setWidth(calcWidth);
+ ownerContext.state.growHandled = true;
+
+ // Now that we've set the inputContext, we need to recalculate the width
+ inputContext.domBlock(me, 'width');
+ width = NaN;
+ }
+ return width;
+ },
+
+ publishInnerHeight: function(ownerContext, height) {
+ ownerContext.inputContext.setHeight(height - this.measureLabelErrorHeight(ownerContext));
+ },
+
+ beginLayoutFixed: function(ownerContext, width, suffix) {
+ var me = this,
+ ieInputWidthAdjustment = me.ieInputWidthAdjustment;
+
+ if (ieInputWidthAdjustment) {
+ // adjust for IE 6/7 strict content-box model
+ // RTL: This might have to be padding-left unless the senses of the padding styles switch when in RTL mode.
+ me.owner.bodyEl.setStyle('padding-right', ieInputWidthAdjustment + 'px');
+ if(suffix === 'px') {
+ width -= ieInputWidthAdjustment;
+ }
+ }
+
+ me.callParent(arguments);
+ }
+});
+
+/**
+ * A mixin which allows a component to be configured and decorated with a label and/or error message as is
+ * common for form fields. This is used by e.g. Ext.form.field.Base and Ext.form.FieldContainer
+ * to let them be managed by the Field layout.
+ *
+ * NOTE: This mixin is mainly for internal library use and most users should not need to use it directly. It
+ * is more likely you will want to use one of the component classes that import this mixin, such as
+ * Ext.form.field.Base or Ext.form.FieldContainer.
+ *
+ * Use of this mixin does not make a component a field in the logical sense, meaning it does not provide any
+ * logic or state related to values or validation; that is handled by the related Ext.form.field.Field
+ * mixin. These two mixins may be used separately (for example Ext.form.FieldContainer is Labelable but not a
+ * Field), or in combination (for example Ext.form.field.Base implements both and has logic for connecting the
+ * two.)
+ *
+ * Component classes which use this mixin should use the Field layout
+ * or a derivation thereof to properly size and position the label and message according to the component config.
+ * They must also call the {@link #initLabelable} method during component initialization to ensure the mixin gets
+ * set up correctly.
+ *
+ * @docauthor Jason Johnston
+ */
+Ext.define("Ext.form.Labelable", {
+ requires: ['Ext.XTemplate'],
+
+ autoEl: {
+ tag: 'table',
+ cellpadding: 0
+ },
+
+ childEls: [
+ /**
+ * @property {Ext.Element} labelCell
+ * The `` Element which contains the label Element for this component. Only available after the component has been rendered.
+ */
+ 'labelCell',
+
+ /**
+ * @property {Ext.Element} labelEl
+ * The label Element for this component. Only available after the component has been rendered.
+ */
+ 'labelEl',
+
+ /**
+ * @property {Ext.Element} bodyEl
+ * The div Element wrapping the component's contents. Only available after the component has been rendered.
+ */
+ 'bodyEl',
+
+ // private - the TD which contains the msgTarget: 'side' error icon
+ 'sideErrorCell',
+
+ /**
+ * @property {Ext.Element} errorEl
+ * The div Element that will contain the component's error message(s). Note that depending on the configured
+ * {@link #msgTarget}, this element may be hidden in favor of some other form of presentation, but will always
+ * be present in the DOM for use by assistive technologies.
+ */
+ 'errorEl',
+
+ 'inputRow',
+
+ 'bottomPlaceHolder'
+ ],
+
+ /**
+ * @cfg {String/String[]/Ext.XTemplate} labelableRenderTpl
+ * The rendering template for the field decorations. Component classes using this mixin
+ * should include logic to use this as their {@link Ext.AbstractComponent#renderTpl renderTpl},
+ * and implement the {@link #getSubTplMarkup} method to generate the field body content.
+ *
+ * The structure of a field is a table as follows:
+ *
+ * If `labelAlign: 'left', `msgTarget: 'side'`
+ *
+ * +----------------------+----------------------+-------------+
+ * | Label: | InputField | sideErrorEl |
+ * +----------------------+----------------------+-------------+
+ *
+ * If `labelAlign: 'left', `msgTarget: 'under'`
+ *
+ * +----------------------+------------------------------------+
+ * | Label: | InputField (colspan=2) |
+ * | | underErrorEl |
+ * +----------------------+------------------------------------+
+ *
+ * If `labelAlign: 'top', `msgTarget: 'side'`
+ *
+ * +---------------------------------------------+-------------+
+ * | label | |
+ * | InputField | sideErrorEl |
+ * +---------------------------------------------+-------------+
+ *
+ * If `labelAlign: 'top', `msgTarget: 'under'`
+ *
+ * +-----------------------------------------------------------+
+ * | label |
+ * | InputField (colspan=2) |
+ * | underErrorEl |
+ * +-----------------------------------------------------------+
+ *
+ * The total columns always the same for fields with each setting of {@link #labelAlign} because when
+ * rendered into a {@link Ext.layout.container.Form} layout, just the `TR` of the table
+ * will be placed into the form's main `TABLE`, and the columns of all the siblings
+ * must match so that they all line up. In a {@link Ext.layout.container.Form} layout, different
+ * settings of {@link #labelAlign} are not supported because of the incompatible column structure.
+ *
+ * When the triggerCell or side error cell are hidden or shown, the input cell's colspan
+ * is recalculated to maintain the correct 3 visible column count.
+ * @private
+ */
+ labelableRenderTpl: [
+
+ // body row. If a heighted Field (eg TextArea, HtmlEditor, this must greedily consume height.
+ ' id="{id}">',
+
+ // Label cell
+ '',
+ '',
+ '{beforeLabelTpl}',
+ ' for="{inputId}" class="{labelCls}"',
+ ' style="{labelStyle}" >',
+ '{beforeLabelTextTpl}',
+ '{fieldLabel}{labelSeparator} ',
+ '{afterLabelTextTpl}',
+ ' ',
+ '{afterLabelTpl}',
+ ' ',
+ ' ',
+
+ // Body of the input. That will be an input element, or, from a TriggerField, a table containing an input cell and trigger cell(s)
+ '',
+ '{beforeBodyEl}',
+
+ // Label just sits on top of the input field if labelAlign === 'top'
+ '',
+ '{beforeLabelTpl}',
+ '',
+ ' for="{inputId}" class="{labelCls}"',
+ ' style="{labelStyle}" >',
+ '{beforeLabelTextTpl}',
+ '{fieldLabel}{labelSeparator} ',
+ '{afterLabelTextTpl}',
+ ' ',
+ '
',
+ '{afterLabelTpl}',
+ ' ',
+
+ '{beforeSubTpl}',
+ '{[values.$comp.getSubTplMarkup()]}',
+ '{afterSubTpl}',
+
+ // Final TD. It's a side error element unless there's a floating external one
+ '',
+ '{afterBodyEl}',
+ ' ',
+ '',
+ '
',
+ ' ',
+ '',
+ '
',
+ '{afterBodyEl}',
+ '',
+ ' ',
+
+ ' ',
+ {
+ disableFormats: true
+ }
+ ],
+
+ /**
+ * @cfg {String/String[]/Ext.XTemplate} activeErrorsTpl
+ * The template used to format the Array of error messages passed to {@link #setActiveErrors} into a single HTML
+ * string. By default this renders each message as an item in an unordered list.
+ */
+ activeErrorsTpl: [
+ '',
+ '',
+ ' '
+ ],
+
+ /**
+ * @property {Boolean} isFieldLabelable
+ * Flag denoting that this object is labelable as a field. Always true.
+ */
+ isFieldLabelable: true,
+
+ /**
+ * @cfg {String} formItemCls
+ * A CSS class to be applied to the outermost element to denote that it is participating in the form field layout.
+ */
+ formItemCls: Ext.baseCSSPrefix + 'form-item',
+
+ /**
+ * @cfg {String} labelCls
+ * The CSS class to be applied to the label element. This (single) CSS class is used to formulate the renderSelector
+ * and drives the field layout where it is concatenated with a hyphen ('-') and {@link #labelAlign}. To add
+ * additional classes, use {@link #labelClsExtra}.
+ */
+ labelCls: Ext.baseCSSPrefix + 'form-item-label',
+
+ /**
+ * @cfg {String} labelClsExtra
+ * An optional string of one or more additional CSS classes to add to the label element. Defaults to empty.
+ */
+
+ /**
+ * @cfg {String} errorMsgCls
+ * The CSS class to be applied to the error message element.
+ */
+ errorMsgCls: Ext.baseCSSPrefix + 'form-error-msg',
+
+ /**
+ * @cfg {String} baseBodyCls
+ * The CSS class to be applied to the body content element.
+ */
+ baseBodyCls: Ext.baseCSSPrefix + 'form-item-body',
+
+ /**
+ * @cfg {String} fieldBodyCls
+ * An extra CSS class to be applied to the body content element in addition to {@link #baseBodyCls}.
+ */
+ fieldBodyCls: '',
+
+ /**
+ * @cfg {String} clearCls
+ * The CSS class to be applied to the special clearing div rendered directly after the field contents wrapper to
+ * provide field clearing.
+ */
+ clearCls: Ext.baseCSSPrefix + 'clear',
+
+ /**
+ * @cfg {String} invalidCls
+ * The CSS class to use when marking the component invalid.
+ */
+ invalidCls : Ext.baseCSSPrefix + 'form-invalid',
+
+ /**
+ * @cfg {String} fieldLabel
+ * The label for the field. It gets appended with the {@link #labelSeparator}, and its position and sizing is
+ * determined by the {@link #labelAlign}, {@link #labelWidth}, and {@link #labelPad} configs.
+ */
+ fieldLabel: undefined,
+
+ /**
+ * @cfg {String} labelAlign
+ * Controls the position and alignment of the {@link #fieldLabel}. Valid values are:
+ *
+ * - "left" (the default) - The label is positioned to the left of the field, with its text aligned to the left.
+ * Its width is determined by the {@link #labelWidth} config.
+ * - "top" - The label is positioned above the field.
+ * - "right" - The label is positioned to the left of the field, with its text aligned to the right.
+ * Its width is determined by the {@link #labelWidth} config.
+ */
+ labelAlign : 'left',
+
+ /**
+ * @cfg {Number} labelWidth
+ * The width of the {@link #fieldLabel} in pixels. Only applicable if the {@link #labelAlign} is set to "left" or
+ * "right".
+ */
+ labelWidth: 100,
+
+ /**
+ * @cfg {Number} labelPad
+ * The amount of space in pixels between the {@link #fieldLabel} and the input field.
+ */
+ labelPad : 5,
+
+ //
+ /**
+ * @cfg {String} labelSeparator
+ * Character(s) to be inserted at the end of the {@link #fieldLabel label text}.
+ *
+ * Set to empty string to hide the separator completely.
+ */
+ labelSeparator : ':',
+ //
+
+ /**
+ * @cfg {String} labelStyle
+ * A CSS style specification string to apply directly to this field's label.
+ */
+
+ /**
+ * @cfg {Boolean} hideLabel
+ * Set to true to completely hide the label element ({@link #fieldLabel} and {@link #labelSeparator}). Also see
+ * {@link #hideEmptyLabel}, which controls whether space will be reserved for an empty fieldLabel.
+ */
+ hideLabel: false,
+
+ /**
+ * @cfg {Boolean} hideEmptyLabel
+ * When set to true, the label element ({@link #fieldLabel} and {@link #labelSeparator}) will be automatically
+ * hidden if the {@link #fieldLabel} is empty. Setting this to false will cause the empty label element to be
+ * rendered and space to be reserved for it; this is useful if you want a field without a label to line up with
+ * other labeled fields in the same form.
+ *
+ * If you wish to unconditionall hide the label even if a non-empty fieldLabel is configured, then set the
+ * {@link #hideLabel} config to true.
+ */
+ hideEmptyLabel: true,
+
+ /**
+ * @cfg {Boolean} preventMark
+ * true to disable displaying any {@link #setActiveError error message} set on this object.
+ */
+ preventMark: false,
+
+ /**
+ * @cfg {Boolean} autoFitErrors
+ * Whether to adjust the component's body area to make room for 'side' or 'under' {@link #msgTarget error messages}.
+ */
+ autoFitErrors: true,
+
+ /**
+ * @cfg {String} msgTarget
+ * The location where the error message text should display. Must be one of the following values:
+ *
+ * - `qtip` Display a quick tip containing the message when the user hovers over the field.
+ * This is the default.
+ *
+ * **{@link Ext.tip.QuickTipManager#init} must have been called for this setting to work.**
+ *
+ * - `title` Display the message in a default browser title attribute popup.
+ * - `under` Add a block div beneath the field containing the error message.
+ * - `side` Add an error icon to the right of the field, displaying the message in a popup on hover.
+ * - `none` Don't display any error message. This might be useful if you are implementing custom error display.
+ * - `[element id]` Add the error message directly to the innerHTML of the specified element.
+ */
+ msgTarget: 'qtip',
+
+ /**
+ * @cfg {String} activeError
+ * If specified, then the component will be displayed with this value as its active error when first rendered. Use
+ * {@link #setActiveError} or {@link #unsetActiveError} to change it after component creation.
+ */
+
+ /**
+ * @private
+ * Tells the layout system that the height can be measured immediately because the width does not need setting.
+ */
+ noWrap: true,
+
+ labelableInsertions: [
+
+ /**
+ * @cfg {String/Array/Ext.XTemplate} beforeBodyEl
+ * An optional string or `XTemplate` configuration to insert in the field markup
+ * at the beginning of the input containing element. If an `XTemplate` is used, the component's {@link Ext.AbstractComponent#renderData render data}
+ * serves as the context.
+ */
+ 'beforeBodyEl',
+
+ /**
+ * @cfg {String/Array/Ext.XTemplate} afterBodyEl
+ * An optional string or `XTemplate` configuration to insert in the field markup
+ * at the end of the input containing element. If an `XTemplate` is used, the component's {@link Ext.AbstractComponent#renderData render data}
+ * serves as the context.
+ */
+ 'afterBodyEl',
+
+ /**
+ * @cfg {String/Array/Ext.XTemplate} beforeLabelTpl
+ * An optional string or `XTemplate` configuration to insert in the field markup
+ * before the label element. If an `XTemplate` is used, the component's {@link Ext.AbstractComponent#renderData render data}
+ * serves as the context.
+ */
+ 'beforeLabelTpl',
+
+ /**
+ * @cfg {String/Array/Ext.XTemplate} afterLabelTpl
+ * An optional string or `XTemplate` configuration to insert in the field markup
+ * after the label element. If an `XTemplate` is used, the component's {@link Ext.AbstractComponent#renderData render data}
+ * serves as the context.
+ */
+ 'afterLabelTpl',
+
+ /**
+ * @cfg {String/Array/Ext.XTemplate} beforeSubTpl
+ * An optional string or `XTemplate` configuration to insert in the field markup
+ * before the {@link #getSubTplMarkup subTpl markup}. If an `XTemplate` is used, the
+ * component's {@link Ext.AbstractComponent#renderData render data} serves as the context.
+ */
+ 'beforeSubTpl',
+
+ /**
+ * @cfg {String/Array/Ext.XTemplate} afterSubTpl
+ * An optional string or `XTemplate` configuration to insert in the field markup
+ * after the {@link #getSubTplMarkup subTpl markup}. If an `XTemplate` is used, the
+ * component's {@link Ext.AbstractComponent#renderData render data} serves as the context.
+ */
+ 'afterSubTpl',
+
+ /**
+ * @cfg {String/Array/Ext.XTemplate} beforeLabelTextTpl
+ * An optional string or `XTemplate` configuration to insert in the field markup
+ * before the label text. If an `XTemplate` is used, the component's {@link Ext.AbstractComponent#renderData render data}
+ * serves as the context.
+ */
+ 'beforeLabelTextTpl',
+
+ /**
+ * @cfg {String/Array/Ext.XTemplate} afterLabelTextTpl
+ * An optional string or `XTemplate` configuration to insert in the field markup
+ * after the label text. If an `XTemplate` is used, the component's {@link Ext.AbstractComponent#renderData render data}
+ * serves as the context.
+ */
+ 'afterLabelTextTpl',
+
+ /**
+ * @cfg {String/Array/Ext.XTemplate} labelAttrTpl
+ * An optional string or `XTemplate` configuration to insert in the field markup
+ * inside the label element (as attributes). If an `XTemplate` is used, the component's
+ * {@link Ext.AbstractComponent#renderData render data} serves as the context.
+ */
+ 'labelAttrTpl'
+ ],
+
+ // This is an array to avoid a split on every call to Ext.copyTo
+ labelableRenderProps: [ 'allowBlank', 'id', 'labelAlign', 'fieldBodyCls', 'baseBodyCls',
+ 'clearCls', 'labelSeparator', 'msgTarget' ],
+
+ /**
+ * Performs initialization of this mixin. Component classes using this mixin should call this method during their
+ * own initialization.
+ */
+ initLabelable: function() {
+ var me = this,
+ padding = me.padding;
+
+ // This Component is rendered as a table. Padding doesn't work on tables
+ // Before padding can be applied to the encapsulating table element, copy the padding into
+ // an extraMargins property which is to be added to all computed margins post render :(
+ if (padding) {
+ me.padding = undefined;
+ me.extraMargins = Ext.Element.parseBox(padding);
+ }
+
+ me.addCls(me.formItemCls);
+
+ // Prevent first render of active error, at Field render time from signalling a change from undefined to "
+ me.lastActiveError = '';
+
+ me.addEvents(
+ /**
+ * @event errorchange
+ * Fires when the active error message is changed via {@link #setActiveError}.
+ * @param {Ext.form.Labelable} this
+ * @param {String} error The active error message
+ */
+ 'errorchange'
+ );
+ },
+
+ /**
+ * Returns the trimmed label by slicing off the label separator character. Can be overridden.
+ * @return {String} The trimmed field label, or empty string if not defined
+ */
+ trimLabelSeparator: function() {
+ var me = this,
+ separator = me.labelSeparator,
+ label = me.fieldLabel || '',
+ lastChar = label.substr(label.length - 1);
+
+ // if the last char is the same as the label separator then slice it off otherwise just return label value
+ return lastChar === separator ? label.slice(0, -1) : label;
+ },
+
+ /**
+ * Returns the label for the field. Defaults to simply returning the {@link #fieldLabel} config. Can be overridden
+ * to provide a custom generated label.
+ * @template
+ * @return {String} The configured field label, or empty string if not defined
+ */
+ getFieldLabel: function() {
+ return this.trimLabelSeparator();
+ },
+
+ /**
+ * Set the label of this field.
+ * @param {String} label The new label. The {@link #labelSeparator} will be automatically appended to the label
+ * string.
+ */
+ setFieldLabel: function(label){
+ label = label || '';
+
+ var me = this,
+ separator = me.labelSeparator,
+ labelEl = me.labelEl;
+
+ me.fieldLabel = label;
+ if (me.rendered) {
+ if (Ext.isEmpty(label) && me.hideEmptyLabel) {
+ labelEl.parent().setDisplayed('none');
+ } else {
+ if (separator) {
+ label = me.trimLabelSeparator() + separator;
+ }
+ labelEl.update(label);
+ labelEl.parent().setDisplayed('');
+ }
+ me.updateLayout();
+ }
+ },
+
+ getInsertionRenderData: function (data, names) {
+ var i = names.length,
+ name, value;
+
+ while (i--) {
+ name = names[i];
+ value = this[name];
+
+ if (value) {
+ if (typeof value != 'string') {
+ if (!value.isTemplate) {
+ value = Ext.XTemplate.getTpl(this, name);
+ }
+ value = value.apply(data);
+ }
+ }
+
+ data[name] = value || '';
+ }
+
+ return data;
+ },
+
+ /**
+ * Generates the arguments for the field decorations {@link #labelableRenderTpl rendering template}.
+ * @return {Object} The template arguments
+ * @protected
+ */
+ getLabelableRenderData: function() {
+ var me = this,
+ data,
+ tempEl,
+ topLabel = me.labelAlign === 'top';
+
+ if (!Ext.form.Labelable.errorIconWidth) {
+ Ext.form.Labelable.errorIconWidth = (tempEl = Ext.resetElement.createChild({style: 'position:absolute', cls: Ext.baseCSSPrefix + 'form-invalid-icon'})).getWidth();
+ tempEl.remove();
+ }
+
+ data = Ext.copyTo({
+ inFormLayout : me.ownerLayout && me.ownerLayout.type === 'form',
+ inputId : me.getInputId(),
+ labelOnLeft : !topLabel,
+ hideLabel : !me.hasVisibleLabel(),
+ fieldLabel : me.getFieldLabel(),
+ labelCellStyle : me.getLabelCellStyle(),
+ labelCellAttrs : me.getLabelCellAttrs(),
+ labelCls : me.getLabelCls(),
+ labelStyle : me.getLabelStyle(),
+ bodyColspan : me.getBodyColspan(),
+ externalError : !me.autoFitErrors,
+ errorMsgCls : me.getErrorMsgCls(),
+ errorIconWidth : Ext.form.Labelable.errorIconWidth
+ },
+ me, me.labelableRenderProps, true);
+
+ me.getInsertionRenderData(data, me.labelableInsertions);
+
+ return data;
+ },
+
+ beforeLabelableRender: function() {
+ var me = this;
+ if (me.ownerLayout) {
+ me.addCls(Ext.baseCSSPrefix + me.ownerLayout.type + '-form-item');
+ }
+ },
+
+ onLabelableRender: function() {
+ var me = this,
+ margins,
+ side,
+ style = {};
+
+ if (me.extraMargins) {
+ margins = me.el.getMargin();
+ for (side in margins) {
+ if (margins.hasOwnProperty(side)) {
+ style['margin-' + side] = (margins[side] + me.extraMargins[side]) + 'px';
+ }
+ }
+ me.el.setStyle(style);
+ }
+ },
+
+ /**
+ * Checks if the field has a visible label
+ * @return {Boolean} True if the field has a visible label
+ */
+ hasVisibleLabel: function(){
+ if (this.hideLabel) {
+ return false;
+ }
+ return !(this.hideEmptyLabel && !this.getFieldLabel());
+ },
+
+ /**
+ * @private
+ * Calculates the colspan value for the body cell - the cell which contains the input field.
+ *
+ * The field table structure contains 4 columns:
+ */
+ getBodyColspan: function() {
+ var me = this,
+ result;
+
+ if (me.msgTarget === 'side' && (!me.autoFitErrors || me.hasActiveError())) {
+ result = 1;
+ } else {
+ result = 2;
+ }
+ if (me.labelAlign !== 'top' && !me.hasVisibleLabel()) {
+ result++;
+ }
+ return result;
+ },
+
+ getLabelCls: function() {
+ var labelCls = this.labelCls,
+ labelClsExtra = this.labelClsExtra;
+
+ if (this.labelAlign === 'top') {
+ labelCls += '-top';
+ }
+ return labelClsExtra ? labelCls + ' ' + labelClsExtra : labelCls;
+ },
+
+ getLabelCellStyle: function() {
+ var me = this,
+ hideLabelCell = me.hideLabel || (!me.fieldLabel && me.hideEmptyLabel);
+
+ return hideLabelCell ? 'display:none;' : '';
+ },
+
+ getErrorMsgCls: function() {
+ var me = this,
+ hideLabelCell = (me.hideLabel || (!me.fieldLabel && me.hideEmptyLabel));
+
+ return me.errorMsgCls + (!hideLabelCell && me.labelAlign === 'top' ? ' ' + Ext.baseCSSPrefix + 'lbl-top-err-icon' : '');
+ },
+
+ getLabelCellAttrs: function() {
+ var me = this,
+ labelAlign = me.labelAlign,
+ result = '';
+
+ if (labelAlign !== 'top') {
+ result = 'valign="top" halign="' + labelAlign + '" width="' + (me.labelWidth + me.labelPad) + '"';
+ }
+ return result + ' class="' + Ext.baseCSSPrefix + 'field-label-cell"';
+ },
+
+ /**
+ * Gets any label styling for the labelEl
+ * @private
+ * @return {String} The label styling
+ */
+ getLabelStyle: function(){
+ var me = this,
+ labelPad = me.labelPad,
+ labelStyle = '';
+
+ // Calculate label styles up front rather than in the Field layout for speed; this
+ // is safe because label alignment/width/pad are not expected to change.
+ if (me.labelAlign !== 'top') {
+ if (me.labelWidth) {
+ labelStyle = 'width:' + me.labelWidth + 'px;';
+ }
+ labelStyle += 'margin-right:' + labelPad + 'px;';
+ }
+
+ return labelStyle + (me.labelStyle || '');
+ },
+
+ /**
+ * Gets the markup to be inserted into the outer template's bodyEl. Defaults to empty string, should be implemented
+ * by classes including this mixin as needed.
+ * @return {String} The markup to be inserted
+ * @protected
+ */
+ getSubTplMarkup: function() {
+ return '';
+ },
+
+ /**
+ * Get the input id, if any, for this component. This is used as the "for" attribute on the label element.
+ * Implementing subclasses may also use this as e.g. the id for their own input element.
+ * @return {String} The input id
+ */
+ getInputId: function() {
+ return '';
+ },
+
+ /**
+ * Gets the active error message for this component, if any. This does not trigger validation on its own, it merely
+ * returns any message that the component may already hold.
+ * @return {String} The active error message on the component; if there is no error, an empty string is returned.
+ */
+ getActiveError : function() {
+ return this.activeError || '';
+ },
+
+ /**
+ * Tells whether the field currently has an active error message. This does not trigger validation on its own, it
+ * merely looks for any message that the component may already hold.
+ * @return {Boolean}
+ */
+ hasActiveError: function() {
+ return !!this.getActiveError();
+ },
+
+ /**
+ * Sets the active error message to the given string. This replaces the entire error message contents with the given
+ * string. Also see {@link #setActiveErrors} which accepts an Array of messages and formats them according to the
+ * {@link #activeErrorsTpl}. Note that this only updates the error message element's text and attributes, you'll
+ * have to call doComponentLayout to actually update the field's layout to match. If the field extends {@link
+ * Ext.form.field.Base} you should call {@link Ext.form.field.Base#markInvalid markInvalid} instead.
+ * @param {String} msg The error message
+ */
+ setActiveError: function(msg) {
+ this.setActiveErrors(msg);
+ },
+
+ /**
+ * Gets an Array of any active error messages currently applied to the field. This does not trigger validation on
+ * its own, it merely returns any messages that the component may already hold.
+ * @return {String[]} The active error messages on the component; if there are no errors, an empty Array is
+ * returned.
+ */
+ getActiveErrors: function() {
+ return this.activeErrors || [];
+ },
+
+ /**
+ * Set the active error message to an Array of error messages. The messages are formatted into a single message
+ * string using the {@link #activeErrorsTpl}. Also see {@link #setActiveError} which allows setting the entire error
+ * contents with a single string. Note that this only updates the error message element's text and attributes,
+ * you'll have to call doComponentLayout to actually update the field's layout to match. If the field extends
+ * {@link Ext.form.field.Base} you should call {@link Ext.form.field.Base#markInvalid markInvalid} instead.
+ * @param {String[]} errors The error messages
+ */
+ setActiveErrors: function(errors) {
+ errors = Ext.Array.from(errors);
+ this.activeError = errors[0];
+ this.activeErrors = errors;
+ this.activeError = this.getTpl('activeErrorsTpl').apply({errors: errors});
+ this.renderActiveError();
+ },
+
+ /**
+ * Clears the active error message(s). Note that this only clears the error message element's text and attributes,
+ * you'll have to call doComponentLayout to actually update the field's layout to match. If the field extends {@link
+ * Ext.form.field.Base} you should call {@link Ext.form.field.Base#clearInvalid clearInvalid} instead.
+ */
+ unsetActiveError: function() {
+ delete this.activeError;
+ delete this.activeErrors;
+ this.renderActiveError();
+ },
+
+ /**
+ * @private
+ * Updates the rendered DOM to match the current activeError. This only updates the content and
+ * attributes, you'll have to call doComponentLayout to actually update the display.
+ */
+ renderActiveError: function() {
+ var me = this,
+ activeError = me.getActiveError(),
+ hasError = !!activeError;
+
+ if (activeError !== me.lastActiveError) {
+ me.fireEvent('errorchange', me, activeError);
+ me.lastActiveError = activeError;
+ }
+
+ if (me.rendered && !me.isDestroyed && !me.preventMark) {
+ // Add/remove invalid class
+ me.el[hasError ? 'addCls' : 'removeCls'](me.invalidCls);
+
+ // Update the aria-invalid attribute
+ me.getActionEl().dom.setAttribute('aria-invalid', hasError);
+
+ // Update the errorEl (There will only be one if msgTarget is 'side' or 'under') with the error message text
+ if (me.errorEl) {
+ me.errorEl.dom.innerHTML = activeError;
+ }
+ }
+ },
+
+ /**
+ * Applies a set of default configuration values to this Labelable instance. For each of the properties in the given
+ * object, check if this component hasOwnProperty that config; if not then it's inheriting a default value from its
+ * prototype and we should apply the default value.
+ * @param {Object} defaults The defaults to apply to the object.
+ */
+ setFieldDefaults: function(defaults) {
+ var me = this,
+ val, key;
+
+ for (key in defaults) {
+ if (defaults.hasOwnProperty(key)) {
+ val = defaults[key];
+
+ if (!me.hasOwnProperty(key)) {
+ me[key] = val;
+ }
+ }
+ }
+ }
+});
+
+/**
+ * @docauthor Jason Johnston
+ *
+ * This mixin provides a common interface for the logical behavior and state of form fields, including:
+ *
+ * - Getter and setter methods for field values
+ * - Events and methods for tracking value and validity changes
+ * - Methods for triggering validation
+ *
+ * **NOTE**: When implementing custom fields, it is most likely that you will want to extend the {@link Ext.form.field.Base}
+ * component class rather than using this mixin directly, as BaseField contains additional logic for generating an
+ * actual DOM complete with {@link Ext.form.Labelable label and error message} display and a form input field,
+ * plus methods that bind the Field value getters and setters to the input field's value.
+ *
+ * If you do want to implement this mixin directly and don't want to extend {@link Ext.form.field.Base}, then
+ * you will most likely want to override the following methods with custom implementations: {@link #getValue},
+ * {@link #setValue}, and {@link #getErrors}. Other methods may be overridden as needed but their base
+ * implementations should be sufficient for common cases. You will also need to make sure that {@link #initField}
+ * is called during the component's initialization.
+ */
+Ext.define('Ext.form.field.Field', {
+ /**
+ * @property {Boolean} isFormField
+ * Flag denoting that this component is a Field. Always true.
+ */
+ isFormField : true,
+
+ /**
+ * @cfg {Object} value
+ * A value to initialize this field with.
+ */
+
+ /**
+ * @cfg {String} name
+ * The name of the field. By default this is used as the parameter name when including the
+ * {@link #getSubmitData field value} in a {@link Ext.form.Basic#submit form submit()}. To prevent the field from
+ * being included in the form submit, set {@link #submitValue} to false.
+ */
+
+ /**
+ * @cfg {Boolean} disabled
+ * True to disable the field. Disabled Fields will not be {@link Ext.form.Basic#submit submitted}.
+ */
+ disabled : false,
+
+ /**
+ * @cfg {Boolean} submitValue
+ * Setting this to false will prevent the field from being {@link Ext.form.Basic#submit submitted} even when it is
+ * not disabled.
+ */
+ submitValue: true,
+
+ /**
+ * @cfg {Boolean} validateOnChange
+ * Specifies whether this field should be validated immediately whenever a change in its value is detected.
+ * If the validation results in a change in the field's validity, a {@link #validitychange} event will be
+ * fired. This allows the field to show feedback about the validity of its contents immediately as the user is
+ * typing.
+ *
+ * When set to false, feedback will not be immediate. However the form will still be validated before submitting if
+ * the clientValidation option to {@link Ext.form.Basic#doAction} is enabled, or if the field or form are validated
+ * manually.
+ *
+ * See also {@link Ext.form.field.Base#checkChangeEvents} for controlling how changes to the field's value are
+ * detected.
+ */
+ validateOnChange: true,
+
+ /**
+ * @private
+ */
+ suspendCheckChange: 0,
+
+ /**
+ * Initializes this Field mixin on the current instance. Components using this mixin should call this method during
+ * their own initialization process.
+ */
+ initField: function() {
+ this.addEvents(
+ /**
+ * @event change
+ * Fires when the value of a field is changed via the {@link #setValue} method.
+ * @param {Ext.form.field.Field} this
+ * @param {Object} newValue The new value
+ * @param {Object} oldValue The original value
+ */
+ 'change',
+ /**
+ * @event validitychange
+ * Fires when a change in the field's validity is detected.
+ * @param {Ext.form.field.Field} this
+ * @param {Boolean} isValid Whether or not the field is now valid
+ */
+ 'validitychange',
+ /**
+ * @event dirtychange
+ * Fires when a change in the field's {@link #isDirty} state is detected.
+ * @param {Ext.form.field.Field} this
+ * @param {Boolean} isDirty Whether or not the field is now dirty
+ */
+ 'dirtychange'
+ );
+
+ this.initValue();
+ },
+
+ /**
+ * Initializes the field's value based on the initial config.
+ */
+ initValue: function() {
+ var me = this;
+
+ me.value = me.transformOriginalValue(me.value);
+ /**
+ * @property {Object} originalValue
+ * The original value of the field as configured in the {@link #value} configuration, or as loaded by the last
+ * form load operation if the form's {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad} setting is `true`.
+ */
+ me.originalValue = me.lastValue = me.value;
+
+ // Set the initial value - prevent validation on initial set
+ me.suspendCheckChange++;
+ me.setValue(me.value);
+ me.suspendCheckChange--;
+ },
+
+ /**
+ * Allows for any necessary modifications before the original
+ * value is set
+ * @protected
+ * @param {Object} value The initial value
+ * @return {Object} The modified initial value
+ */
+ transformOriginalValue: function(value){
+ return value;
+ },
+
+ /**
+ * Returns the {@link Ext.form.field.Field#name name} attribute of the field. This is used as the parameter name
+ * when including the field value in a {@link Ext.form.Basic#submit form submit()}.
+ * @return {String} name The field {@link Ext.form.field.Field#name name}
+ */
+ getName: function() {
+ return this.name;
+ },
+
+ /**
+ * Returns the current data value of the field. The type of value returned is particular to the type of the
+ * particular field (e.g. a Date object for {@link Ext.form.field.Date}).
+ * @return {Object} value The field value
+ */
+ getValue: function() {
+ return this.value;
+ },
+
+ /**
+ * Sets a data value into the field and runs the change detection and validation.
+ * @param {Object} value The value to set
+ * @return {Ext.form.field.Field} this
+ */
+ setValue: function(value) {
+ var me = this;
+ me.value = value;
+ me.checkChange();
+ return me;
+ },
+
+ /**
+ * Returns whether two field {@link #getValue values} are logically equal. Field implementations may override this
+ * to provide custom comparison logic appropriate for the particular field's data type.
+ * @param {Object} value1 The first value to compare
+ * @param {Object} value2 The second value to compare
+ * @return {Boolean} True if the values are equal, false if inequal.
+ */
+ isEqual: function(value1, value2) {
+ return String(value1) === String(value2);
+ },
+
+ /**
+ * Returns whether two values are logically equal.
+ * Similar to {@link #isEqual}, however null or undefined values will be treated as empty strings.
+ * @private
+ * @param {Object} value1 The first value to compare
+ * @param {Object} value2 The second value to compare
+ * @return {Boolean} True if the values are equal, false if inequal.
+ */
+ isEqualAsString: function(value1, value2){
+ return String(Ext.value(value1, '')) === String(Ext.value(value2, ''));
+ },
+
+ /**
+ * Returns the parameter(s) that would be included in a standard form submit for this field. Typically this will be
+ * an object with a single name-value pair, the name being this field's {@link #getName name} and the value being
+ * its current stringified value. More advanced field implementations may return more than one name-value pair.
+ *
+ * Note that the values returned from this method are not guaranteed to have been successfully {@link #validate
+ * validated}.
+ *
+ * @return {Object} A mapping of submit parameter names to values; each value should be a string, or an array of
+ * strings if that particular name has multiple values. It can also return null if there are no parameters to be
+ * submitted.
+ */
+ getSubmitData: function() {
+ var me = this,
+ data = null;
+ if (!me.disabled && me.submitValue && !me.isFileUpload()) {
+ data = {};
+ data[me.getName()] = '' + me.getValue();
+ }
+ return data;
+ },
+
+ /**
+ * Returns the value(s) that should be saved to the {@link Ext.data.Model} instance for this field, when {@link
+ * Ext.form.Basic#updateRecord} is called. Typically this will be an object with a single name-value pair, the name
+ * being this field's {@link #getName name} and the value being its current data value. More advanced field
+ * implementations may return more than one name-value pair. The returned values will be saved to the corresponding
+ * field names in the Model.
+ *
+ * Note that the values returned from this method are not guaranteed to have been successfully {@link #validate
+ * validated}.
+ *
+ * @return {Object} A mapping of submit parameter names to values; each value should be a string, or an array of
+ * strings if that particular name has multiple values. It can also return null if there are no parameters to be
+ * submitted.
+ */
+ getModelData: function() {
+ var me = this,
+ data = null;
+ if (!me.disabled && !me.isFileUpload()) {
+ data = {};
+ data[me.getName()] = me.getValue();
+ }
+ return data;
+ },
+
+ /**
+ * Resets the current field value to the originally loaded value and clears any validation messages. See {@link
+ * Ext.form.Basic}.{@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}
+ */
+ reset : function(){
+ var me = this;
+
+ me.beforeReset();
+ me.setValue(me.originalValue);
+ me.clearInvalid();
+ // delete here so we reset back to the original state
+ delete me.wasValid;
+ },
+
+ /**
+ * Template method before a field is reset.
+ * @protected
+ */
+ beforeReset: Ext.emptyFn,
+
+ /**
+ * Resets the field's {@link #originalValue} property so it matches the current {@link #getValue value}. This is
+ * called by {@link Ext.form.Basic}.{@link Ext.form.Basic#setValues setValues} if the form's
+ * {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad} property is set to true.
+ */
+ resetOriginalValue: function() {
+ this.originalValue = this.getValue();
+ this.checkDirty();
+ },
+
+ /**
+ * Checks whether the value of the field has changed since the last time it was checked.
+ * If the value has changed, it:
+ *
+ * 1. Fires the {@link #change change event},
+ * 2. Performs validation if the {@link #validateOnChange} config is enabled, firing the
+ * {@link #validitychange validitychange event} if the validity has changed, and
+ * 3. Checks the {@link #isDirty dirty state} of the field and fires the {@link #dirtychange dirtychange event}
+ * if it has changed.
+ */
+ checkChange: function() {
+ if (!this.suspendCheckChange) {
+ var me = this,
+ newVal = me.getValue(),
+ oldVal = me.lastValue;
+ if (!me.isEqual(newVal, oldVal) && !me.isDestroyed) {
+ me.lastValue = newVal;
+ me.fireEvent('change', me, newVal, oldVal);
+ me.onChange(newVal, oldVal);
+ }
+ }
+ },
+
+ /**
+ * @private
+ * Called when the field's value changes. Performs validation if the {@link #validateOnChange}
+ * config is enabled, and invokes the dirty check.
+ */
+ onChange: function(newVal, oldVal) {
+ if (this.validateOnChange) {
+ this.validate();
+ }
+ this.checkDirty();
+ },
+
+ /**
+ * Returns true if the value of this Field has been changed from its {@link #originalValue}.
+ * Will always return false if the field is disabled.
+ *
+ * Note that if the owning {@link Ext.form.Basic form} was configured with
+ * {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad} then the {@link #originalValue} is updated when
+ * the values are loaded by {@link Ext.form.Basic}.{@link Ext.form.Basic#setValues setValues}.
+ * @return {Boolean} True if this field has been changed from its original value (and is not disabled),
+ * false otherwise.
+ */
+ isDirty : function() {
+ var me = this;
+ return !me.disabled && !me.isEqual(me.getValue(), me.originalValue);
+ },
+
+ /**
+ * Checks the {@link #isDirty} state of the field and if it has changed since the last time it was checked,
+ * fires the {@link #dirtychange} event.
+ */
+ checkDirty: function() {
+ var me = this,
+ isDirty = me.isDirty();
+ if (isDirty !== me.wasDirty) {
+ me.fireEvent('dirtychange', me, isDirty);
+ me.onDirtyChange(isDirty);
+ me.wasDirty = isDirty;
+ }
+ },
+
+ /**
+ * @private Called when the field's dirty state changes.
+ * @param {Boolean} isDirty
+ */
+ onDirtyChange: Ext.emptyFn,
+
+ /**
+ * Runs this field's validators and returns an array of error messages for any validation failures. This is called
+ * internally during validation and would not usually need to be used manually.
+ *
+ * Each subclass should override or augment the return value to provide their own errors.
+ *
+ * @param {Object} value The value to get errors for (defaults to the current field value)
+ * @return {String[]} All error messages for this field; an empty Array if none.
+ */
+ getErrors: function(value) {
+ return [];
+ },
+
+ /**
+ * Returns whether or not the field value is currently valid by {@link #getErrors validating} the field's current
+ * value. The {@link #validitychange} event will not be fired; use {@link #validate} instead if you want the event
+ * to fire. **Note**: {@link #disabled} fields are always treated as valid.
+ *
+ * Implementations are encouraged to ensure that this method does not have side-effects such as triggering error
+ * message display.
+ *
+ * @return {Boolean} True if the value is valid, else false
+ */
+ isValid : function() {
+ var me = this;
+ return me.disabled || Ext.isEmpty(me.getErrors());
+ },
+
+ /**
+ * Returns whether or not the field value is currently valid by {@link #getErrors validating} the field's current
+ * value, and fires the {@link #validitychange} event if the field's validity has changed since the last validation.
+ * **Note**: {@link #disabled} fields are always treated as valid.
+ *
+ * Custom implementations of this method are allowed to have side-effects such as triggering error message display.
+ * To validate without side-effects, use {@link #isValid}.
+ *
+ * @return {Boolean} True if the value is valid, else false
+ */
+ validate : function() {
+ var me = this,
+ isValid = me.isValid();
+ if (isValid !== me.wasValid) {
+ me.wasValid = isValid;
+ me.fireEvent('validitychange', me, isValid);
+ }
+ return isValid;
+ },
+
+ /**
+ * A utility for grouping a set of modifications which may trigger value changes into a single transaction, to
+ * prevent excessive firing of {@link #change} events. This is useful for instance if the field has sub-fields which
+ * are being updated as a group; you don't want the container field to check its own changed state for each subfield
+ * change.
+ * @param {Object} fn A function containing the transaction code
+ */
+ batchChanges: function(fn) {
+ try {
+ this.suspendCheckChange++;
+ fn();
+ } catch(e){
+ throw e;
+ } finally {
+ this.suspendCheckChange--;
+ }
+ this.checkChange();
+ },
+
+ /**
+ * Returns whether this Field is a file upload field; if it returns true, forms will use special techniques for
+ * {@link Ext.form.Basic#submit submitting the form} via AJAX. See {@link Ext.form.Basic#hasUpload} for details. If
+ * this returns true, the {@link #extractFileInput} method must also be implemented to return the corresponding file
+ * input element.
+ * @return {Boolean}
+ */
+ isFileUpload: function() {
+ return false;
+ },
+
+ /**
+ * Only relevant if the instance's {@link #isFileUpload} method returns true. Returns a reference to the file input
+ * DOM element holding the user's selected file. The input will be appended into the submission form and will not be
+ * returned, so this method should also create a replacement.
+ * @return {HTMLElement}
+ */
+ extractFileInput: function() {
+ return null;
+ },
+
+ /**
+ * @method markInvalid
+ * Associate one or more error messages with this field. Components using this mixin should implement this method to
+ * update the component's rendering to display the messages.
+ *
+ * **Note**: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to return `false`
+ * if the value does _pass_ validation. So simply marking a Field as invalid will not prevent submission of forms
+ * submitted with the {@link Ext.form.action.Submit#clientValidation} option set.
+ *
+ * @param {String/String[]} errors The error message(s) for the field.
+ */
+ markInvalid: Ext.emptyFn,
+
+ /**
+ * @method clearInvalid
+ * Clear any invalid styles/messages for this field. Components using this mixin should implement this method to
+ * update the components rendering to clear any existing messages.
+ *
+ * **Note**: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to return `true`
+ * if the value does not _pass_ validation. So simply clearing a field's errors will not necessarily allow
+ * submission of forms submitted with the {@link Ext.form.action.Submit#clientValidation} option set.
+ */
+ clearInvalid: Ext.emptyFn
+
+});
+
+/**
+ * @docauthor Jason Johnston
+ *
+ * Base class for form fields that provides default event handling, rendering, and other common functionality
+ * needed by all form field types. Utilizes the {@link Ext.form.field.Field} mixin for value handling and validation,
+ * and the {@link Ext.form.Labelable} mixin to provide label and error message display.
+ *
+ * In most cases you will want to use a subclass, such as {@link Ext.form.field.Text} or {@link Ext.form.field.Checkbox},
+ * rather than creating instances of this class directly. However if you are implementing a custom form field,
+ * using this as the parent class is recommended.
+ *
+ * # Values and Conversions
+ *
+ * Because Base implements the Field mixin, it has a main value that can be initialized with the
+ * {@link #value} config and manipulated via the {@link #getValue} and {@link #setValue} methods. This main
+ * value can be one of many data types appropriate to the current field, for instance a {@link Ext.form.field.Date Date}
+ * field would use a JavaScript Date object as its value type. However, because the field is rendered as a HTML
+ * input, this value data type can not always be directly used in the rendered field.
+ *
+ * Therefore Base introduces the concept of a "raw value". This is the value of the rendered HTML input field,
+ * and is normally a String. The {@link #getRawValue} and {@link #setRawValue} methods can be used to directly
+ * work with the raw value, though it is recommended to use getValue and setValue in most cases.
+ *
+ * Conversion back and forth between the main value and the raw value is handled by the {@link #valueToRaw} and
+ * {@link #rawToValue} methods. If you are implementing a subclass that uses a non-String value data type, you
+ * should override these methods to handle the conversion.
+ *
+ * # Rendering
+ *
+ * The content of the field body is defined by the {@link #fieldSubTpl} XTemplate, with its argument data
+ * created by the {@link #getSubTplData} method. Override this template and/or method to create custom
+ * field renderings.
+ *
+ * # Example usage:
+ *
+ * @example
+ * // A simple subclass of Base that creates a HTML5 search field. Redirects to the
+ * // searchUrl when the Enter key is pressed.222
+ * Ext.define('Ext.form.SearchField', {
+ * extend: 'Ext.form.field.Base',
+ * alias: 'widget.searchfield',
+ *
+ * inputType: 'search',
+ *
+ * // Config defining the search URL
+ * searchUrl: 'http://www.google.com/search?q={0}',
+ *
+ * // Add specialkey listener
+ * initComponent: function() {
+ * this.callParent();
+ * this.on('specialkey', this.checkEnterKey, this);
+ * },
+ *
+ * // Handle enter key presses, execute the search if the field has a value
+ * checkEnterKey: function(field, e) {
+ * var value = this.getValue();
+ * if (e.getKey() === e.ENTER && !Ext.isEmpty(value)) {
+ * location.href = Ext.String.format(this.searchUrl, value);
+ * }
+ * }
+ * });
+ *
+ * Ext.create('Ext.form.Panel', {
+ * title: 'Base Example',
+ * bodyPadding: 5,
+ * width: 250,
+ *
+ * // Fields will be arranged vertically, stretched to full width
+ * layout: 'anchor',
+ * defaults: {
+ * anchor: '100%'
+ * },
+ * items: [{
+ * xtype: 'searchfield',
+ * fieldLabel: 'Search',
+ * name: 'query'
+ * }],
+ * renderTo: Ext.getBody()
+ * });
+ */
+Ext.define('Ext.form.field.Base', {
+ extend: 'Ext.Component',
+ mixins: {
+ labelable: 'Ext.form.Labelable',
+ field: 'Ext.form.field.Field'
+ },
+ alias: 'widget.field',
+ alternateClassName: ['Ext.form.Field', 'Ext.form.BaseField'],
+ requires: ['Ext.util.DelayedTask', 'Ext.XTemplate', 'Ext.layout.component.field.Field'],
+
+ /**
+ * @cfg {Ext.XTemplate} fieldSubTpl
+ * The content of the field body is defined by this config option.
+ * @private
+ */
+ fieldSubTpl: [ // note: {id} here is really {inputId}, but {cmpId} is available
+ ' name="{name}"',
+ ' value="{[Ext.util.Format.htmlEncode(values.value)]}" ',
+ ' placeholder="{placeholder}" ',
+ '{%if (values.maxLength !== undefined){%} maxlength="{maxLength}"{%}%}',
+ ' readonly="readonly" ',
+ ' disabled="disabled" ',
+ ' tabIndex="{tabIdx}" ',
+ ' style="{fieldStyle}" ',
+ ' class="{fieldCls} {typeCls} {editableCls}" autocomplete="off"/>',
+ {
+ disableFormats: true
+ }
+ ],
+
+ subTplInsertions: [
+ /**
+ * @cfg {String/Array/Ext.XTemplate} inputAttrTpl
+ * An optional string or `XTemplate` configuration to insert in the field markup
+ * inside the input element (as attributes). If an `XTemplate` is used, the component's
+ * {@link #getSubTplData subTpl data} serves as the context.
+ */
+ 'inputAttrTpl'
+ ],
+
+ /**
+ * @cfg {String} name
+ * The name of the field. This is used as the parameter name when including the field value
+ * in a {@link Ext.form.Basic#submit form submit()}. If no name is configured, it falls back to the {@link #inputId}.
+ * To prevent the field from being included in the form submit, set {@link #submitValue} to false.
+ */
+
+ /**
+ * @cfg {String} inputType
+ * The type attribute for input fields -- e.g. radio, text, password, file. The extended types
+ * supported by HTML5 inputs (url, email, etc.) may also be used, though using them will cause older browsers to
+ * fall back to 'text'.
+ *
+ * The type 'password' must be used to render that field type currently -- there is no separate Ext component for
+ * that. You can use {@link Ext.form.field.File} which creates a custom-rendered file upload field, but if you want
+ * a plain unstyled file input you can use a Base with inputType:'file'.
+ */
+ inputType: 'text',
+
+ /**
+ * @cfg {Number} tabIndex
+ * The tabIndex for this field. Note this only applies to fields that are rendered, not those which are built via
+ * applyTo
+ */
+
+ //
+ /**
+ * @cfg {String} invalidText
+ * The error text to use when marking a field invalid and no message is provided
+ */
+ invalidText : 'The value in this field is invalid',
+ //
+
+ /**
+ * @cfg {String} [fieldCls='x-form-field']
+ * The default CSS class for the field input
+ */
+ fieldCls : Ext.baseCSSPrefix + 'form-field',
+
+ /**
+ * @cfg {String} fieldStyle
+ * Optional CSS style(s) to be applied to the {@link #inputEl field input element}. Should be a valid argument to
+ * {@link Ext.Element#applyStyles}. Defaults to undefined. See also the {@link #setFieldStyle} method for changing
+ * the style after initialization.
+ */
+
+ /**
+ * @cfg {String} [focusCls='x-form-focus']
+ * The CSS class to use when the field receives focus
+ */
+ focusCls : 'form-focus',
+
+ /**
+ * @cfg {String} dirtyCls
+ * The CSS class to use when the field value {@link #isDirty is dirty}.
+ */
+ dirtyCls : Ext.baseCSSPrefix + 'form-dirty',
+
+ /**
+ * @cfg {String[]} checkChangeEvents
+ * A list of event names that will be listened for on the field's {@link #inputEl input element}, which will cause
+ * the field's value to be checked for changes. If a change is detected, the {@link #change change event} will be
+ * fired, followed by validation if the {@link #validateOnChange} option is enabled.
+ *
+ * Defaults to ['change', 'propertychange'] in Internet Explorer, and ['change', 'input', 'textInput', 'keyup',
+ * 'dragdrop'] in other browsers. This catches all the ways that field values can be changed in most supported
+ * browsers; the only known exceptions at the time of writing are:
+ *
+ * - Safari 3.2 and older: cut/paste in textareas via the context menu, and dragging text into textareas
+ * - Opera 10 and 11: dragging text into text fields and textareas, and cut via the context menu in text fields
+ * and textareas
+ * - Opera 9: Same as Opera 10 and 11, plus paste from context menu in text fields and textareas
+ *
+ * If you need to guarantee on-the-fly change notifications including these edge cases, you can call the
+ * {@link #checkChange} method on a repeating interval, e.g. using {@link Ext.TaskManager}, or if the field is within
+ * a {@link Ext.form.Panel}, you can use the FormPanel's {@link Ext.form.Panel#pollForChanges} configuration to set up
+ * such a task automatically.
+ */
+ checkChangeEvents: Ext.isIE && (!document.documentMode || document.documentMode < 9) ?
+ ['change', 'propertychange'] :
+ ['change', 'input', 'textInput', 'keyup', 'dragdrop'],
+
+ /**
+ * @cfg {Number} checkChangeBuffer
+ * Defines a timeout in milliseconds for buffering {@link #checkChangeEvents} that fire in rapid succession.
+ * Defaults to 50 milliseconds.
+ */
+ checkChangeBuffer: 50,
+
+ componentLayout: 'field',
+
+ /**
+ * @cfg {Boolean} readOnly
+ * true to mark the field as readOnly in HTML.
+ *
+ * **Note**: this only sets the element's readOnly DOM attribute. Setting `readOnly=true`, for example, will not
+ * disable triggering a ComboBox or Date; it gives you the option of forcing the user to choose via the trigger
+ * without typing in the text box. To hide the trigger use `{@link Ext.form.field.Trigger#hideTrigger hideTrigger}`.
+ */
+ readOnly : false,
+
+ /**
+ * @cfg {String} readOnlyCls
+ * The CSS class applied to the component's main element when it is {@link #readOnly}.
+ */
+ readOnlyCls: Ext.baseCSSPrefix + 'form-readonly',
+
+ /**
+ * @cfg {String} inputId
+ * The id that will be given to the generated input DOM element. Defaults to an automatically generated id. If you
+ * configure this manually, you must make sure it is unique in the document.
+ */
+
+ /**
+ * @cfg {Boolean} validateOnBlur
+ * Whether the field should validate when it loses focus. This will cause fields to be validated
+ * as the user steps through the fields in the form regardless of whether they are making changes to those fields
+ * along the way. See also {@link #validateOnChange}.
+ */
+ validateOnBlur: true,
+
+ // private
+ hasFocus : false,
+
+ baseCls: Ext.baseCSSPrefix + 'field',
+
+ maskOnDisable: false,
+
+ // private
+ initComponent : function() {
+ var me = this;
+
+ me.callParent();
+
+ me.subTplData = me.subTplData || {};
+
+ me.addEvents(
+ /**
+ * @event specialkey
+ * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. To handle other keys
+ * see {@link Ext.util.KeyMap}. You can check {@link Ext.EventObject#getKey} to determine which key was
+ * pressed. For example:
+ *
+ * var form = new Ext.form.Panel({
+ * ...
+ * items: [{
+ * fieldLabel: 'Field 1',
+ * name: 'field1',
+ * allowBlank: false
+ * },{
+ * fieldLabel: 'Field 2',
+ * name: 'field2',
+ * listeners: {
+ * specialkey: function(field, e){
+ * // e.HOME, e.END, e.PAGE_UP, e.PAGE_DOWN,
+ * // e.TAB, e.ESC, arrow keys: e.LEFT, e.RIGHT, e.UP, e.DOWN
+ * if (e.{@link Ext.EventObject#getKey getKey()} == e.ENTER) {
+ * var form = field.up('form').getForm();
+ * form.submit();
+ * }
+ * }
+ * }
+ * }
+ * ],
+ * ...
+ * });
+ *
+ * @param {Ext.form.field.Base} this
+ * @param {Ext.EventObject} e The event object
+ */
+ 'specialkey',
+
+ /**
+ * @event writeablechange
+ * Fires when this field changes its read-only status.
+ * @param {Ext.form.field.Base} this
+ * @param {Boolean} Read only flag
+ */
+ 'writeablechange'
+ );
+
+ // Init mixins
+ me.initLabelable();
+ me.initField();
+
+ // Default name to inputId
+ if (!me.name) {
+ me.name = me.getInputId();
+ }
+ },
+
+ beforeRender: function(){
+ var me = this;
+
+ me.callParent(arguments);
+ me.beforeLabelableRender(arguments);
+ if (me.readOnly) {
+ me.addCls(me.readOnlyCls);
+ }
+ },
+
+ /**
+ * Returns the input id for this field. If none was specified via the {@link #inputId} config, then an id will be
+ * automatically generated.
+ */
+ getInputId: function() {
+ return this.inputId || (this.inputId = this.id + '-inputEl');
+ },
+
+ /**
+ * Creates and returns the data object to be used when rendering the {@link #fieldSubTpl}.
+ * @return {Object} The template data
+ * @template
+ */
+ getSubTplData: function() {
+ var me = this,
+ type = me.inputType,
+ inputId = me.getInputId(),
+ data;
+
+ data = Ext.apply({
+ id : inputId,
+ cmpId : me.id,
+ name : me.name || inputId,
+ disabled : me.disabled,
+ readOnly : me.readOnly,
+ value : me.getRawValue(),
+ type : type,
+ fieldCls : me.fieldCls,
+ fieldStyle : me.getFieldStyle(),
+ tabIdx : me.tabIndex,
+ typeCls : Ext.baseCSSPrefix + 'form-' + (type === 'password' ? 'text' : type)
+ }, me.subTplData);
+
+ me.getInsertionRenderData(data, me.subTplInsertions);
+
+ return data;
+ },
+
+ afterFirstLayout: function() {
+ this.callParent();
+ var el = this.inputEl;
+ if (el) {
+ el.selectable();
+ }
+ },
+
+ applyRenderSelectors: function() {
+ var me = this;
+
+ me.callParent();
+
+ /**
+ * @property {Ext.Element} inputEl
+ * The input Element for this Field. Only available after the field has been rendered.
+ */
+ me.inputEl = me.el.getById(me.getInputId());
+ },
+
+ /**
+ * Gets the markup to be inserted into the outer template's bodyEl. For fields this is the actual input element.
+ */
+ getSubTplMarkup: function() {
+ return this.getTpl('fieldSubTpl').apply(this.getSubTplData());
+ },
+
+ initRenderTpl: function() {
+ var me = this;
+ if (!me.hasOwnProperty('renderTpl')) {
+ me.renderTpl = me.getTpl('labelableRenderTpl');
+ }
+ return me.callParent();
+ },
+
+ initRenderData: function() {
+ return Ext.applyIf(this.callParent(), this.getLabelableRenderData());
+ },
+
+ /**
+ * Set the {@link #fieldStyle CSS style} of the {@link #inputEl field input element}.
+ * @param {String/Object/Function} style The style(s) to apply. Should be a valid argument to {@link
+ * Ext.Element#applyStyles}.
+ */
+ setFieldStyle: function(style) {
+ var me = this,
+ inputEl = me.inputEl;
+ if (inputEl) {
+ inputEl.applyStyles(style);
+ }
+ me.fieldStyle = style;
+ },
+
+ getFieldStyle: function() {
+ return 'width:100%;' + (Ext.isObject(this.fieldStyle) ? Ext.DomHelper.generateStyles(this.fieldStyle) : this.fieldStyle ||'');
+ },
+
+ // private
+ onRender : function() {
+ var me = this;
+ me.callParent(arguments);
+ me.onLabelableRender();
+ me.renderActiveError();
+ },
+
+ getFocusEl: function() {
+ return this.inputEl;
+ },
+
+ isFileUpload: function() {
+ return this.inputType === 'file';
+ },
+
+ extractFileInput: function() {
+ var me = this,
+ fileInput = me.isFileUpload() ? me.inputEl.dom : null,
+ clone;
+ if (fileInput) {
+ clone = fileInput.cloneNode(true);
+ fileInput.parentNode.replaceChild(clone, fileInput);
+ me.inputEl = Ext.get(clone);
+ }
+ return fileInput;
+ },
+
+ // private override to use getSubmitValue() as a convenience
+ getSubmitData: function() {
+ var me = this,
+ data = null,
+ val;
+ if (!me.disabled && me.submitValue && !me.isFileUpload()) {
+ val = me.getSubmitValue();
+ if (val !== null) {
+ data = {};
+ data[me.getName()] = val;
+ }
+ }
+ return data;
+ },
+
+ /**
+ * Returns the value that would be included in a standard form submit for this field. This will be combined with the
+ * field's name to form a name=value pair in the {@link #getSubmitData submitted parameters}. If an empty string is
+ * returned then just the name= will be submitted; if null is returned then nothing will be submitted.
+ *
+ * Note that the value returned will have been {@link #processRawValue processed} but may or may not have been
+ * successfully {@link #validate validated}.
+ *
+ * @return {String} The value to be submitted, or null.
+ */
+ getSubmitValue: function() {
+ return this.processRawValue(this.getRawValue());
+ },
+
+ /**
+ * Returns the raw value of the field, without performing any normalization, conversion, or validation. To get a
+ * normalized and converted value see {@link #getValue}.
+ * @return {String} value The raw String value of the field
+ */
+ getRawValue: function() {
+ var me = this,
+ v = (me.inputEl ? me.inputEl.getValue() : Ext.value(me.rawValue, ''));
+ me.rawValue = v;
+ return v;
+ },
+
+ /**
+ * Sets the field's raw value directly, bypassing {@link #valueToRaw value conversion}, change detection, and
+ * validation. To set the value with these additional inspections see {@link #setValue}.
+ * @param {Object} value The value to set
+ * @return {Object} value The field value that is set
+ */
+ setRawValue: function(value) {
+ var me = this;
+ value = Ext.value(me.transformRawValue(value), '');
+ me.rawValue = value;
+
+ // Some Field subclasses may not render an inputEl
+ if (me.inputEl) {
+ me.inputEl.dom.value = value;
+ }
+ return value;
+ },
+
+ /**
+ * Transform the raw value before it is set
+ * @protected
+ * @param {Object} value The value
+ * @return {Object} The value to set
+ */
+ transformRawValue: function(value) {
+ return value;
+ },
+
+ /**
+ * Converts a mixed-type value to a raw representation suitable for displaying in the field. This allows controlling
+ * how value objects passed to {@link #setValue} are shown to the user, including localization. For instance, for a
+ * {@link Ext.form.field.Date}, this would control how a Date object passed to {@link #setValue} would be converted
+ * to a String for display in the field.
+ *
+ * See {@link #rawToValue} for the opposite conversion.
+ *
+ * The base implementation simply does a standard toString conversion, and converts {@link Ext#isEmpty empty values}
+ * to an empty string.
+ *
+ * @param {Object} value The mixed-type value to convert to the raw representation.
+ * @return {Object} The converted raw value.
+ */
+ valueToRaw: function(value) {
+ return '' + Ext.value(value, '');
+ },
+
+ /**
+ * Converts a raw input field value into a mixed-type value that is suitable for this particular field type. This
+ * allows controlling the normalization and conversion of user-entered values into field-type-appropriate values,
+ * e.g. a Date object for {@link Ext.form.field.Date}, and is invoked by {@link #getValue}.
+ *
+ * It is up to individual implementations to decide how to handle raw values that cannot be successfully converted
+ * to the desired object type.
+ *
+ * See {@link #valueToRaw} for the opposite conversion.
+ *
+ * The base implementation does no conversion, returning the raw value untouched.
+ *
+ * @param {Object} rawValue
+ * @return {Object} The converted value.
+ */
+ rawToValue: function(rawValue) {
+ return rawValue;
+ },
+
+ /**
+ * Performs any necessary manipulation of a raw field value to prepare it for {@link #rawToValue conversion} and/or
+ * {@link #validate validation}, for instance stripping out ignored characters. In the base implementation it does
+ * nothing; individual subclasses may override this as needed.
+ *
+ * @param {Object} value The unprocessed string value
+ * @return {Object} The processed string value
+ */
+ processRawValue: function(value) {
+ return value;
+ },
+
+ /**
+ * Returns the current data value of the field. The type of value returned is particular to the type of the
+ * particular field (e.g. a Date object for {@link Ext.form.field.Date}), as the result of calling {@link #rawToValue} on
+ * the field's {@link #processRawValue processed} String value. To return the raw String value, see {@link #getRawValue}.
+ * @return {Object} value The field value
+ */
+ getValue: function() {
+ var me = this,
+ val = me.rawToValue(me.processRawValue(me.getRawValue()));
+ me.value = val;
+ return val;
+ },
+
+ /**
+ * Sets a data value into the field and runs the change detection and validation. To set the value directly
+ * without these inspections see {@link #setRawValue}.
+ * @param {Object} value The value to set
+ * @return {Ext.form.field.Field} this
+ */
+ setValue: function(value) {
+ var me = this;
+ me.setRawValue(me.valueToRaw(value));
+ return me.mixins.field.setValue.call(me, value);
+ },
+
+ onBoxReady: function() {
+ var me = this;
+ me.callParent();
+
+ if (me.setReadOnlyOnBoxReady) {
+ me.setReadOnly(me.readOnly);
+ }
+
+ },
+
+ //private
+ onDisable: function() {
+ var me = this,
+ inputEl = me.inputEl;
+
+ me.callParent();
+ if (inputEl) {
+ inputEl.dom.disabled = true;
+ if (me.hasActiveError()) {
+ // clear invalid state since the field is now disabled
+ me.clearInvalid();
+ me.needsValidateOnEnable = true;
+ }
+ }
+ },
+
+ //private
+ onEnable: function() {
+ var me = this,
+ inputEl = me.inputEl;
+
+ me.callParent();
+ if (inputEl) {
+ inputEl.dom.disabled = false;
+ if (me.needsValidateOnEnable) {
+ delete me.needsValidateOnEnable;
+ // will trigger errors to be shown
+ me.forceValidation = true;
+ me.isValid();
+ delete me.forceValidation;
+ }
+ }
+ },
+
+ /**
+ * Sets the read only state of this field.
+ * @param {Boolean} readOnly Whether the field should be read only.
+ */
+ setReadOnly: function(readOnly) {
+ var me = this,
+ inputEl = me.inputEl;
+ readOnly = !!readOnly;
+ me[readOnly ? 'addCls' : 'removeCls'](me.readOnlyCls);
+ me.readOnly = readOnly;
+ if (inputEl) {
+ inputEl.dom.readOnly = readOnly;
+ } else if (me.rendering) {
+ me.setReadOnlyOnBoxReady = true;
+ }
+ me.fireEvent('writeablechange', me, readOnly);
+ },
+
+ // private
+ fireKey: function(e){
+ if(e.isSpecialKey()){
+ this.fireEvent('specialkey', this, new Ext.EventObjectImpl(e));
+ }
+ },
+
+ // private
+ initEvents : function(){
+ var me = this,
+ inputEl = me.inputEl,
+ onChangeTask,
+ onChangeEvent,
+ events = me.checkChangeEvents,
+ e,
+ eLen = events.length,
+ event;
+
+ // standardise buffer across all browsers + OS-es for consistent event order.
+ // (the 10ms buffer for Editors fixes a weird FF/Win editor issue when changing OS window focus)
+ if (me.inEditor) {
+ me.onBlur = Ext.Function.createBuffered(me.onBlur, 10);
+ }
+ if (inputEl) {
+ me.mon(inputEl, Ext.EventManager.getKeyEvent(), me.fireKey, me);
+
+ // listen for immediate value changes
+ onChangeTask = new Ext.util.DelayedTask(me.checkChange, me);
+ me.onChangeEvent = onChangeEvent = function() {
+ onChangeTask.delay(me.checkChangeBuffer);
+ };
+
+ for (e = 0; e < eLen; e++) {
+ event = events[e];
+
+ if (event === 'propertychange') {
+ me.usesPropertychange = true;
+ }
+
+ me.mon(inputEl, event, onChangeEvent);
+ }
+ }
+ me.callParent();
+ },
+
+ doComponentLayout: function() {
+ var me = this,
+ inputEl = me.inputEl,
+ usesPropertychange = me.usesPropertychange,
+ ename = 'propertychange',
+ onChangeEvent = me.onChangeEvent;
+
+ // In IE if propertychange is one of the checkChangeEvents, we need to remove
+ // the listener prior to layout and re-add it after, to prevent it from firing
+ // needlessly for attribute and style changes applied to the inputEl.
+ if (usesPropertychange) {
+ me.mun(inputEl, ename, onChangeEvent);
+ }
+ me.callParent(arguments);
+ if (usesPropertychange) {
+ me.mon(inputEl, ename, onChangeEvent);
+ }
+ },
+
+ /**
+ * @private Called when the field's dirty state changes. Adds/removes the {@link #dirtyCls} on the main element.
+ * @param {Boolean} isDirty
+ */
+ onDirtyChange: function(isDirty) {
+ this[isDirty ? 'addCls' : 'removeCls'](this.dirtyCls);
+ },
+
+
+ /**
+ * Returns whether or not the field value is currently valid by {@link #getErrors validating} the
+ * {@link #processRawValue processed raw value} of the field. **Note**: {@link #disabled} fields are
+ * always treated as valid.
+ *
+ * @return {Boolean} True if the value is valid, else false
+ */
+ isValid : function() {
+ var me = this,
+ disabled = me.disabled,
+ validate = me.forceValidation || !disabled;
+
+
+ return validate ? me.validateValue(me.processRawValue(me.getRawValue())) : disabled;
+ },
+
+
+ /**
+ * Uses {@link #getErrors} to build an array of validation errors. If any errors are found, they are passed to
+ * {@link #markInvalid} and false is returned, otherwise true is returned.
+ *
+ * Previously, subclasses were invited to provide an implementation of this to process validations - from 3.2
+ * onwards {@link #getErrors} should be overridden instead.
+ *
+ * @param {Object} value The value to validate
+ * @return {Boolean} True if all validations passed, false if one or more failed
+ */
+ validateValue: function(value) {
+ var me = this,
+ errors = me.getErrors(value),
+ isValid = Ext.isEmpty(errors);
+ if (!me.preventMark) {
+ if (isValid) {
+ me.clearInvalid();
+ } else {
+ me.markInvalid(errors);
+ }
+ }
+
+ return isValid;
+ },
+
+ /**
+ * Display one or more error messages associated with this field, using {@link #msgTarget} to determine how to
+ * display the messages and applying {@link #invalidCls} to the field's UI element.
+ *
+ * **Note**: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to return `false`
+ * if the value does _pass_ validation. So simply marking a Field as invalid will not prevent submission of forms
+ * submitted with the {@link Ext.form.action.Submit#clientValidation} option set.
+ *
+ * @param {String/String[]} errors The validation message(s) to display.
+ */
+ markInvalid : function(errors) {
+ // Save the message and fire the 'invalid' event
+ var me = this,
+ oldMsg = me.getActiveError();
+ me.setActiveErrors(Ext.Array.from(errors));
+ if (oldMsg !== me.getActiveError()) {
+ me.updateLayout();
+ }
+ },
+
+ /**
+ * Clear any invalid styles/messages for this field.
+ *
+ * **Note**: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to return `true`
+ * if the value does not _pass_ validation. So simply clearing a field's errors will not necessarily allow
+ * submission of forms submitted with the {@link Ext.form.action.Submit#clientValidation} option set.
+ */
+ clearInvalid : function() {
+ // Clear the message and fire the 'valid' event
+ var me = this,
+ hadError = me.hasActiveError();
+ me.unsetActiveError();
+ if (hadError) {
+ me.updateLayout();
+ }
+ },
+
+ /**
+ * @private Overrides the method from the Ext.form.Labelable mixin to also add the invalidCls to the inputEl,
+ * as that is required for proper styling in IE with nested fields (due to lack of child selector)
+ */
+ renderActiveError: function() {
+ var me = this,
+ hasError = me.hasActiveError();
+ if (me.inputEl) {
+ // Add/remove invalid class
+ me.inputEl[hasError ? 'addCls' : 'removeCls'](me.invalidCls + '-field');
+ }
+ me.mixins.labelable.renderActiveError.call(me);
+ },
+
+
+ getActionEl: function() {
+ return this.inputEl || this.el;
+ }
+
+});
+
+/**
+ * @singleton
+ * @alternateClassName Ext.form.VTypes
+ *
+ * This is a singleton object which contains a set of commonly used field validation functions
+ * and provides a mechanism for creating reusable custom field validations.
+ * The following field validation functions are provided out of the box:
+ *
+ * - {@link #alpha}
+ * - {@link #alphanum}
+ * - {@link #email}
+ * - {@link #url}
+ *
+ * VTypes can be applied to a {@link Ext.form.field.Text Text Field} using the `{@link Ext.form.field.Text#vtype vtype}` configuration:
+ *
+ * Ext.create('Ext.form.field.Text', {
+ * fieldLabel: 'Email Address',
+ * name: 'email',
+ * vtype: 'email' // applies email validation rules to this field
+ * });
+ *
+ * To create custom VTypes:
+ *
+ * // custom Vtype for vtype:'time'
+ * var timeTest = /^([1-9]|1[0-9]):([0-5][0-9])(\s[a|p]m)$/i;
+ * Ext.apply(Ext.form.field.VTypes, {
+ * // vtype validation function
+ * time: function(val, field) {
+ * return timeTest.test(val);
+ * },
+ * // vtype Text property: The error text to display when the validation function returns false
+ * timeText: 'Not a valid time. Must be in the format "12:34 PM".',
+ * // vtype Mask property: The keystroke filter mask
+ * timeMask: /[\d\s:amp]/i
+ * });
+ *
+ * In the above example the `time` function is the validator that will run when field validation occurs,
+ * `timeText` is the error message, and `timeMask` limits what characters can be typed into the field.
+ * Note that the `Text` and `Mask` functions must begin with the same name as the validator function.
+ *
+ * Using a custom validator is the same as using one of the build-in validators - just use the name of the validator function
+ * as the `{@link Ext.form.field.Text#vtype vtype}` configuration on a {@link Ext.form.field.Text Text Field}:
+ *
+ * Ext.create('Ext.form.field.Text', {
+ * fieldLabel: 'Departure Time',
+ * name: 'departureTime',
+ * vtype: 'time' // applies custom time validation rules to this field
+ * });
+ *
+ * Another example of a custom validator:
+ *
+ * // custom Vtype for vtype:'IPAddress'
+ * Ext.apply(Ext.form.field.VTypes, {
+ * IPAddress: function(v) {
+ * return /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v);
+ * },
+ * IPAddressText: 'Must be a numeric IP address',
+ * IPAddressMask: /[\d\.]/i
+ * });
+ *
+ * It's important to note that using {@link Ext#apply Ext.apply()} means that the custom validator function
+ * as well as `Text` and `Mask` fields are added as properties of the `Ext.form.field.VTypes` singleton.
+ */
+Ext.define('Ext.form.field.VTypes', (function(){
+ // closure these in so they are only created once.
+ var alpha = /^[a-zA-Z_]+$/,
+ alphanum = /^[a-zA-Z0-9_]+$/,
+ email = /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/,
+ url = /(((^https?)|(^ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@`~=%!]*)(\.\w{2,})?)*\/?)/i;
+
+ // All these messages and functions are configurable
+ return {
+ singleton: true,
+ alternateClassName: 'Ext.form.VTypes',
+
+ /**
+ * The function used to validate email addresses. Note that this is a very basic validation - complete
+ * validation per the email RFC specifications is very complex and beyond the scope of this class, although this
+ * function can be overridden if a more comprehensive validation scheme is desired. See the validation section
+ * of the [Wikipedia article on email addresses][1] for additional information. This implementation is intended
+ * to validate the following emails:
+ *
+ * - `barney@example.de`
+ * - `barney.rubble@example.com`
+ * - `barney-rubble@example.coop`
+ * - `barney+rubble@example.com`
+ *
+ * [1]: http://en.wikipedia.org/wiki/E-mail_address
+ *
+ * @param {String} value The email address
+ * @return {Boolean} true if the RegExp test passed, and false if not.
+ */
+ 'email' : function(v){
+ return email.test(v);
+ },
+ //
+ /**
+ * @property {String} emailText
+ * The error text to display when the email validation function returns false.
+ * Defaults to: 'This field should be an e-mail address in the format "user@example.com"'
+ */
+ 'emailText' : 'This field should be an e-mail address in the format "user@example.com"',
+ //
+ /**
+ * @property {RegExp} emailMask
+ * The keystroke filter mask to be applied on email input. See the {@link #email} method for information about
+ * more complex email validation. Defaults to: /[a-z0-9_\.\-@]/i
+ */
+ 'emailMask' : /[a-z0-9_\.\-@\+]/i,
+
+ /**
+ * The function used to validate URLs
+ * @param {String} value The URL
+ * @return {Boolean} true if the RegExp test passed, and false if not.
+ */
+ 'url' : function(v){
+ return url.test(v);
+ },
+ //
+ /**
+ * @property {String} urlText
+ * The error text to display when the url validation function returns false.
+ * Defaults to: 'This field should be a URL in the format "http:/'+'/www.example.com"'
+ */
+ 'urlText' : 'This field should be a URL in the format "http:/'+'/www.example.com"',
+ //
+
+ /**
+ * The function used to validate alpha values
+ * @param {String} value The value
+ * @return {Boolean} true if the RegExp test passed, and false if not.
+ */
+ 'alpha' : function(v){
+ return alpha.test(v);
+ },
+ //
+ /**
+ * @property {String} alphaText
+ * The error text to display when the alpha validation function returns false.
+ * Defaults to: 'This field should only contain letters and _'
+ */
+ 'alphaText' : 'This field should only contain letters and _',
+ //
+ /**
+ * @property {RegExp} alphaMask
+ * The keystroke filter mask to be applied on alpha input. Defaults to: /[a-z_]/i
+ */
+ 'alphaMask' : /[a-z_]/i,
+
+ /**
+ * The function used to validate alphanumeric values
+ * @param {String} value The value
+ * @return {Boolean} true if the RegExp test passed, and false if not.
+ */
+ 'alphanum' : function(v){
+ return alphanum.test(v);
+ },
+ //
+ /**
+ * @property {String} alphanumText
+ * The error text to display when the alphanumeric validation function returns false.
+ * Defaults to: 'This field should only contain letters, numbers and _'
+ */
+ 'alphanumText' : 'This field should only contain letters, numbers and _',
+ //
+ /**
+ * @property {RegExp} alphanumMask
+ * The keystroke filter mask to be applied on alphanumeric input. Defaults to: /[a-z0-9_]/i
+ */
+ 'alphanumMask' : /[a-z0-9_]/i
+ };
+}()));
+
+/**
+ * @docauthor Jason Johnston
+ *
+ * A basic text field. Can be used as a direct replacement for traditional text inputs,
+ * or as the base class for more sophisticated input controls (like {@link Ext.form.field.TextArea}
+ * and {@link Ext.form.field.ComboBox}). Has support for empty-field placeholder values (see {@link #emptyText}).
+ *
+ * # Validation
+ *
+ * The Text field has a useful set of validations built in:
+ *
+ * - {@link #allowBlank} for making the field required
+ * - {@link #minLength} for requiring a minimum value length
+ * - {@link #maxLength} for setting a maximum value length (with {@link #enforceMaxLength} to add it
+ * as the `maxlength` attribute on the input element)
+ * - {@link #regex} to specify a custom regular expression for validation
+ *
+ * In addition, custom validations may be added:
+ *
+ * - {@link #vtype} specifies a virtual type implementation from {@link Ext.form.field.VTypes} which can contain
+ * custom validation logic
+ * - {@link #validator} allows a custom arbitrary function to be called during validation
+ *
+ * The details around how and when each of these validation options get used are described in the
+ * documentation for {@link #getErrors}.
+ *
+ * By default, the field value is checked for validity immediately while the user is typing in the
+ * field. This can be controlled with the {@link #validateOnChange}, {@link #checkChangeEvents}, and
+ * {@link #checkChangeBuffer} configurations. Also see the details on Form Validation in the
+ * {@link Ext.form.Panel} class documentation.
+ *
+ * # Masking and Character Stripping
+ *
+ * Text fields can be configured with custom regular expressions to be applied to entered values before
+ * validation: see {@link #maskRe} and {@link #stripCharsRe} for details.
+ *
+ * # Example usage
+ *
+ * @example
+ * Ext.create('Ext.form.Panel', {
+ * title: 'Contact Info',
+ * width: 300,
+ * bodyPadding: 10,
+ * renderTo: Ext.getBody(),
+ * items: [{
+ * xtype: 'textfield',
+ * name: 'name',
+ * fieldLabel: 'Name',
+ * allowBlank: false // requires a non-empty value
+ * }, {
+ * xtype: 'textfield',
+ * name: 'email',
+ * fieldLabel: 'Email Address',
+ * vtype: 'email' // requires value to be a valid email address format
+ * }]
+ * });
+ */
+Ext.define('Ext.form.field.Text', {
+ extend:'Ext.form.field.Base',
+ alias: 'widget.textfield',
+ requires: ['Ext.form.field.VTypes', 'Ext.layout.component.field.Text'],
+ alternateClassName: ['Ext.form.TextField', 'Ext.form.Text'],
+
+ /**
+ * @cfg {String} vtypeText
+ * A custom error message to display in place of the default message provided for the **`{@link #vtype}`** currently
+ * set for this field. **Note**: only applies if **`{@link #vtype}`** is set, else ignored.
+ */
+
+ /**
+ * @cfg {RegExp} stripCharsRe
+ * A JavaScript RegExp object used to strip unwanted content from the value
+ * during input. If `stripCharsRe` is specified,
+ * every *character sequence* matching `stripCharsRe` will be removed.
+ */
+
+ /**
+ * @cfg {Number} size
+ * An initial value for the 'size' attribute on the text input element. This is only used if the field has no
+ * configured {@link #width} and is not given a width by its container's layout. Defaults to 20.
+ */
+ size: 20,
+
+ /**
+ * @cfg {Boolean} [grow=false]
+ * true if this field should automatically grow and shrink to its content
+ */
+
+ /**
+ * @cfg {Number} growMin
+ * The minimum width to allow when `{@link #grow} = true`
+ */
+ growMin : 30,
+
+ /**
+ * @cfg {Number} growMax
+ * The maximum width to allow when `{@link #grow} = true`
+ */
+ growMax : 800,
+
+ //
+ /**
+ * @cfg {String} growAppend
+ * A string that will be appended to the field's current value for the purposes of calculating the target field
+ * size. Only used when the {@link #grow} config is true. Defaults to a single capital "W" (the widest character in
+ * common fonts) to leave enough space for the next typed character and avoid the field value shifting before the
+ * width is adjusted.
+ */
+ growAppend: 'W',
+ //
+
+ /**
+ * @cfg {String} vtype
+ * A validation type name as defined in {@link Ext.form.field.VTypes}
+ */
+
+ /**
+ * @cfg {RegExp} maskRe An input mask regular expression that will be used to filter keystrokes (character being
+ * typed) that do not match.
+ * Note: It does not filter characters already in the input.
+ */
+
+ /**
+ * @cfg {Boolean} [disableKeyFilter=false]
+ * Specify true to disable input keystroke filtering
+ */
+
+ /**
+ * @cfg {Boolean} allowBlank
+ * Specify false to validate that the value's length is > 0
+ */
+ allowBlank : true,
+
+ /**
+ * @cfg {Number} minLength
+ * Minimum input field length required
+ */
+ minLength : 0,
+
+ /**
+ * @cfg {Number} maxLength
+ * Maximum input field length allowed by validation. This behavior is intended to
+ * provide instant feedback to the user by improving usability to allow pasting and editing or overtyping and back
+ * tracking. To restrict the maximum number of characters that can be entered into the field use the
+ * **{@link Ext.form.field.Text#enforceMaxLength enforceMaxLength}** option.
+ *
+ * Defaults to Number.MAX_VALUE.
+ */
+ maxLength : Number.MAX_VALUE,
+
+ /**
+ * @cfg {Boolean} enforceMaxLength
+ * True to set the maxLength property on the underlying input field. Defaults to false
+ */
+
+ /**
+ * @cfg {String} minLengthText
+ * Error text to display if the **{@link #minLength minimum length}** validation fails.
+ */
+ //
+ minLengthText : 'The minimum length for this field is {0}',
+ //
+
+ //
+ /**
+ * @cfg {String} maxLengthText
+ * Error text to display if the **{@link #maxLength maximum length}** validation fails
+ */
+ maxLengthText : 'The maximum length for this field is {0}',
+ //
+
+ /**
+ * @cfg {Boolean} [selectOnFocus=false]
+ * true to automatically select any existing field text when the field receives input focus
+ */
+
+ //
+ /**
+ * @cfg {String} blankText
+ * The error text to display if the **{@link #allowBlank}** validation fails
+ */
+ blankText : 'This field is required',
+ //
+
+ /**
+ * @cfg {Function} validator
+ * A custom validation function to be called during field validation ({@link #getErrors}).
+ * If specified, this function will be called first, allowing the developer to override the default validation
+ * process.
+ *
+ * This function will be passed the following parameters:
+ *
+ * @cfg {Object} validator.value The current field value
+ * @cfg {Boolean/String} validator.return
+ *
+ * - True if the value is valid
+ * - An error message if the value is invalid
+ */
+
+ /**
+ * @cfg {RegExp} regex
+ * A JavaScript RegExp object to be tested against the field value during validation.
+ * If the test fails, the field will be marked invalid using
+ * either **{@link #regexText}** or **{@link #invalidText}**.
+ */
+
+ /**
+ * @cfg {String} regexText
+ * The error text to display if **{@link #regex}** is used and the test fails during validation
+ */
+ regexText : '',
+
+ /**
+ * @cfg {String} emptyText
+ * The default text to place into an empty field.
+ *
+ * Note that normally this value will be submitted to the server if this field is enabled; to prevent this you can
+ * set the {@link Ext.form.action.Action#submitEmptyText submitEmptyText} option of {@link Ext.form.Basic#submit} to
+ * false.
+ *
+ * Also note that if you use {@link #inputType inputType}:'file', {@link #emptyText} is not supported and should be
+ * avoided.
+ *
+ * Note that for browsers that support it, setting this property will use the HTML 5 placeholder attribute, and for
+ * older browsers that don't support the HTML 5 placeholder attribute the value will be placed directly into the input
+ * element itself as the raw value. This means that older browsers will obfuscate the {@link #emptyText} value for
+ * password input fields.
+ */
+
+ /**
+ * @cfg {String} [emptyCls='x-form-empty-field']
+ * The CSS class to apply to an empty field to style the **{@link #emptyText}**.
+ * This class is automatically added and removed as needed depending on the current field value.
+ */
+ emptyCls : Ext.baseCSSPrefix + 'form-empty-field',
+
+ /**
+ * @cfg {String} [requiredCls='x-form-required-field']
+ * The CSS class to apply to a required field, i.e. a field where **{@link #allowBlank}** is false.
+ */
+ requiredCls : Ext.baseCSSPrefix + 'form-required-field',
+
+ /**
+ * @cfg {Boolean} [enableKeyEvents=false]
+ * true to enable the proxying of key events for the HTML input field
+ */
+
+ componentLayout: 'textfield',
+
+ // private
+ valueContainsPlaceholder : false,
+
+
+ initComponent: function () {
+ var me = this;
+
+ me.callParent();
+
+ me.addEvents(
+ /**
+ * @event autosize
+ * Fires when the **{@link #autoSize}** function is triggered and the field is resized according to the
+ * {@link #grow}/{@link #growMin}/{@link #growMax} configs as a result. This event provides a hook for the
+ * developer to apply additional logic at runtime to resize the field if needed.
+ * @param {Ext.form.field.Text} this This text field
+ * @param {Number} width The new field width
+ */
+ 'autosize',
+
+ /**
+ * @event keydown
+ * Keydown input field event. This event only fires if **{@link #enableKeyEvents}** is set to true.
+ * @param {Ext.form.field.Text} this This text field
+ * @param {Ext.EventObject} e
+ */
+ 'keydown',
+ /**
+ * @event keyup
+ * Keyup input field event. This event only fires if **{@link #enableKeyEvents}** is set to true.
+ * @param {Ext.form.field.Text} this This text field
+ * @param {Ext.EventObject} e
+ */
+ 'keyup',
+ /**
+ * @event keypress
+ * Keypress input field event. This event only fires if **{@link #enableKeyEvents}** is set to true.
+ * @param {Ext.form.field.Text} this This text field
+ * @param {Ext.EventObject} e
+ */
+ 'keypress'
+ );
+ me.addStateEvents('change');
+ me.setGrowSizePolicy();
+ },
+
+ // private
+ setGrowSizePolicy: function(){
+ if (this.grow) {
+ this.shrinkWrap |= 1; // width must shrinkWrap
+ }
+ },
+
+ // private
+ initEvents : function(){
+ var me = this,
+ el = me.inputEl;
+
+ me.callParent();
+ if(me.selectOnFocus || me.emptyText){
+ me.mon(el, 'mousedown', me.onMouseDown, me);
+ }
+ if(me.maskRe || (me.vtype && me.disableKeyFilter !== true && (me.maskRe = Ext.form.field.VTypes[me.vtype+'Mask']))){
+ me.mon(el, 'keypress', me.filterKeys, me);
+ }
+
+ if (me.enableKeyEvents) {
+ me.mon(el, {
+ scope: me,
+ keyup: me.onKeyUp,
+ keydown: me.onKeyDown,
+ keypress: me.onKeyPress
+ });
+ }
+ },
+
+ /**
+ * @private
+ * Override. Treat undefined and null values as equal to an empty string value.
+ */
+ isEqual: function(value1, value2) {
+ return this.isEqualAsString(value1, value2);
+ },
+
+ /**
+ * @private
+ * If grow=true, invoke the autoSize method when the field's value is changed.
+ */
+ onChange: function() {
+ this.callParent();
+ this.autoSize();
+ },
+
+ getSubTplData: function() {
+ var me = this,
+ value = me.getRawValue(),
+ isEmpty = me.emptyText && value.length < 1,
+ maxLength = me.maxLength,
+ placeholder;
+
+ // We can't just dump the value here, since MAX_VALUE ends up
+ // being something like 1.xxxxe+300, which gets interpreted as 1
+ // in the markup
+ if (me.enforceMaxLength) {
+ if (maxLength === Number.MAX_VALUE) {
+ maxLength = undefined;
+ }
+ } else {
+ maxLength = undefined;
+ }
+
+ if (isEmpty) {
+ if (Ext.supports.Placeholder) {
+ placeholder = me.emptyText;
+ } else {
+ value = me.emptyText;
+ me.valueContainsPlaceholder = true;
+ }
+ }
+
+ return Ext.apply(me.callParent(), {
+ maxLength : maxLength,
+ readOnly : me.readOnly,
+ placeholder : placeholder,
+ value : value,
+ fieldCls : me.fieldCls + ((isEmpty && (placeholder || value)) ? ' ' + me.emptyCls : '') + (me.allowBlank ? '' : ' ' + me.requiredCls)
+ });
+ },
+
+ afterRender: function(){
+ this.autoSize();
+ this.callParent();
+ },
+
+ onMouseDown: function(e){
+ var me = this;
+ if(!me.hasFocus){
+ me.mon(me.inputEl, 'mouseup', Ext.emptyFn, me, { single: true, preventDefault: true });
+ }
+ },
+
+ /**
+ * Performs any necessary manipulation of a raw String value to prepare it for conversion and/or
+ * {@link #validate validation}. For text fields this applies the configured {@link #stripCharsRe}
+ * to the raw value.
+ * @param {String} value The unprocessed string value
+ * @return {String} The processed string value
+ */
+ processRawValue: function(value) {
+ var me = this,
+ stripRe = me.stripCharsRe,
+ newValue;
+
+ if (stripRe) {
+ newValue = value.replace(stripRe, '');
+ if (newValue !== value) {
+ me.setRawValue(newValue);
+ value = newValue;
+ }
+ }
+ return value;
+ },
+
+ //private
+ onDisable: function(){
+ this.callParent();
+ if (Ext.isIE) {
+ this.inputEl.dom.unselectable = 'on';
+ }
+ },
+
+ //private
+ onEnable: function(){
+ this.callParent();
+ if (Ext.isIE) {
+ this.inputEl.dom.unselectable = '';
+ }
+ },
+
+ onKeyDown: function(e) {
+ this.fireEvent('keydown', this, e);
+ },
+
+ onKeyUp: function(e) {
+ this.fireEvent('keyup', this, e);
+ },
+
+ onKeyPress: function(e) {
+ this.fireEvent('keypress', this, e);
+ },
+
+ /**
+ * Resets the current field value to the originally-loaded value and clears any validation messages.
+ * Also adds **{@link #emptyText}** and **{@link #emptyCls}** if the original value was blank.
+ */
+ reset : function(){
+ this.callParent();
+ this.applyEmptyText();
+ },
+
+ applyEmptyText : function(){
+ var me = this,
+ emptyText = me.emptyText,
+ isEmpty;
+
+ if (me.rendered && emptyText) {
+ isEmpty = me.getRawValue().length < 1 && !me.hasFocus;
+
+ if (Ext.supports.Placeholder) {
+ me.inputEl.dom.placeholder = emptyText;
+ } else if (isEmpty) {
+ me.setRawValue(emptyText);
+ me.valueContainsPlaceholder = true;
+ }
+
+ //all browsers need this because of a styling issue with chrome + placeholders.
+ //the text isnt vertically aligned when empty (and using the placeholder)
+ if (isEmpty) {
+ me.inputEl.addCls(me.emptyCls);
+ }
+
+ me.autoSize();
+ }
+ },
+
+ afterFirstLayout: function() {
+ this.callParent();
+ if (Ext.isIE && this.disabled) {
+ var el = this.inputEl;
+ if (el) {
+ el.dom.unselectable = 'on';
+ }
+ }
+ },
+
+ // private
+ preFocus : function(){
+ var me = this,
+ inputEl = me.inputEl,
+ emptyText = me.emptyText,
+ isEmpty;
+
+ me.callParent(arguments);
+ if ((emptyText && !Ext.supports.Placeholder) && (inputEl.dom.value === me.emptyText && me.valueContainsPlaceholder)) {
+ me.setRawValue('');
+ isEmpty = true;
+ inputEl.removeCls(me.emptyCls);
+ me.valueContainsPlaceholder = false;
+ } else if (Ext.supports.Placeholder) {
+ me.inputEl.removeCls(me.emptyCls);
+ }
+ if (me.selectOnFocus || isEmpty) {
+ inputEl.dom.select();
+ }
+ },
+
+ onFocus: function() {
+ var me = this;
+ me.callParent(arguments);
+ if (me.emptyText) {
+ me.autoSize();
+ }
+ },
+
+ // private
+ postBlur : function(){
+ this.callParent(arguments);
+ this.applyEmptyText();
+ },
+
+ // private
+ filterKeys : function(e){
+ /*
+ * On European keyboards, the right alt key, Alt Gr, is used to type certain special characters.
+ * JS detects a keypress of this as ctrlKey & altKey. As such, we check that alt isn't pressed
+ * so we can still process these special characters.
+ */
+ if (e.ctrlKey && !e.altKey) {
+ return;
+ }
+ var key = e.getKey(),
+ charCode = String.fromCharCode(e.getCharCode());
+
+ if((Ext.isGecko || Ext.isOpera) && (e.isNavKeyPress() || key === e.BACKSPACE || (key === e.DELETE && e.button === -1))){
+ return;
+ }
+
+ if((!Ext.isGecko && !Ext.isOpera) && e.isSpecialKey() && !charCode){
+ return;
+ }
+ if(!this.maskRe.test(charCode)){
+ e.stopEvent();
+ }
+ },
+
+ getState: function() {
+ return this.addPropertyToState(this.callParent(), 'value');
+ },
+
+ applyState: function(state) {
+ this.callParent(arguments);
+ if(state.hasOwnProperty('value')) {
+ this.setValue(state.value);
+ }
+ },
+
+ /**
+ * Returns the raw String value of the field, without performing any normalization, conversion, or validation. Gets
+ * the current value of the input element if the field has been rendered, ignoring the value if it is the
+ * {@link #emptyText}. To get a normalized and converted value see {@link #getValue}.
+ * @return {String} The raw String value of the field
+ */
+ getRawValue: function() {
+ var me = this,
+ v = me.callParent();
+ if (v === me.emptyText && me.valueContainsPlaceholder) {
+ v = '';
+ }
+ return v;
+ },
+
+ /**
+ * Sets a data value into the field and runs the change detection and validation. Also applies any configured
+ * {@link #emptyText} for text fields. To set the value directly without these inspections see {@link #setRawValue}.
+ * @param {Object} value The value to set
+ * @return {Ext.form.field.Text} this
+ */
+ setValue: function(value) {
+ var me = this,
+ inputEl = me.inputEl;
+
+ if (inputEl && me.emptyText && !Ext.isEmpty(value)) {
+ inputEl.removeCls(me.emptyCls);
+ me.valueContainsPlaceholder = false;
+ }
+
+ me.callParent(arguments);
+
+ me.applyEmptyText();
+ return me;
+ },
+
+ /**
+ * Validates a value according to the field's validation rules and returns an array of errors
+ * for any failing validations. Validation rules are processed in the following order:
+ *
+ * 1. **Field specific validator**
+ *
+ * A validator offers a way to customize and reuse a validation specification.
+ * If a field is configured with a `{@link #validator}`
+ * function, it will be passed the current field value. The `{@link #validator}`
+ * function is expected to return either:
+ *
+ * - Boolean `true` if the value is valid (validation continues).
+ * - a String to represent the invalid message if invalid (validation halts).
+ *
+ * 2. **Basic Validation**
+ *
+ * If the `{@link #validator}` has not halted validation,
+ * basic validation proceeds as follows:
+ *
+ * - `{@link #allowBlank}` : (Invalid message = `{@link #blankText}`)
+ *
+ * Depending on the configuration of `{@link #allowBlank}`, a
+ * blank field will cause validation to halt at this step and return
+ * Boolean true or false accordingly.
+ *
+ * - `{@link #minLength}` : (Invalid message = `{@link #minLengthText}`)
+ *
+ * If the passed value does not satisfy the `{@link #minLength}`
+ * specified, validation halts.
+ *
+ * - `{@link #maxLength}` : (Invalid message = `{@link #maxLengthText}`)
+ *
+ * If the passed value does not satisfy the `{@link #maxLength}`
+ * specified, validation halts.
+ *
+ * 3. **Preconfigured Validation Types (VTypes)**
+ *
+ * If none of the prior validation steps halts validation, a field
+ * configured with a `{@link #vtype}` will utilize the
+ * corresponding {@link Ext.form.field.VTypes VTypes} validation function.
+ * If invalid, either the field's `{@link #vtypeText}` or
+ * the VTypes vtype Text property will be used for the invalid message.
+ * Keystrokes on the field will be filtered according to the VTypes
+ * vtype Mask property.
+ *
+ * 4. **Field specific regex test**
+ *
+ * If none of the prior validation steps halts validation, a field's
+ * configured `{@link #regex}` test will be processed.
+ * The invalid message for this test is configured with `{@link #regexText}`
+ *
+ * @param {Object} value The value to validate. The processed raw value will be used if nothing is passed.
+ * @return {String[]} Array of any validation errors
+ */
+ getErrors: function(value) {
+ var me = this,
+ errors = me.callParent(arguments),
+ validator = me.validator,
+ emptyText = me.emptyText,
+ allowBlank = me.allowBlank,
+ vtype = me.vtype,
+ vtypes = Ext.form.field.VTypes,
+ regex = me.regex,
+ format = Ext.String.format,
+ msg;
+
+ value = value || me.processRawValue(me.getRawValue());
+
+ if (Ext.isFunction(validator)) {
+ msg = validator.call(me, value);
+ if (msg !== true) {
+ errors.push(msg);
+ }
+ }
+
+ if (value.length < 1 || (value === me.emptyText && me.valueContainsPlaceholder)) {
+ if (!allowBlank) {
+ errors.push(me.blankText);
+ }
+ //if value is blank, there cannot be any additional errors
+ return errors;
+ }
+
+ if (value.length < me.minLength) {
+ errors.push(format(me.minLengthText, me.minLength));
+ }
+
+ if (value.length > me.maxLength) {
+ errors.push(format(me.maxLengthText, me.maxLength));
+ }
+
+ if (vtype) {
+ if(!vtypes[vtype](value, me)){
+ errors.push(me.vtypeText || vtypes[vtype +'Text']);
+ }
+ }
+
+ if (regex && !regex.test(value)) {
+ errors.push(me.regexText || me.invalidText);
+ }
+
+ return errors;
+ },
+
+ /**
+ * Selects text in this field
+ * @param {Number} [start=0] The index where the selection should start
+ * @param {Number} [end] The index where the selection should end (defaults to the text length)
+ */
+ selectText : function(start, end){
+ var me = this,
+ v = me.getRawValue(),
+ doFocus = true,
+ el = me.inputEl.dom,
+ undef,
+ range;
+
+ if (v.length > 0) {
+ start = start === undef ? 0 : start;
+ end = end === undef ? v.length : end;
+ if (el.setSelectionRange) {
+ el.setSelectionRange(start, end);
+ }
+ else if(el.createTextRange) {
+ range = el.createTextRange();
+ range.moveStart('character', start);
+ range.moveEnd('character', end - v.length);
+ range.select();
+ }
+ doFocus = Ext.isGecko || Ext.isOpera;
+ }
+ if (doFocus) {
+ me.focus();
+ }
+ },
+
+ /**
+ * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed. This
+ * only takes effect if {@link #grow} = true, and fires the {@link #autosize} event if the width changes.
+ */
+ autoSize: function() {
+ var me = this;
+ if (me.grow && me.rendered) {
+ me.autoSizing = true;
+ me.updateLayout();
+ }
+ },
+
+ afterComponentLayout: function() {
+ var me = this,
+ width;
+
+ me.callParent(arguments);
+ if (me.autoSizing) {
+ width = me.inputEl.getWidth();
+ if (width !== me.lastInputWidth) {
+ me.fireEvent('autosize', me, width);
+ me.lastInputWidth = width;
+ delete me.autoSizing;
+ }
+ }
+ }
+});
+
+/**
+ * Layout class for {@link Ext.form.field.TextArea} fields. Handles sizing the textarea field.
+ * @private
+ */
+Ext.define('Ext.layout.component.field.TextArea', {
+ extend: 'Ext.layout.component.field.Text',
+ alias: 'layout.textareafield',
+
+ type: 'textareafield',
+
+ canGrowWidth: false,
+
+ naturalSizingProp: 'cols',
+
+ beginLayout: function(ownerContext){
+ this.callParent(arguments);
+ ownerContext.target.inputEl.setStyle('height', '');
+ },
+
+ measureContentHeight: function (ownerContext) {
+ var me = this,
+ owner = me.owner,
+ height = me.callParent(arguments),
+ inputContext, inputEl, value, max, curWidth, calcHeight;
+
+ if (owner.grow && !ownerContext.state.growHandled) {
+ inputContext = ownerContext.inputContext;
+ inputEl = owner.inputEl;
+ curWidth = inputEl.getWidth(true); //subtract border/padding to get the available width for the text
+
+ // Get and normalize the field value for measurement
+ value = Ext.util.Format.htmlEncode(inputEl.dom.value) || ' ';
+ value += owner.growAppend;
+
+ // Translate newlines to tags
+ value = value.replace(/\n/g, ' ');
+
+ // Find the height that contains the whole text value
+ calcHeight = Ext.util.TextMetrics.measure(inputEl, value, curWidth).height +
+ inputContext.getBorderInfo().height + inputContext.getPaddingInfo().height;
+
+ // Constrain
+ calcHeight = Ext.Number.constrain(calcHeight, owner.growMin, owner.growMax);
+ inputContext.setHeight(calcHeight);
+ ownerContext.state.growHandled = true;
+
+ // Now that we've set the inputContext, we need to recalculate the width
+ inputContext.domBlock(me, 'height');
+ height = NaN;
+ }
+ return height;
+ }
+});
+
+/**
+ * @docauthor Robert Dougan
+ *
+ * This class creates a multiline text field, which can be used as a direct replacement for traditional
+ * textarea fields. In addition, it supports automatically {@link #grow growing} the height of the textarea to
+ * fit its content.
+ *
+ * All of the configuration options from {@link Ext.form.field.Text} can be used on TextArea.
+ *
+ * Example usage:
+ *
+ * @example
+ * Ext.create('Ext.form.FormPanel', {
+ * title : 'Sample TextArea',
+ * width : 400,
+ * bodyPadding: 10,
+ * renderTo : Ext.getBody(),
+ * items: [{
+ * xtype : 'textareafield',
+ * grow : true,
+ * name : 'message',
+ * fieldLabel: 'Message',
+ * anchor : '100%'
+ * }]
+ * });
+ *
+ * Some other useful configuration options when using {@link #grow} are {@link #growMin} and {@link #growMax}.
+ * These allow you to set the minimum and maximum grow heights for the textarea.
+ *
+ * **NOTE:** In some browsers, carriage returns ('\r', not to be confused with new lines)
+ * will be automatically stripped out the value is set to the textarea. Since we cannot
+ * use any reasonable method to attempt to re-insert these, they will automatically be
+ * stripped out to ensure the behaviour is consistent across browser.
+ */
+Ext.define('Ext.form.field.TextArea', {
+ extend:'Ext.form.field.Text',
+ alias: ['widget.textareafield', 'widget.textarea'],
+ alternateClassName: 'Ext.form.TextArea',
+ requires: [
+ 'Ext.XTemplate',
+ 'Ext.layout.component.field.TextArea',
+ 'Ext.util.DelayedTask'
+ ],
+
+ // This template includes a \n after